Guide
Specification
Sqliter specification
The usage guide documents the public API. This specification describes the driver's behaviour and native backend.
sqliter is a general-purpose Pooka driver for embedded SQLite databases. It
supports applications, scripts, services, data importers, and tests. SQL stays
visible to callers. SQLite supplies the SQL engine, query planner, locking, and
storage.
Package and modules
| Module | Responsibility |
|---|---|
sqliter |
Open, configure, and close connections. Execute one SQL statement and read its results. |
sqliter/value |
Bind and represent SQLite storage values and parameters. |
sqliter/row |
Inspect ordered result columns and decode records. |
sqliter statement functions |
Reuse prepared statements and consume rows incrementally. |
sqliter transaction functions |
Transactions, savepoints, and checked access to the reserved connection. |
sqliter/database |
Backup, restore, checkpoint, and SQLite runtime information. |
sqliter/error |
Structured failures from the driver, SQLite, and row decoding. |
The package and module root are both sqliter.
API in use
import sqliter
import sqliter/row
import sqliter/value
class Note(id: Int, title: String)
load_notes(path: String) {
sqliter.with_connection(sqliter.File(path), sqliter.defaults(), fn(db) {
sqliter.query_as(
db,
"SELECT id, title FROM notes WHERE id > ? ORDER BY id",
value.Positional([value.Integer(0)]),
fn(result) {
let id = row.integer(result, 0)?
let title = row.text(result, 1)?
Ok(Note(id, title))
}
)
})
}
Use the same execution API inside a transaction. The transaction handle carries the authorization for that process to use the connection until the callback finishes.
import sqliter
import sqliter/value
title_note(db: sqliter.Connection, id: Int, title: String) {
sqliter.transaction(db, sqliter.TransactionMode.Immediate, fn(tx) {
sqliter.execute(
tx,
"UPDATE notes SET title = :title WHERE id = :id",
value.Named([#(":title", value.Text(title)), #(":id", value.Integer(id))])
)
})
}
Connections and transaction handles share the Session base class.
Their distinct types let API signatures express which operations require an
idle connection or an active transaction. See the usage guide for a complete program.
Connections and configuration
- Open file databases in read-only, read-write, or read-write-create mode.
opendefaults to read-write-create. Expose explicit constructors for a file path, a private in-memory database, and a SQLite-managed temporary database. File paths are passed literally. with_connectionopens once, calls the caller's function, and attempts close on every exit path. Preserve the operation's error when cleanup also fails. Report both through a structured scoped error.- Foreign key enforcement is enabled per connection by default. Keep the database's journal mode unless the caller asks to change it. Expose the effective mode so callers can see, for example, that a memory database did not switch to WAL. Expose synchronous mode and a finite busy timeout.
- Apply configuration before handing out the connection. If opening or configuration fails, release the native handle.
- Closing an idle connection disposes of its statements. Repeated close is
harmless. Closing during a transaction or active row iteration returns a
typed error. Operations on invalidated handles return
Closed. - Reads and writes use SQLite locking. Separate connections can be used from separate BEAM processes. The library serializes operations on each individual connection; a statement or cursor never races with reset or disposal.
SQL execution
| Operation | Contract |
|---|---|
execute |
Run one statement that has no result columns. Return the change in SQLite’s total-change counter and the current last-insert rowid. |
query |
Run one statement and materialize its rows. |
query_one |
Return exactly one row or a cardinality error. |
query_optional |
Return zero or one row, or a cardinality error. |
query_as |
Decode each row with a caller-supplied typed function. Include the row index if decoding fails. |
fold_rows |
Consume rows incrementally and permit a deliberate early stop. |
execute_script |
Run trusted multi-statement SQL, with no parameter binding. Return the statement index on failure. |
execute rejects statements with result columns before stepping them.
Use a query operation for RETURNING. The change counter includes SQLite’s trigger and foreign key side effects.
Last-insert rowid is connection-local
and can be left over from earlier statements. It must be exposed with that
meaning and must never be inferred from SQL text. Use RETURNING when the
caller needs the identity of a specific inserted row.
Single-statement APIs reject a second statement. Use SQLite's prepare tail to detect it, so semicolons in comments or string literals are handled correctly. Allow trailing whitespace and comments. Empty SQL and embedded NUL bytes receive explicit errors. A script is only atomic when run inside a transaction. Track completed statements when a script fails.
Values, parameters, and rows
| SQLite storage class | Pooka representation |
|---|---|
| NULL | value.Null |
| INTEGER | value.Integer(Int), checked to fit signed 64-bit before binding |
| REAL | value.Real(Float), finite values only on input |
| TEXT | value.Text(String), length-aware UTF-8 |
| BLOB | value.Blob(BitArray), byte-aligned arbitrary bytes |
Keep NULL, empty text, and empty blobs distinct. Read the actual storage
class. Boolean, date, JSON, and domain-specific conversions belong in explicit
encoders and decoders. A TEXT result containing invalid UTF-8 returns a
conversion error; callers needing its raw bytes can select CAST(column AS BLOB).
Support positional and named binding. Positional values bind in SQLite
parameter index order, including the index rules for explicit ?NNN markers.
Named bindings match complete names including their :, @, or $
prefixes. Repeated references to one named parameter use the same value. Reject
missing or extra values, duplicate supplied names, and mixed named and
positional SQL in named mode. Report the slot or name associated with the
error. Pass values through SQLite's bind API. Callers supply SQL identifiers
in the SQL text because SQL parameters represent values.
Rows preserve column order and names, including duplicate aliases. Zero-based
lookup always works for a valid column index. Name lookup distinguishes missing
columns from ambiguous names. Provide storage-class accessors, nullable
decoders, and an adapter for composing with pooka/dynamic/decode. A decoding
failure identifies the column and the expected storage class.
Statements and incremental reads
- Prepared statements are tied to one connection. A caller can bind and run a statement repeatedly. A new execution resets the statement and clears the old bindings.
- Statement results are independent Pooka values. Copy SQLite's borrowed text and blob buffers before the next step, reset, or finalization.
- Explicit finalization is idempotent. A scoped statement helper finalizes on normal return, errors, and process termination. The connection owner can recover orphaned native resources on its next operation.
fold_rowsborrows an exclusive cursor until completion, early stop, or failure. The callback runs in the caller. Any use of the same connection from the callback returnsConnectionBusyrather than waiting on itself. A transaction-owned cursor still allows operations on other connections.- Streaming writes using
RETURNINGrequire care. Early stop or decoder failure cannot promise to undo writes already made by SQLite. Use a transaction and return an error if the operation must roll back.
Transactions and concurrency
Expose deferred, immediate, and exclusive transactions. The callback receives a
transaction handle. Operations through the original connection return
ConnectionBusy while the transaction is active. The transaction handle is
usable only by its owner process and becomes stale on completion.
A successful callback result triggers commit. A returned error, callback exception, or monitored owner termination triggers rollback. Re-raise a callback exception after cleanup. Return a typed commit failure if commit was unsuccessful, attempt rollback, and preserve both failures when needed. Distinguish the caller's error type from database failures in the transaction result.
Nested work uses explicit driver-managed savepoints. Savepoint names are generated inside the driver. Roll back to and release a failed savepoint. The outer callback decides whether to continue. Manual transaction SQL is rejected through the managed API, including scripts. Use SQLite's authorizer during preparation to distinguish transaction control from strings and comments. Only the driver's internal transaction commands bypass that check.
Use a per-connection owner to serialize work and monitor transaction and cursor owners. Run user callbacks in the calling process. Never execute a user callback while holding a native lock or on the connection worker. Dirty NIF calls keep potentially blocking SQLite work away from normal BEAM schedulers. Release in-flight resources only when native calls have returned.
Pass an operation-specific handle to query_cancellable or
execute_cancellable to cancel an active statement. Cancellation may interrupt
SQLite while it is working. Completed operations retain their effects. A stale cancel handle must not interrupt
the next statement. A busy timeout controls lock waits separately from
cancellation.
Administration and errors
- Report the SQLite library version and supported capabilities from the loaded backend, including optional SQL features. Expose selected change counters and last-insert rowid as connection-scoped values.
- Back up to a distinct destination connection using SQLite's online backup API. Restore uses the same API with the backup as source and the target database as destination. The driver reserves both connections in a stable order, rejects self-copy and read-only destinations, and finishes the backup handle on every outcome. The copy runs to completion in one SQLite backup step and may replace the destination.
- Provide passive, full, restart, and truncate WAL checkpoints and return available frame counts. Report contention and unsupported journal mode through the typed result.
- Return a typed error with the operation, primary SQLite result code, extended result code, and message when available. Preserve unknown numeric codes. Capture any SQLite SQL error offset before another operation changes the connection error state. Represent offsets as optional zero-based UTF-8 bytes. Never add SQL parameter values to error messages.
- Separate SQLite errors from invalid bindings, missing or ambiguous columns, failed conversions, unexpected cardinality, busy or closed handles, failed cleanup, and an unavailable native backend.
Native backend and distribution
The backend is a small Erlang NIF over SQLite's C API. Keep the public API and lifecycle coordination in Pooka. Use native resource handles for connections and statements, dirty execution for calls that may block, and explicit release for normal cleanup. Native resource destructors are a final safeguard. SQLite handles are serialized by the connection owner and guarded against close and cancellation races at the native boundary.
The release build uses the pinned SQLite amalgamation.
The Hex archive layout places prebuilt NIFs under priv/native/<target>/.
On supported targets, the normal Pooka build loads the packaged NIF without a
local C compiler, Make invocation, or system SQLite installation. The native
CI matrix builds and tests Linux and macOS on x86-64 and arm64, and Windows
on x86-64. See platform support for the build and packaging
details.
The initial driver surface excludes an ORM, migrations, connection pools, custom SQL functions, virtual table callbacks, loadable extensions, and VFS plug-ins. A later library can implement higher-level features through normal connections, prepared statements, and transactions.