frostlake

2026-11-29

A dependency-free Common Lisp driver for the Frostlake database engine.

Upstream URL

github.com/Frostlake-DB/frostlake-lisp

Author

MLorek

License

Apache-2.0
README

frostlake-lisp

A dependency-free Common Lisp driver for Frostlake, speaking the engine's HTTP protocol against a running DatabaseHttpServer. No Quicklisp packages, no foreign library, nothing to build — frostlake.asd names no dependencies at all.

Standard Lisp has no sockets and no locks, so those live in one file (src/portability.lisp) behind read-time conditionals. Everything else — the JSON reader, the DSN parser, the SQL scanner, parameter binding, value conversion, the HTTP client — is portable ANSI Common Lisp.

Engine version

Requires a Frostlake engine 0.2.0 or newer. Ask a running server which one it is with (server-version conn) — every release answers it, so the check works against any engine.

The driver versions independently of the engine: it speaks the HTTP protocol, not the jar, so this is a floor rather than a lockstep pin.

Install

Not in Quicklisp yet. Clone it where ASDF will find it — ~/common-lisp/, ~/.local/share/common-lisp/source/, or Quicklisp's local-projects/ — and load it:

(asdf:load-system "frostlake")

Or point ASDF at a checkout anywhere:

(push #p"/path/to/frostlake-lisp/" asdf:*central-registry*)
(asdf:load-system "frostlake")

Usage

(use-package :frostlake)

(with-connection (conn "frostlake://localhost:18082/MY_DB?schema=PUBLIC")
  (execute conn "CREATE TABLE people (id INTEGER, name VARCHAR)")

  (result-update-count
   (execute conn "INSERT INTO people VALUES (?, ?), (?, ?)" 1 "Ada" 2 "Grace"))
  ;; => 2

  (scalar (execute conn "SELECT name FROM people WHERE id = ?" 1))
  ;; => "Ada"

  (do-rows (row (execute conn "SELECT id, name FROM people ORDER BY id"))
    (format t "~D ~A~%" (aref row 0) (aref row 1))))

connect contacts the server before it returns: it calls the health endpoint and applies the scope the DSN names, so a database that does not exist is reported there rather than surfacing later on whichever query happened to run first.

with-connection closes on the way out however the body leaves. (connect dsn) and (disconnect conn) are the explicit pair.

examples/basic.lisp is a runnable tour:

sbcl --script examples/basic.lisp frostlake://localhost:18082

DSN

frostlake://host[:port][/DATABASE][?param=value&…]

http:// is accepted too and means the same thing. Omitting the port means the engine's own default, 18082; for http it means 80. An IPv6 address goes in brackets: frostlake://[::1]:18082.

ParameterMeaningDefault
schemaschema to USE on the session—
rolerole to USE on the session—
warehousewarehouse to USE on the session—
timeouthow long one statement may take; 0 removes the bound5m
connectTimeouthow long to wait for the socket10s
idleLimithow long a connection may idle before its scope is re-applied, on an engine before 0.1.0 (see Session lifetime); 0 switches the check off30m
tlsaccepted, but see TLSfalse

Durations are a bare number of seconds or a number with an ms / s / m / h suffix, and are held exactly — 500ms is 1/2, not a float that drifts. timeout, connectTimeout and idleLimit may also be passed as keywords to connect, where they outrank the DSN.

An unknown parameter is refused rather than ignored: a typo in schema or timeout changes behaviour without saying so. Credentials are refused too — the server authenticates nobody, so a password in a DSN would be silently dropped, and silently dropping a password is worse than saying so.

Running statements

CallWhat it gives
(execute conn sql &rest parameters)the first result
(execute-all conn sql &rest parameters)every result, in order, for a ;-separated request
(execute* conn sql &key parameters multi-statement-count)the same, with its arguments named
(execute-all* conn sql &key parameters multi-statement-count)the same, with its arguments named
(query conn sql &rest parameters)the rows, each an alist of column name to cell
(scalar result)the first cell of the first row
(server-version conn)what SELECT CURRENT_VERSION() reports

A session runs one statement per request until it asks for more, so a ;-separated request is refused on its count rather than answered. :multi-statement-count declares how many this one request holds:

(execute-all* conn "SELECT 1; SELECT 2" :multi-statement-count 2)

0 means any number. The count travels with that one request and outranks the session's MULTI_STATEMENT_COUNT without changing it, so nothing has to be saved and put back, and two connections sharing nothing but the server cannot disturb each other. Leave the keyword out and no count is sent at all — the session's value, which (execute conn "ALTER SESSION SET MULTI_STATEMENT_COUNT = n") sets, decides as before.

execute* and execute-all* exist because a lambda list cannot both collect positional bind values with &rest and read keywords: they take the same call as execute and execute-all with its arguments named, :parameters being the list the &rest would have collected — or the one map params builds for :name markers.

A result holds:

AccessorWhat it holds
result-columnsa column per column, in order
result-valuesevery cell, a vector per row — the lossless view
result-rowsthe same rows as alists, built on first use and kept
result-update-countrows affected by DML, or -1 when the statement returned data
result-countersthe raw number of rows … counters behind it
result-cellone cell, by position or by column name
result-column-indexa column's position, matched exactly first, case-insensitively after
do-rowsiterate the rows

A column holds column-name, column-data-type, column-nullable, column-precision, column-scale and column-length — the declared width of a text or binary column, in characters for VARCHAR and bytes for BINARY. Every other type has no width and reports nil, as does a field an older engine never sent; an unbounded column reports the most it could hold (16777216), so there is nothing to guess.

result-rows is an alist rather than a hash table because a hash table cannot hold two columns called the same thing — a self-join reports ID twice. assoc answers with the first, the second is still there to be found, and result-values stays lossless either way.

A DML statement answers with a status grid rather than data — one row of number of rows inserted-style counters. That grid is reported as it arrived; result-update-count is the friendly reading of it.

Parameters

The protocol has no server-side binding, so parameters are inlined client-side with the same rules Frostlake's JDBC driver uses. Positional ? markers take the arguments themselves:

(execute conn "INSERT INTO people VALUES (?, ?)" 1 "Ada")

and :name markers take one map, which params builds:

(execute conn "SELECT :a + :b AS total" (params :a 2 :b 40))

The count has to match in both directions: a placeholder left without an argument is an error, never a silently bound NULL. A statement may use one style or the other, not both.

Markers inside string literals, quoted identifiers, dollar-quoted bodies and comments are left alone, and so is Snowflake's v:field VARIANT path syntax, a :: cast and a := assignment. With no arguments at all a statement passes through verbatim, which is what leaves server-side markers — a Scripting EXECUTE IMMEDIATE :v, a cursor's OPEN c USING (?) — for the server.

query-error-statement holds the SQL after substitution, so a bound password or card number appears in it verbatim. The condition's message and printed form carry none of it: log those freely, treat the statement as secret.

Types

Reading, guided by the column's declared type:

SQLLisp
NUMBER(p,0), INTEGER, BIGINTinteger — exact at any width
NUMBER(p,s), DECIMALrational — exact; (float x 1d0) when you want a float
FLOAT, DOUBLE, REALdouble-float
VARCHAR, VARIANT, OBJECT, ARRAYstring (the engine renders the last three as text)
BOOLEANt / nil
NULL:null
DATEsql-date
TIMEsql-time
TIMESTAMP, TIMESTAMP_NTZ, DATETIMEsql-timestamp
TIMESTAMP_TZ, TIMESTAMP_LTZzoned-timestamp
BINARY, VARBINARY(vector (unsigned-byte 8))

and writing, when binding:

LispSQL literal
:nullNULL
t / nilTRUE / FALSE
integerthe digits, exactly
ratioan exact decimal literal
floatthe shortest form that reads back the same; NaN and the infinities cast from text
string, character'…', backslashes and quotes escaped
(vector (unsigned-byte 8))X'hex'
sql-date / sql-time / sql-timestamp / zoned-timestamp'…'::DATE / ::TIME / ::TIMESTAMP_NTZ / ::TIMESTAMP_TZ
list, vector[…], elements formatted recursively
hash-table{'key': …}, values formatted recursively

Three of these are worth saying out loud.

Exact numbers. Common Lisp can hold a NUMBER(38,0) and a NUMBER(38,2) exactly, and a double-float cannot, so the driver keeps them: the JSON reader preserves each number's literal text and the column's declared type decides how to read it. 3.15 in a NUMBER(10,2) arrives as 63/20. Bind *exact-decimals* to nil for a double-float instead; approximate columns were never exact and are always double-float either way.

:null, not nil. nil is false, the empty list, and — on most people's fingers — the thing you test with; making it SQL NULL as well would collapse three answers into one. Bind *null-value* to nil for the terser reading once nothing downstream needs to tell them apart. The same rule runs backwards when binding: nil is FALSE, and an empty array has to be written #(), because '() is nil.

Temporals are structures, not universal times. ANSI's universal time starts in 1900, counts whole seconds, and has nowhere to put a zone — three things a SQL timestamp routinely needs. sql-date, sql-time, sql-timestamp and zoned-timestamp hold every field the wire carries. zoned-timestamp-utc gives the instant, which is what to compare two zoned values by; sql-timestamp-to-universal-time and universal-time-to-sql-timestamp bridge to the standard representation for callers who can accept what it drops.

Transactions

(with-transaction (conn)
  (execute conn "INSERT INTO acc VALUES (1)"))

BEGIN on the way in, COMMIT on a normal exit, ROLLBACK on any other — and the original condition is re-signalled either way. begin-transaction, commit and rollback are there for a transaction whose shape does not fit a block.

A transaction lives on the session, so the connection is not held for the duration: anything else run on this same connection meanwhile joins the transaction. Give a transaction its own connection if that is not what you want.

Session lifetime

A connection holds one engine session, named by the first answer (connection-session-id), and every later request carries its id.

What is sent. An engine from 0.1.0 on reports newSession in its answers, and the first answer that names a session tells the driver which kind it is talking to. From then on, every request that carries the id also carries requireSession: true: the engine resumes that session or refuses the request with a 404, and never runs the statement in a fresh session at its default scope. An older engine is never sent the field.

After a lost session. A session goes when it idles past the engine's expiry (30 minutes), when something releases it, or when the server restarts. On the 404 the driver drops the id, and then:

  • if the session held nothing a fresh one lacks, the DSN's scope (USE ROLE / WAREHOUSE / DATABASE / SCHEMA) goes on a fresh session and the statement is sent once more — the caller sees only its result. A second 404 in a row signals session-lost-error;
  • if a transaction was open — begin-transaction, or a BEGIN or START TRANSACTION statement — it went with the session, and session-lost-error says so. The statement did not run;
  • if the session had been moved or set up — USE, SET, UNSET, ALTER SESSION, a temporary object, a CREATE or DROP of a database or schema — that context went with it, and session-lost-error says so rather than run the statement somewhere its author did not intend. It did not run.

Either way the connection stays usable: the next statement starts a fresh session on the DSN's scope. An older engine gives no such signal — it quietly rebuilds an expired session under the same id — so against one the driver re-applies the DSN's scope after idleLimit of idling, unless the caller has moved the session themselves.

Putting a moved session back. (apply-dsn-scope conn) sends the DSN's USE statements again, in dependency order, and from then on the session counts as the DSN's once more: one lost after that is replaced and its statement sent again, and the idle re-scope resumes. Session variables, settings and temporary objects are not undone by it.

On disconnect. The session is released with DELETE /api/sessions/{id}, which also rolls back a transaction left open on it. It is a courtesy: bounded by the shorter of the statement timeout and five seconds, and nothing it meets — a 404, a refusal, a server that is gone or never answers — is signalled. A second disconnect sends nothing. An older engine has no such endpoint and is sent nothing; its idle sweep reclaims the session.

Errors

Every failure is a frostlake-error, so one handler catches the lot. The four subtypes are what a caller actually branches on:

ConditionMeans
query-errorthe engine rejected the statement. frostlake-error-message is its own wording; query-error-statement is the SQL
connection-errorthe request never became an answer. connection-error-endpoint and connection-error-status when the failure names them
usage-errorthe driver never sent it: a malformed DSN, a closed connection, a bind value with no SQL equivalent
session-lost-errorthe engine no longer held the session, and it took an open transaction or a context with it; the statement did not run. session-lost-error-statement is the SQL — see Session lifetime

A statement that failed with a connection-error has an unknown fate — it may have arrived and run before the connection broke — so it must not be blindly retried. One that failed with a session-lost-error has a known one: it never ran.

Concurrency

A connection serializes its own statements, under a real lock on SBCL, CCL, LispWorks and Allegro. Sharing one across threads is therefore safe but pointless: statements queue, because session state — USE, session variables, an open transaction — carries from one to the next, which is exactly what a half-interleaved second statement would break. Give each thread its own connection.

Portability

SBCL is what this is developed and tested against. ECL, CCL, CLISP, LispWorks and Allegro have socket branches written from their documented APIs but are not exercised here; an implementation with no branch is reported at connect time rather than at load time, so the rest of the driver still loads and its tests still pass there.

TLS

The engine's own server speaks plain HTTP — it is a com.sun.net.httpserver.HttpServer — so an https DSN means something in front of it terminates TLS. This driver has no TLS of its own and says so at connect rather than failing later with a socket error. Put the proxy on a plain port the driver can reach, or tunnel.

Tests

sbcl --eval '(asdf:test-system "frostlake")'

Unit tests need nothing. The integration tests and the engine-owned testkit corpus need a classpath to boot an engine from, and skip themselves without one rather than passing against a stub. The corpus is replayed only when FL_CORPUS names frostlake's engine/src/test/resources/testkit, and skips without it:

FL_CORPUS=/path/to/frostlake/engine/src/test/resources/testkit \
FROSTLAKE_CLASSPATH='/path/to/frostlake/lib/*' sbcl \
  --eval '(asdf:load-system "frostlake/test")' \
  --eval '(sb-ext:exit :code (if (frostlake-test:run-all-tests) 0 1))'
VariableMeaning
FROSTLAKE_CLASSPATHthe engine jars, for booting a DatabaseHttpServer
FL_CORPUSthe testkit directory whose suites/*.json are replayed (best absolute: a relative one is read from the working directory)
FROSTLAKE_TESTKIT_FILTERrun only the suites whose file name contains this

The corpus is engine-owned (engine/src/test/resources/testkit/suites/*.json, spec in SCHEMA.md beside them) and language-neutral, so suites added on the engine side are picked up here with no driver change. Results land in results/testkit-lisp.tsv, and the checks this transport cannot express — an error's code or SQLSTATE, which the HTTP protocol does not carry — are recorded in results/missing-apis-lisp.md rather than failed on.

Each run boots its engine with a user.home of its own. A default-configured engine persists outside its working directory — the catalog under ~/.frostlake_engine/data, internal stages under ~/.frostlake_stages — so without that, consecutive runs inherit each other's databases, warehouses and stages.

Engine behaviour worth knowing

Found while building this, and true of any client:

  • TIME keeps whole seconds only. '10:30:05.25'::TIME reads back as 10:30:05, and TIME(9) truncates the same way. TIMESTAMP_NTZ does keep its fraction.
  • A zoned literal needs a colon in its offset. The engine prints +0100 and parses +01:00, so that is what the driver writes; it reads both.
  • A session is created by the execute endpoint, not the health one. connection-session-id is nil until the first statement — or until connect applies a DSN that names a scope.
  • An array literal is not accepted in a VALUES clause. INSERT INTO t VALUES (['a','b']) is refused; INSERT INTO t SELECT ['a','b'] is fine, and so is an array literal anywhere in a SELECT. A bound vector renders the same way either way.
  • On engines before 0.1.0 the HTTP endpoint refuses a blank statement itself (400, SQL is required), so the engine's own wording for one is not observable over this transport. From 0.1.0 it runs and fails with SQL compilation error: Empty SQL statement.

Licence

Apache-2.0. See LICENSE.

Dependencies (0)

    Dependents (0)

      • GitHub
      • Quicklisp