santoku-sqlite
View on LuaRocksSQLite for Lua: prepared-statement query closures, transactions, zero-copy carray vector binds, BM25 full-text search over santoku tokens, and encrypted databases
santoku-sqlite is the framework's SQLite binding. A small C core, santoku.sqlite.db, wraps the SQLite C API, and santoku.sqlite turns prepared statements into reusable query closures with transaction control. This page ships the WebAssembly build, so most examples run live against in-memory databases in your browser.
Details
- A carray virtual table binds santoku-matrix vectors as zero-copy SQL inputs.
- santoku.sqlite.fts is a full-text index over your own tokens.
- santoku.sqlite.mirror keeps a local copy of a table in another database, such as MySQL.
- An encrypting VFS seals every byte on disk.
- santoku.sqlite.sync syncs existing tables between peers over a hybrid logical clock. Its create, request, respond, apply, push, ack and gc have their own page: https://santoku.dev/santoku-sqlite/sync
- The C core compiles unchanged to WebAssembly. There it also registers an OPFS-backed VFS, opfs-coop: synchronous access handles held in a dedicated worker, one cooperative Web Lock shared across tabs, and a pool of slot files.
- File persistence and the encryption key setup need a real filesystem, so those examples are shown for reading.
Connections and statements
Open a database
open, open_memory and open_v2 return a connection userdata. The santoku.sqlite wrapper turns the connection into a table of statement factories.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec([=[
create table cities (name text, state text);
create index cities_state on cities (state);
]=])
print("tables:", db.getter(
"select count(*) from sqlite_master where type = 'table'")())
print("raw handle:", type(db.db))
print("autocommit:", db.db:autocommit())
db.close()
return "closed"
Details
- A failed open returns nil, SQLite's message and the result code. The wrapper raises that failure through santoku.error.
- A worker that can't write the file sees "unable to open database file" and the CANTOPEN code.
- open(path, true) and open_v2(path, vfs, true) open the database read-only.
- exec runs raw SQL, including scripts of more than one statement.
- The raw connection stays reachable at db.db.
- close finalizes every cached statement, then closes the handle.
- db.db:autocommit() is true outside a transaction.
- db.db:close_vm() finalizes every statement without closing the connection. It raises while a statement runs.
- Since 6.1.0, the native build creates a new database file as 0664 less the process umask. So umask 002 leaves the file group-writable.
- SQLite gives the -wal, -journal and -shm files the database file's own mode.
runner and getter
Each factory prepares its statement once and returns a closure you call with bind values. runner executes the statement for effect, and getter fetches one row.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table cities (name text, state text)")
local addcity = db.runner("insert into cities (name, state) values (?, ?)")
addcity("Tampa", "Florida")
addcity("Albany", "New York")
local move = db.runner("update cities set state = ? where name = ?")
print("moved:", move("Georgia", "Albany"), move("Georgia", "Nowhere"))
move("New York", "Albany")
local getcity = db.getter("select * from cities where name = ?", true)
local city = getcity("Tampa")
print("row:", city.name, city.state)
local getstate = db.getter("select state from cities where name = ?")
print("value:", getstate("Albany"))
return getstate("Tampa")
Details
- runner returns how many rows the statement inserted, updated or deleted. So 0 from an update or delete means no row matched.
- db.changes() reports the same count for the last statement on the connection.
- getter returns a named table when prop is true, and otherwise the column values themselves. It returns nothing when no row matches.
- A getter over an update or delete with a RETURNING clause runs the write and returns the row it touched. So nil means no row matched, which is the usual way to answer 404.
- The toku init scaffolds' web/status.lua answers a nil with no write status as 404.
- db.query(sql, ...) runs once without caching. It returns every row as an array of value arrays, plus the column names.
- Plain SQL reaches every SQLite feature this build compiles in. FTS5 isn't one of them since 6.0.0, and santoku.sqlite.fts is the full-text index.
The prop argument
The prop argument sets how each row comes back. true yields a { column = value } table, false discards the row, and anything else spreads the columns.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table people (name text, age integer)")
db.runner("insert into people (name, age) values (?, ?)")("Ada", 36)
local get_cols = db.getter("select name, age from people where name = ?")
local name, age = get_cols("Ada")
print("spread:", name, age)
local get_row = db.getter("select name, age from people where name = ?", true)
local row = get_row("Ada")
print("table:", row.name, row.age)
local discard = db.getter("select name, age from people where name = ?", false)
print("discarded:", discard("Ada"))
return name
Details
- false runs the statement for effect.
- Anything else, including no prop at all, spreads the columns as multiple return values.
- all is the exception, since it collects one value per row. There anything other than true collects only the first column.
Named parameters
Pass a single table, and its string keys bind to :name parameters. Each call picks the positional or the named style.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table cities (name text, state text)")
local add = db.runner("insert into cities (name, state) values (:name, :state)")
add({ name = "Tampa", state = "Florida" })
add({ name = "Miami", state = "Florida" })
local get = db.getter("select state from cities where name = :name")
print("state:", get({ name = "Tampa" }))
return get({ name = "Miami" })
Details
- Keys without a matching parameter are ignored.
- The same statement accepts either style on each call.
inserter and the rowid
inserter runs like a runner but returns last_insert_rowid, so integer primary keys come back to the caller.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table notes (id integer primary key, body text)")
local add = db.inserter("insert into notes (body) values (?)")
local id1 = add("first")
local id2 = add("second")
print("rowids:", id1, id2)
local get = db.getter("select body from notes where id = ?")
print("fetched:", get(id2))
return id2
Stream rows with iter
iter returns a bind closure plus a resetter. A call to the closure binds the values and yields an iterator over the rows.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table cities (name text, state text)")
local add = db.runner("insert into cities (name, state) values (?, ?)")
add("Tampa", "Florida")
add("Miami", "Florida")
add("Albany", "New York")
local rows = db.iter("select name, state from cities order by name")
for name, state in rows() do
print(name, state)
end
local bystate, reset = db.iter("select name from cities where state = ?")
for name in bystate("Florida") do
print("first hit only:", name)
break
end
reset()
return "done"
Details
- The default prop spreads the columns of each row. prop true yields tables.
- One closure holds one statement. Call the resetter after you leave a traversal early: it releases the statement, and the open iterator returns nil from then on.
- A new bind also ends the iterator before it.
- Build two closures for two live cursors over the same SQL.
Collect rows with all
all materializes the result. prop true collects named-table rows, and the default collects the first column of each row into a flat list.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local arr = require("santoku.array")
local db = sql(sqlite.open_memory())
db.exec("create table cities (name text, state text)")
local add = db.runner("insert into cities (name, state) values (?, ?)")
add("Tampa", "Florida")
add("Miami", "Florida")
add("Albany", "New York")
local rows = db.all("select name, state from cities order by name", true)()
print("rows:", #rows, "first:", rows[1].name)
local names = db.all("select name from cities where state = ? order by name")
print("florida:", arr.concat(names("Florida"), ", "))
return #rows
Details
- Bind values go to the second call, so one factory serves many queries.
Transactions
Transactions in a closure
transaction(fn, ...) begins, calls fn with the trailing arguments, commits on return and returns fn's results. On error it rolls back and re-raises.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table t (n integer)")
local addn = db.runner("insert into t (n) values (?)")
local count = db.getter("select count(*) from t")
local total = db.transaction(function (a, b)
addn(a)
addn(b)
return count()
end, 1, 2)
print("committed:", total)
local ok, e = err.pcall(db.transaction, function ()
addn(3)
err.error("boom")
end)
print("rolled back:", ok, e, "count still", count())
db.transaction("deferred", function ()
db.transaction(function ()
addn(4)
end)
end)
print("nested commits once:", count())
return count()
Details
- A leading string picks the begin mode.
- Since 6.1.0, a nested call runs inside the outer transaction in its own savepoint.
- When a nested call raises, its changes roll back to that savepoint and the error propagates.
- A caller that catches the error keeps the outer transaction open, without the inner changes.
Manual begin and commit
begin, commit and rollback let you drive the transaction yourself, for control flow that doesn't fit a closure. begin defaults to immediate.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table t (n integer)")
local addn = db.runner("insert into t (n) values (?)")
local count = db.getter("select count(*) from t")
db.begin("immediate")
addn(1)
addn(2)
db.commit()
print("after commit:", count())
db.begin()
addn(3)
db.rollback()
print("after rollback:", count())
return count()
Details
- Pass deferred or exclusive to begin to choose another mode.
Concurrent access
retry_busy under nginx
retry_busy({ runtime }) sets busy_timeout to 0 and retries in Lua while the database is busy, calling runtime.sleep(ms) between tries. Pass santoku.resty.async, so an OpenResty worker serves other requests while it waits.
local db = sql(sqlite.open(db_file))
local retry = ngx.shared.sqlite_retry
db.exec("pragma journal_mode = WAL")
db.retry_busy({
runtime = require("santoku.resty.async"),
count = function (key, n) return retry:incr(key, n, 0) end,
budget_ms = 30000,
})
local add = db.runner("insert into jobs (name) values (?)")
add("nightly")
Details
- Since santoku-sqlite 7.0.0, opts.runtime is anything with sleep(ms), and opts.sleep raises "retry_busy takes opts.runtime, not opts.sleep".
- Since santoku-sqlite 8.0.0, retry_busy raises without a runtime, and santoku.sqlite.db.sleep is gone. In a native script, pass santoku.system.async, so other tasks run while the write waits.
- santoku.resty.sqlite passes the runtime itself: https://santoku.dev/santoku-resty
- SQLite's busy_timeout sleeps inside the C call. Under OpenResty, a worker that waits on another worker's write lock stalls every request it holds.
- retry_busy retries begin, commit, and the first step of a statement run outside a transaction.
- Inside an open transaction a busy statement raises at once, since a retry of one statement could break the transaction.
- Building a statement takes no lock.
- retry_busy takes these options besides runtime and count.
- first_ms: the first wait, 0.1 ms by default. It must be above 0.
- max_ms: the longest wait, 250 ms by default. It must be at least first_ms.
- budget_ms: the total wait, 30000 ms by default.
- Waits start at first_ms and double up to max_ms until budget_ms runs out. Then SQLITE_BUSY raises as it would without retry_busy.
- ngx.sleep rounds to whole milliseconds. So the default schedule yields three times with ngx.sleep(0), then waits 1, 2, 3, 6 ms and so on.
- Another worker holds the write lock for tens of microseconds per autocommit write. So a 5 ms first wait left the lock idle most of the time.
- Measured on a 4-worker server at 64 clients, half of them writing:
| first_ms | Requests/s | p99 |
|---|---|---|
| 5 | 148.3k | 9.82 ms |
| 0.1 | 269.7k | 1.10 ms |
| 0.1, with the checkpointer below | 279.7k | 0.43 ms |
- ngx.sleep is disabled in init_worker_by_lua, so a call made there must not hit a lock.
- Light threads that share one connection queue behind each other's open transactions and iterators.
- A queued light thread's wait doubles from first_ms to max_ms, or to 1 ms when count is set.
- A queued light thread raises "database is locked by another thread on this connection" when budget_ms runs out.
- One coroutine's writes land in the order it makes them, since each call returns only after its write is done or has failed.
- Writes from other light threads on the same connection, and from other workers, may land between them in any order.
- Backoff alone isn't fair across workers. A write that has backed off to max_ms keeps losing the lock to fresh writes that retry from first_ms.
- With backoff alone on a 4-worker server at 64 clients, the slowest write waited 2.7-3.2 s.
- count is a function (key, n) that adds n to a counter shared by every process on the database and returns the new value. n = 0 reads the counter.
- With count set, a write that has slept fair_ms (2 ms by default) takes a ticket from "tail" and waits for "head" to reach it.
- Only the write at the head probes the lock, every 1 ms or less. It advances "head" once it has the lock.
- While tail is ahead of head, every other write holds off, so the longest waiter gets the lock next.
- Reads never queue.
- If head doesn't move for max_ms, a waiter advances it. So a ticket lost with a dead worker costs at most max_ms once.
- Two writers may then probe together, and SQLite's lock still lets only one in.
- With no queue, a write costs two count reads.
- Under OpenResty, back count with incr on a lua_shared_dict, declared in nginx.conf as "lua_shared_dict sqlite_retry 1m;".
- Prefix the key per database when several databases share the dict.
- Measured on the same 4-worker server at 64 clients:
| Setting | Mixed requests/s | Write requests/s | Mixed p99 | Write p99 | Slowest request |
|---|---|---|---|---|---|
| fair_ms 2 | 356.5k | 219.9k | 1.57 ms | 4.90 ms | 41-68 ms |
| fair_ms 10 | 325.0k | 205.0k | 9.31 ms | 10.02 ms | not reported |
| no count | 286.9k | 180.7k | not reported | not reported | 2.7-8.2 s |
- The 0.1 ms default of first_ms, the doubling wait of a queued light thread, and count and fair_ms date from 6.1.0.
The WAL checkpointer since santoku-sqlite 6.1.0
db.checkpointer(opts) returns step(), which checkpoints the WAL from one connection that does nothing else. It bounds the WAL and keeps checkpoints off the commit path of the request connections.
local process = require("ngx.process")
local db = sql(sqlite.open(db_file))
db.exec("pragma journal_mode = WAL")
db.exec("pragma synchronous = NORMAL")
local runtime = require("santoku.resty.async")
if process.type() == "privileged agent" then
local step = db.checkpointer({ runtime = runtime })
ngx.timer.at(0, function ()
while not ngx.worker.exiting() do
step()
runtime.sleep(100)
end
end)
else
db.exec("pragma wal_autocheckpoint = 0")
db.retry_busy({ runtime = runtime })
end
Details
- In WAL mode, SQLite's wal_autocheckpoint (1000 pages) runs a checkpoint inside the COMMIT that crosses it.
- At synchronous NORMAL that checkpoint fsyncs the WAL and then the database file. So whichever request commits waits for both.
- The WAL can only restart from its beginning when no reader still uses it. Under steady reads some reader always does, so the file grows without bound.
- The fix is one connection that does nothing but checkpoint, with wal_autocheckpoint = 0 on every request connection.
- db.checkpoint(mode, opts) runs sqlite3_wal_checkpoint_v2. It returns busy, the WAL's frames and the frames copied back.
- mode is passive (the default), full, restart or truncate.
- passive copies what it can without waiting.
- restart and truncate hold the WAL write lock while they copy and while they wait for readers to leave the WAL. Every writer waits with them.
- They wait with their own busy handler, starting at 10 microseconds, for at most opts.budget_ms (20). Then they return busy = true.
- They put the connection's busy_timeout back afterwards.
- After a restart the next commit writes from the start of the WAL. truncate also cuts the file to 0 bytes.
- checkpoint raises SQLITE_LOCKED inside a transaction on its own connection.
- Each step runs a passive checkpoint, then opts.mode when a trigger fires.
- opts.mode: restart, or truncate.
- opts.restart_every: run opts.mode every this many steps, 10 by default. 0 turns this trigger off.
- opts.restart_frames: run opts.mode once the WAL holds this many frames, 0 by default. 0 turns this trigger off.
- A busy restart retries on the next step.
- opts.runtime: anything with sleep(ms), like retry_busy's. With it, a restart tries without waiting, releases the write lock, calls runtime.sleep(1) and tries again while SQLite reports busy.
- Since santoku-sqlite 7.0.0, opts.runtime replaces opts.sleep, and opts.sleep raises.
- Writers commit between those tries.
- Without a runtime, a restart waits inside SQLite's busy handler.
- opts.budget_ms: the wall time a restart may take, 1000 with a runtime and 20 without.
- opts.idle_steps: 10 by default, and 0 turns it off. Once this many steps in a row see no commit from any connection, the step runs one truncate in place of any restart due.
- The idle check reads pragma data_version for other connections and total_changes() for its own.
- The idle truncate leaves a 0-byte WAL while the server is idle. It runs again only after a commit.
- The WAL's frame count can't serve as that signal. Batches of equal size between steps restart the WAL to the same count every time.
- Under steady writes the idle truncate never fires.
- step() returns the mode it ran last plus the three values of checkpoint.
- With opts.runtime a step yields. So run the steps one at a time from a loop, since ngx.timer.every would start a second step while one sleeps.
- Run the checkpointer from a timer in a process that serves no requests: nginx's privileged agent.
- require("ngx.process").enable_privileged_agent() turns the agent on in init_by_lua. The agent runs init_worker_by_lua like a worker.
- The code below is that init_worker_by_lua.
- Request connections get WAL, synchronous NORMAL, wal_autocheckpoint = 0 and retry_busy, and no journal_size_limit.
- SQLite applies journal_size_limit only in the first commit after the WAL restarts, on the connection that commits. So the limit does nothing on the checkpointer's own connection.
- Without journal_size_limit the checkpointer still bounds how far the WAL grows, and the idle truncate empties the file once writes stop.
- On a new database, the switch to WAL takes the write lock. A worker that loses that race gets SQLITE_BUSY without a call to the busy handler.
- santoku-resty's santoku.resty.sqlite, which the web and API scaffolds use, retries the switch for that reason: https://santoku.dev/santoku-resty
- Every measurement below ran on a 4-worker server at 64 clients.
- A restart with a runtime, behind one writer connection:
| Metric | Without a runtime | With a runtime |
|---|---|---|
| mean restart | 195 ms | 48 ms |
| write requests/s | 292.4k | 336.8k |
- The idle truncate kept throughput within 1.2% under steady writes:
| Metric | Without idle truncate | With idle truncate |
|---|---|---|
| WAL at rest | 0.58-0.73 GB | 0 bytes |
- The defaults with a runtime and a step every 100 ms:
| Setup | Mixed requests/s | Write requests/s |
|---|---|---|
| no single writer connection | 288.0k | 179.2k |
| one writer connection | 412.7k | 331.1k |
- Those defaults left a 0-byte WAL at rest.
- How far the WAL grew:
| Setup | WAL peak | Throughput |
|---|---|---|
| restart_every, the default | 0.70 GB | the baseline |
| restart_frames = 16384 in place of restart_every | 0.15 GB | about 10% less |
| wal_autocheckpoint 1000, no checkpointer | 10-12 GB | not reported |
- The checkpoint's fsyncs still slow commits on the request connections:
| Setup | p999 |
|---|---|
| with a checkpointer | 46-48 ms |
| writes with no checkpoints at all | 0.24 ms |
- journal_size_limit on the request connections cost 13% of mixed throughput and 16% of write throughput:
| Metric | Without journal_size_limit | With journal_size_limit |
|---|---|---|
| mixed requests/s | 279.7k | 242.4k |
| write requests/s | 176.8k | 148.1k |
| write p99 | 1.21 ms | 3.42 ms |
Errors and values
Errors and result codes
The wrapper raises through santoku.error with errmsg and errcode from the connection. So err.pcall recovers the message and the code as separate values.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
local ok, msg, code = err.pcall(function ()
return db.exec("not valid sql")
end)
print("ok:", ok)
print("message:", msg)
print("code:", code, code == sqlite.ERROR)
local ok2, msg2 = err.pcall(function ()
return db.runner("select x from nope")
end)
print("prepare fails too:", ok2, msg2)
return code
Details
- A statement that fails to prepare raises from the C layer instead. Its message starts with prepare: and carries no code.
- The module also exports the raw result constants OK, ERROR, ROW and DONE.
Values across the boundary
The factories and bind_values convert Lua values to SQL by type. nil, booleans, numbers, strings and santoku-matrix vectors bind, and any other value raises.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local err = require("santoku.error")
local ivec = require("santoku.ivec")
local db = sql(sqlite.open_memory())
print("vector rows:", db.getter("select count(*) from carray(?)")(ivec.create({ 4, 5, 6 })))
print(err.pcall(db.getter("select ?"), function () end))
db.exec("create table t (a, b, c, d)")
db.runner("insert into t (a, b, c, d) values (?, ?, ?, ?)")(
nil, true, 1.5, "x\0y")
local a, b, c, d = db.getter("select a, b, c, d from t")()
print("null:", a)
print("boolean as int:", b)
print("number:", c)
print("bytes:", #d, d == "x\0y")
return #d
Details
- nil binds SQL null, and null reads back as nil.
- Booleans bind as 0 or 1.
- Numbers always bind as doubles. They're exact for integers up to 2^53, and integer columns read back as plain Lua numbers.
- Strings pass unchanged in both directions, embedded zeros included.
- An ivec, svec, fvec or dvec binds as a carray pointer, through the factories as well as bind_values.
- A factory called with a single table still binds the table by name.
- Since 6.0.0, a value with no SQL form raises. The messages:
- A table, function, thread or light userdata raises "bind_values: parameter <i> is a <type>, which cannot be bound".
- A named parameter gives the same message with the prefix bind_names: in place of bind_values:.
- Other userdata raises "... is a userdata that is not an ivec, svec, fvec or dvec".
Application structure
A module of closures
Prepare each statement once at module setup, then compose the closures inside one transaction. Run every mutation path through db.transaction.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec([=[
create table users (id integer primary key, email text unique);
create table tokens (user_id integer, token text);
]=])
local get_user = db.getter("select * from users where email = ?", true)
local create_user = db.inserter("insert into users (email) values (?)")
local delete_user_tokens = db.runner("delete from tokens where user_id = ?")
local insert_token = db.runner("insert into tokens (user_id, token) values (?, ?)")
local function login (email, token)
return db.transaction(function ()
local user = get_user(email)
local id = user and user.id or create_user(email)
delete_user_tokens(id)
insert_token(id, token)
return id
end)
end
print("first login:", login("a@example.com", "t1"))
print("second login:", login("a@example.com", "t2"))
return db.getter("select count(*) from tokens")()
The store builder since santoku-sqlite 6.1.0
db.store(builder) calls builder(db), which prepares its statements and returns { read = {...}, write = {...} }. store gives back one flat table of those methods.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local db = sql(sqlite.open_memory())
db.exec("create table notes (id integer primary key, body text not null)")
local notes = db.store(function (db)
local add = db.inserter("insert into notes (body) values (?)")
local count = db.getter("select count(*) from notes")
return {
read = {
count = function ()
return count()
end,
},
write = {
add_pair = function (a, b)
return add(a), add(b)
end,
},
}
end)
print("ids:", notes.add_pair("first", "second"))
print("failed write:", notes.add_pair("third", nil))
print("count:", notes.count())
return notes.count()
Details
- Read methods come back as they are and raise on error.
- Each write method runs inside db.transaction and returns true and its own values.
- When a write raises, the whole write rolls back. The method then returns nil and "failed: " plus the message.
- So err.checkok(notes.add(x)) returns the write's values or raises "failed: ...", and local ok, r = notes.add(x) branches on ok. santoku.async.proxy and santoku.resty.sqlite return the same way.
- Called inside an open db.transaction, a write nests like any db.transaction call.
- A failing nested write rolls back to its savepoint. So the outer transaction stays open and commits none of the failed write's changes.
- store raises when the builder returns a key other than read and write, a method that isn't a function, or one name in both.
- store works with or without retry_busy, so the same builder serves plain Lua, the resty CLI and OpenResty.
Raising store writes since santoku-sqlite 6.2.0
db.store(builder, { raise = true }) makes each write method return only its own values and raise its error instead of returning nil. Use it in batch jobs, so one failed write aborts the caller's whole transaction.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local err = require("santoku.error")
local db = sql(sqlite.open_memory())
db.exec("create table notes (id integer primary key, body text not null)")
db.exec("create table cursor (at integer not null)")
db.exec("insert into cursor values (0)")
local notes = db.store(function (db)
local add = db.inserter("insert into notes (body) values (?)")
local advance = db.runner("update cursor set at = ?")
local at = db.getter("select at from cursor")
return {
read = {
at = function ()
return at()
end,
},
write = {
add = function (body)
return add(body)
end,
advance = function (n)
advance(n)
end,
},
}
end, { raise = true })
local ok = err.pcall(db.transaction, function ()
notes.add("first")
notes.advance(10)
notes.add(nil)
end)
print("job committed:", ok)
print("cursor:", notes.at())
return notes.at()
Details
- Each write still runs inside db.transaction and rolls back when it raises.
- Called inside an open db.transaction, the error passes up through the caller's transaction. That transaction rolls back too, so it commits none of its writes.
- A raising write called from inside another raising write aborts the outer write the same way.
- opts.raise defaults to false, which keeps the true or nil, "failed: " return of the store builder.
- store raises when opts isn't a table, has a key other than raise, or raise isn't a boolean.
Migrations
santoku.migrate takes a db handle and a { filename = sql } table, and applies the migrations it hasn't seen inside one transaction. Run it on every open, server side and in the browser.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local db = sql(sqlite.open_memory())
local migrations = {
["001-init.sql"] = "create table notes (id integer primary key, body text);",
["002-tags.sql"] = [=[
create table tags (note_id integer, tag text);
create index tags_note on tags (note_id);
]=],
}
migrate(db, migrations)
migrate(db, migrations)
migrations["003-drafts.sql"] =
"alter table notes add column draft integer not null default 0;"
migrate(db, migrations)
print("applied:", db.getter("select count(*) from migrations")())
return db.all("select filename from migrations order by filename")()
Details
- santoku.migrate is its own rock, santoku-migrate.
- It sorts the names, comparing digit runs as numbers.
- It records each name in migrations(filename varchar(255) not null primary key), so reruns are idempotent.
- Embed the migration files at build time.
- The same function takes a santoku-mysql handle.
- The santoku-migrate tab has the rest: https://santoku.dev/santoku-migrate
Mirror a remote table since santoku-sqlite 6.4.0
santoku.sqlite.mirror(db, source, spec) keeps a local table in step with a table in another database. pull copies rows changed since the stored stamp. check compares bucket checksums and repairs drift and deletes.
local str = require("santoku.string")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local mirror = require("santoku.sqlite.mirror")
local db = sql(sqlite.open_memory())
db.exec("create table mirror_state (name text primary key, stamp text)")
db.exec("create table m_books (id integer primary key, title text, _crc integer)")
local books = {
{ id = 1, title = "Dune", stamp = "2026-01-01" },
{ id = 2, title = "Emma", stamp = "2026-01-02" },
}
local function rows (keep)
local out = {}
for _, b in ipairs(books) do
if keep(b) then
local h = 0
for i = 1, #b.title do
h = (h * 31 + str.byte(b.title, i)) % 4294967296
end
out[#out + 1] = { id = b.id, title = b.title, _crc = h, _stamp = b.stamp }
end
end
local i = 0
return function ()
i = i + 1
return out[i]
end
end
local source = {
since = function (stamp)
return rows(function (b)
return stamp == nil or b.stamp >= stamp
end)
end,
sums = function ()
local n, s = 0, 0
for r in rows(function () return true end) do
n, s = n + 1, s + r._crc
end
local sent = false
return function ()
if not sent then
sent = true
return { b = 0, n = n, s = s }
end
end
end,
range = function (_, lo, hi)
return rows(function (b)
return b.id >= lo and b.id < hi
end)
end,
}
local m = mirror(db, source, { name = "books", table = "m_books", key = "id", cols = { "title" }, width = 1000 })
print("pulled:", #m.pull())
books = { { id = 2, title = "Persuasion", stamp = "2026-01-02" } }
print("retitled:", #m.pull())
local changed, buckets = m.check()
print("deleted:", #changed, "buckets:", buckets)
return db.all("select id, title from m_books", true)()
Details
- The local table holds spec.key as its primary key, the spec.cols columns and an integer _crc. In bucket mode it also holds an integer _b. Create the table in a migration.
- spec.table names the local table and defaults to spec.name.
- spec.state names the stamp table, mirror_state by default, with a name text primary key and a stamp column.
- spec.width groups integer keys into ranges of that many keys. spec.buckets takes a bucket number from the source, for any key type. Give exactly one.
- The source is a table of functions. Each returns an iterator of row tables, and the source computes every checksum, so mirror never builds remote SQL.
| Function | Returns rows of | Used by |
|---|---|---|
| since(stamp) | key, cols, _crc and _stamp, plus _b in bucket mode, stamped at or after stamp | pull |
| sums() | b, n and s: a bucket, its row count and its _crc sum | check |
| range(b, lo, hi) | the since columns for bucket b. lo and hi bound the keys in width mode | check |
| top() | optional. Returns the newest stamp, not an iterator | check |
- since gets nil as the stamp on the first pull.
- pull returns the changed keys. It skips a row whose _crc matches and stores the newest _stamp it saw.
- check returns the changed and deleted keys and the count of buckets that differed. It rewrites each differing bucket in its own transaction.
- A bucket differs when its row count or _crc sum differs. In width mode SQLite computes the bucket as key / width on integer keys, so the source must group keys the same way.
- mirror raises on a spec without name, key, cols and exactly one of width and buckets, and on a name that isn't an identifier.
- pull and check raise when the source lacks a function they call.
Vectors
carray vector inputs
Pass a santoku-matrix vector where a parameter is expected, and it binds as a carray table with a single value column. SQL reads it zero-copy from the vector's backing store, in rowid order.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local arr = require("santoku.array")
local db = sql(sqlite.open_memory())
db.exec("create table items (id integer primary key, label text)")
local add = db.runner("insert into items (id, label) values (?, ?)")
add(1, "alpha")
add(2, "beta")
add(3, "gamma")
add(4, "delta")
local pick = db.all(
"select label from items where id in (select value from carray(?)) order by id")
local labels = pick(ivec.create({ 2, 4 }))
for i = 1, #labels do
print("hit:", labels[i])
end
local above = db.all("select value from carray(?) where value > ?")
print("filtered:", arr.concat(above(fvec.create({ 0.5, 2.5, 1.5 }), 1.0), ", "))
return #labels
Details
| Vector | carray type |
|---|---|
| ivec | int64 |
| svec | int32 |
| fvec | float |
| dvec | double |
Raw statements and slices
db.db:prepare exposes the statement object. Its bind_carray(pidx, vec, start, count) binds a zero-copy slice of a vector and raises on out-of-range bounds.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local ivec = require("santoku.ivec")
local db = sql(sqlite.open_memory())
local stmt = db.db:prepare("select value from carray(?1) order by rowid")
local v = ivec.create({ 1, 2, 3, 4, 5 })
stmt:reset()
stmt:bind_carray(1, v, 1, 3)
while true do
local res = stmt:step()
if res == sqlite.ROW then
print("value:", stmt:get_value(0))
elseif res == sqlite.DONE then
stmt:reset()
break
else
err.error(db.db:errmsg(), db.db:errcode())
end
end
return "done"
Details
- The statement object has step, reset, get_value, get_values, get_named_values, columns, column_names, bind_values, bind_names and bind_carray.
- reset also clears the bindings.
- start is 0-based and defaults to 0. count defaults to the rest of the vector.
- So start 1 and count 3 in the example bind 2, 3 and 4.
- Compare step results against the exported ROW and DONE constants.
Full-text search
Search over user text
A search box needs a tokenizer and an index. santoku.learn.tokenizer's tokenize_raw turns each text into hashed word counts, and santoku.sqlite.fts indexes those rows and ranks them with BM25.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local fts = require("santoku.sqlite.fts")
local tokenizer = require("santoku.learn.tokenizer")
local csr = require("santoku.csr")
local arr = require("santoku.array")
local db = sql(sqlite.open_memory())
local function tokens (texts)
local off, tok, val = tokenizer.tokenize_raw({ texts = texts, n_samples = #texts,
mode = "words", ngram_min = 1, ngram_max = 1, normalize = true })
return csr.create({ offsets = off, neighbors = tok, values = val })
end
local idx = fts.create(db, { name = "places" })
idx.add({ "uyuni", "komodo", "moreno" }, tokens({
"Salar de Uyuni, the largest salt flat on Earth",
"Komodo Island, home of the komodo dragon",
"Perito Moreno, a glacier in Patagonia",
}))
local function search (q)
local hits = idx.search(tokens({ q }), 10)
return arr.concat(arr.map(hits, function (h) return h.id end), " ")
end
print("SALT flat:", search("SALT flat"))
print("Dragón:", search("Dragón"))
print("glacier island:", search("glacier island"))
print("volcano:", search("volcano"))
return search("salt")
Details
- Call tokenize_raw with mode = "words" and normalize = true. It has no vocabulary to fit.
- The same function tokenizes the query, so user text never becomes query syntax.
- A word matches only the same word after normalize. Case and accents fold, and there's no prefix or stem matching.
- Query words are OR-ed, and a word that no document holds adds nothing.
The fts index
fts.create(db, opts) builds a full-text index over your own token ids. It creates a santoku_fts virtual table <name>_ft and a <name>_map table from your text ids to integer rowids.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local fts = require("santoku.sqlite.fts")
local str = require("santoku.string")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local csr = require("santoku.csr")
local db = sql(sqlite.open_memory())
local idx = fts.create(db, { name = "docs" })
idx.add({ "a", "b", "c", "d", "e" }, csr.create({
offsets = ivec.create({ 0, 3, 6, 8, 10, 12 }),
neighbors = ivec.create({ 1, 2, 3, 2, 4, 5, 6, 7, 7, 8, 8, 9 }),
values = fvec.create({ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }),
}))
local q = csr.create({
offsets = ivec.create({ 0, 2 }),
neighbors = ivec.create({ 1, 2 }),
values = fvec.create({ 1, 1 }),
})
local hits = idx.search(q, 10)
for i = 1, #hits do
print(hits[i].id, str.format("score %.3f coverage %.2f", hits[i].score, hits[i].coverage))
end
local unknown = idx.search(csr.create({
offsets = ivec.create({ 0, 3 }),
neighbors = ivec.create({ 1, 2, 999 }),
values = fvec.create({ 1, 1, 1 }),
}), 10)
print("unknown token, same coverage:", unknown[1].coverage == hits[1].coverage)
idx.remove({ "a" })
print("after remove:", #idx.search(q, 10))
idx.clear()
print("after clear:", #idx.search(q, 10))
return #hits
Details
- Documents and queries are csr rows of token ids, as santoku.learn.tokenizer returns them. So the tokenizer decides what a token is.
- fts.create takes these opts.
- name: the index name.
- schema: optional.
- k1 and b: the BM25 parameters, 1.2 and 0.75 by default.
- blocks: token-id block widths, one length norm each.
- integer_ids: integer ids as rowids, described below.
- Postings live in shadow tables, so SQLite supplies transactions, rollback and locking.
- add(ids, csr) rounds each value to the nearest integer, at least 1. It sums repeated tokens in a row and replaces any row already stored under the same id.
- Pass raw counts to add.
- remove(ids) and clear() delete.
- search(csr, k, scales) ranks every document that shares a token with the csr's first row. It returns at most k hits, 50 by default, as { id, score, coverage }, best first.
- score is the negated BM25 sum. It equals csr:bm25(k1, b) on the stored documents followed by csr:topk with the query, and the specs compare each score with ==.
- Ties go to the lower rowid.
- Query values weight their tokens. When present, they must be an fvec.
- coverage divides the score by the query's weighted idf sum, capped at 1.
- That sum skips query tokens with no live document, so an unknown token leaves coverage unchanged.
- With blocks, scales is an fvec with one weight per block, and a token outside every block raises.
- integer_ids = true takes integer ids within ±2^53 as the rowid, with no <name>_map. Reopening an index with the other kind of id raises.
- Prefer word tokens over character n-grams.
- When queries and documents use different words for the same thing, keep the top 100 hits as candidates. Rerank them with an embedding model through the rerank method of santoku.learn.retrieval.reranker.
- The santoku-learn-llama tab shows the full recipe: https://santoku.dev/santoku-learn-llama
Rebuild an fts index
rebuild(ids, csr, batch) replaces the whole index while searches keep reading the old one. Other writers only ever wait for one batch.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local fts = require("santoku.sqlite.fts")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local csr = require("santoku.csr")
local db = sql(sqlite.open_memory())
local idx = fts.create(db, { name = "docs" })
idx.add({ "a" }, csr.create({
offsets = ivec.create({ 0, 1 }),
neighbors = ivec.create({ 1 }),
values = fvec.create({ 1 }),
}))
idx.rebuild({ "b", "c", "d" }, csr.create({
offsets = ivec.create({ 0, 1, 2, 3 }),
neighbors = ivec.create({ 1, 1, 2 }),
values = fvec.create({ 1, 1, 1 }),
}), 2)
local hits = idx.search(csr.create({
offsets = ivec.create({ 0, 1 }),
neighbors = ivec.create({ 1 }),
values = fvec.create({ 1 }),
}), 10)
for i = 1, #hits do
print("hit:", hits[i].id)
end
return #hits
Details
- rebuild builds a second pair of tables beside the live one. It commits batch rows per transaction, 5000 by default.
- Then it merges the new index into one segment, renames the new pair into place in one short transaction, and drops the old pair.
- Searches read the old index until the swap.
- A failed build leaves the live index intact, and the next rebuild drops the partial copy.
- Inside a caller's db.transaction, rebuild commits with that transaction, which then holds every batch.
- The old index's pages stay in the file as free pages that later writes reuse.
- To shrink the file, run VACUUM yourself outside a transaction. This build keeps temporary storage in memory, so VACUUM needs about the database's size in RAM.
- The table names <name>_new_* and <name>_old_* are reserved.
fts in SQL
<name>_ft is a plain virtual table, so SQL can join it, count it or page it. The factories bind a vector argument as carray, so they page, count and rank straight from the table.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local fts = require("santoku.sqlite.fts")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local csr = require("santoku.csr")
local arr = require("santoku.array")
local db = sql(sqlite.open_memory())
db.exec("create table papers (id integer primary key, title text, published integer)")
local add_paper = db.runner("insert into papers (id, title, published) values (?, ?, ?)")
local idx = fts.create(db, { name = "num", integer_ids = true })
local ids, offs, toks = {}, { 0 }, {}
for i = 1, 40 do
ids[i] = 100 + i
add_paper(ids[i], "paper " .. i, 2000 + i % 7)
arr.push(toks, 1 + i % 5, 6 + i % 3)
offs[#offs + 1] = #toks
end
local ones = fvec.create(#toks)
ones:fill(1)
idx.add(ids, csr.create({ offsets = ivec.create(offs), neighbors = ivec.create(toks), values = ones }))
local tv = ivec.create({ 2, 7 })
print("matches:", db.getter("select count(*) from num_ft f where f.tokens = ?")(tv))
local page = db.all("select f.rowid as id from num_ft f where f.tokens = ? order by f.rowid limit ? offset ?")
print("page 2:", arr.concat(page(tv, 5, 5), " "))
local newest = db.all([=[
select p.title from num_ft f join papers p on p.id = f.rowid
where f.tokens = ? order by p.published desc, p.id limit 3
]=])
print("newest:", arr.concat(newest(tv), ", "))
local top = db.all("select f.rowid as id, f.score as score from num_ft f where f.tokens = ? and f.k = ? order by f.score", true)
local best = top(tv, 3)
local hits = idx.search(csr.create({ offsets = ivec.create({ 0, 2 }), neighbors = tv, values = fvec.create({ 1, 1 }) }), 3)
print("same as search:", best[1].id == hits[1].id and best[1].score == hits[1].score)
return #best
Details
- The table has these columns.
- rowid: <name>_map.rid, or the id itself with integer_ids.
- score: the negated BM25 sum that search returns.
- maxw: the query's weighted idf sum, so coverage is -score / maxw capped at 1.
- The hidden columns take the query.
- tokens: an ivec or svec bound as carray. It's required.
- weights: an fvec with one weight per token.
- k: a row limit.
- k1 and b: the BM25 parameters.
- scales: one weight per block.
- tfs: the document's term frequencies on insert.
- A statement that uses score or maxw gets ranked rows, best first, and order by score costs nothing extra.
- A statement that uses neither skips scoring and streams every match in ascending rowid order, so joins and count(*) stay cheap.
- With a k below the match count, such a statement returns the ranked top k in rowid order.
- Writes also go through the table, with these statements.
- insert into <name>_ft (rowid, tokens, tfs)
- delete from <name>_ft where rowid = ?
- insert into <name>_ft (<name>_ft) values ('optimize')
- insert into <name>_ft (<name>_ft) values ('delete-all')
FTS5 tables from 5.x since santoku-sqlite 6.0.0
Every connection registers a drop-only fts5 module, because 6.0.0 removed FTS5. drop table on an old FTS5 table removes it and its shadow tables.
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local err = require("santoku.error")
local db = sql(sqlite.open_memory())
local ok, msg = err.pcall(function ()
db.exec("create virtual table notes using fts5(body)")
end)
print(ok, msg)
local st = db.db:prepare("select 1")
print("bind_tokens:", st.bind_tokens)
return ok
Details
- 6.0.0 removed FTS5, its santoku tokenizer, the santoku_bm25 and santoku_bm25_max functions, and the bind_tokens, bind_match and bind_weights statement methods.
- fts.create finds a 5.x <name>_ft by its using fts5 SQL. It drops that table and <name>_map in one transaction, then creates the new pair empty, so re-add your rows after it.
- Any other statement on an old FTS5 table raises "FTS5 was removed in santoku-sqlite 6.0.0; this table can only be dropped".
- create virtual table ... using fts5 raises "FTS5 was removed in santoku-sqlite 6.0.0; fts5 tables can only be dropped".
- Reopening an index with different blocks raises "fts.create: <name> was created with blocks (...), not (...)".
Untrusted SQL
Files and encryption
Files and persistence
open(path, readonly) creates or reopens a database file. open_v2(path, vfs) also picks the VFS by name.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local d1 = sql(err.assert(sqlite.open("app.db")))
d1.exec("create table if not exists t (n)")
d1.runner("insert into t (n) values (?)")(42)
d1.close()
local d2 = sql(err.assert(sqlite.open("app.db")))
print("persisted:", d2.getter("select n from t")())
d2.close()
print("wasm build:", sqlite.wasm)
return "done"
Details
- On failure, open, open_memory and open_v2 return nil, SQLite's message and its result code. So err.checknil or assert surfaces the reason.
- open_encrypted returns nil and the message on failure.
- The wasm flag reports which build you're on.
- In the browser the default filesystem is memory-backed. Durable storage goes through OPFS: https://santoku.dev/santoku-sqlite#santoku-sqlite--encrypted-sqlite-over-opfs
Encrypted databases
open_encrypted seals every byte on disk with XChaCha20-Poly1305 under a 32-byte key. Tampered, reordered or transplanted blocks fail closed instead of decrypting.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local str = require("santoku.string")
local key = str.rep("\42", 32)
local db = sql(err.assert(sqlite.open_encrypted("notes.db", key)))
db.exec("create table if not exists notes (id integer primary key, body text)")
db.runner("insert into notes (body) values (?)")("sealed at rest")
print("rows:", db.getter("select count(*) from notes")())
db.close()
local wrong = str.rep("\7", 32)
local ok = err.pcall(function ()
local raw = err.assert(sqlite.open_encrypted("notes.db", wrong))
return sql(raw).getter("select count(*) from notes")()
end)
print("wrong key reads:", ok)
local nope, msg = sqlite.open_encrypted("notes.db", "tooshort")
print("bad key size:", nope, msg)
return "closed, key released"
Details
- Pages, journal and WAL all live in the same authenticated container, with the magic TKSQENC1.
- Each block write draws a fresh nonce.
- The AAD binds the block index and a per-file salt.
- A wrong key or a key of the wrong size can't read anything.
- Closing the connection releases the key.
Key registry and merged reads
key_set registers a key per resolved path in a process-wide table. Call it before ATTACH, and one connection spans databases sealed under different keys.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local str = require("santoku.string")
local key_a = str.rep("A", 32)
local key_b = str.rep("B", 32)
err.assert(sqlite.key_set("a.db", key_a))
err.assert(sqlite.key_set("b.db", key_b))
local vfs = err.assert(sqlite.enc_vfs())
local merged = sql(err.assert(sqlite.open_v2(":memory:", vfs)))
merged.exec("attach database 'a.db' as s1")
merged.exec("attach database 'b.db' as s2")
print("all notes:", merged.getter([=[
select count(*) from (
select id from s1.notes union all select id from s2.notes)
]=])())
merged.exec("detach database s1")
merged.exec("detach database s2")
merged.close()
sqlite.key_clear("a.db")
sqlite.key_clear("b.db")
return "done"
Details
- key_clear evicts a key. In-flight writes on a cleared key then fail.
- Attached databases inherit the connection's VFS, so a plain connection can never read an encrypted attach.
- enc_vfs names the encrypting VFS. So even a :memory: main database can host encrypted attaches as a merged read view.
Encrypted SQLite over OPFS
In the wasm build the module registers the opfs-coop VFS. The encrypting VFS stacks on top of it through the third argument, the parent VFS.
local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local str = require("santoku.string")
local path = "/d-0123abcd.db"
local key32 = str.rep("\1", 32)
err.assert(sqlite.key_set(path, key32, "opfs-coop"))
local raw = err.assert(sqlite.open_encrypted(path, key32, "opfs-coop"))
local db = sql(raw)
db.exec("pragma journal_mode = TRUNCATE")
db.exec("pragma synchronous = NORMAL")
db.exec("pragma temp_store = MEMORY")
db.exec("create table if not exists notes (id integer primary key, body text)")
db.runner("insert into notes (body) values (?)")("durable and sealed")
print("rows:", db.getter("select count(*) from notes")())
db.db:reset_cache()
db.close()
sqlite.key_clear(path, "opfs-coop")
return "done"
Details
- opfs-coop uses OPFS synchronous access handles in a dedicated worker, one cooperative exclusive Web Lock shared across tabs, and a pool of slot files.
- The pool opens its access handles with mode "readwrite-unsafe", which only Chromium 121 and later support. So the OPFS worker needs Chromium 121 or later, and opening the pool fails on Firefox and Safari.
- A complete encrypted open takes a hashed filename and a derived key. Then it runs key_set, open_encrypted on the parent VFS, the pragmas and the migrations, in that order.
- Another tab may hold the lock and write in between. reset_cache then resets statements and drops the page cache of the main and every attached database.
- So the next read after reset_cache sees the new state.
- Under opfs-coop a file holds one open connection per worker. A second open of the same file in that worker fails with SQLITE_CANTOPEN, so share the one connection.
Examples
Projects that toku init creates with this rock. The examples page shows their files.
- A JSON API: An OpenResty server with no frontend, over a server-side sqlite database.
toku init --example api my-api - A library with a command: A Lua rock with a C module, a sqlite store behind migrations, and an argparse command.
toku init --example lib my-lib - An offline web app: The web app with its data in sqlite in the browser, synced to the server, and a service worker so it boots offline.
toku init --example pwa my-app - A full-text search command: A command that indexes notes in a sqlite file and ranks them for a query with BM25.
toku init --example search my-search - A web app: A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server.
toku init --example web my-app