santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-migrate

View on LuaRocks

versioned, idempotent, forward-only SQL migrations for santoku-sqlite and santoku-mysql handles, in one transaction

santoku-migrate applies versioned schema migrations to a santoku-sqlite or santoku-mysql handle with one function. Pass the handle and a table that maps names to SQL scripts. It applies the scripts that haven't run yet, in version order, inside one transaction, and records each name in a migrations table.

Details
  • Migrations are forward-only. Append a new numbered migration and never edit an applied one.
  • When a change is too deep to express as SQL over live data, wipe and rebuild under a schema epoch, as the last card shows.
  • The rock depends only on santoku. It calls the handle's transaction, exec, getter and runner.
  • santoku.migrate runs on a database whose migrations table santoku.sqlite.migrate created.
  • santoku.sqlite.migrate fails on a database that santoku.migrate created.
  • The first four examples run live in this page against an in-memory SQLite database.
  • The consumer patterns after them touch files, servers or build machinery, so they're shown for reading.

The migrate function

require("santoku.migrate") returns one function, migrate(db, migrations). Keys name the migrations and values are SQL scripts. migrate applies what's missing in version order and records each name.

local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local err = require("santoku.error")
local db = sql(sqlite.open_memory())
migrate(db, {
  ["0.0.1"] = "create table items (id integer primary key, name text);",
  ["0.0.2"] = "alter table items add column done integer not null default 0;",
})
db.runner("insert into items (name) values (?)")("write docs")
for row in db.iter("select filename from migrations order by filename", true)() do
  print(row.filename)
end
print(err.pcall(migrate, db, "nope"))
return db.getter("select count(*) from items")()
Details
  • migrate creates migrations(filename varchar(255) not null primary key) if that table is missing.
  • A migrations argument that isn't a table raises "migrations must be a table".

Idempotent and forward-only

migrate skips applied names, so a second call with the same table does nothing, even when a migration inserts rows. A call at every startup is safe.

local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local db = sql(sqlite.open_memory())
local first = "create table c (n integer); insert into c (n) values (1);"
migrate(db, { ["0.0.1"] = first })
migrate(db, { ["0.0.1"] = first })
migrate(db, { ["0.0.1"] = first, ["0.0.2"] = "insert into c (n) values (2);" })
for row in db.iter("select n from c order by n", true)() do
  print(row.n)
end
return db.getter("select count(*) from c")()
Details
  • A later call with a superset applies only the new keys.
  • Applied migrations match by name alone. So an edit to the body of an applied migration changes nothing on existing databases.

Version-aware ordering

migrate sorts keys with a comparator that compares digit runs as numbers and other bytes by value. So 0.0.2 < 0.0.10 < 0.1.0.

local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local db = sql(sqlite.open_memory())
local function log (v)
  return "insert into log (name) values ('" .. v .. "');"
end
migrate(db, {
  ["0.0.1"] = "create table log (seq integer primary key, name text);",
  ["0.0.2"] = log("0.0.2"),
  ["0.0.10"] = log("0.0.10"),
  ["0.1.0"] = log("0.1.0"),
})
for row in db.iter("select name from log order by seq", true)() do
  print(row.name)
end
return db.getter("select count(*) from log")()
Details

A key that is a prefix of another key sorts first.

One transaction per call

Every migration and its record run inside one db.transaction. On SQLite a failing script raises and rolls back the whole call, the migrations table included.

local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local err = require("santoku.error")
local db = sql(sqlite.open_memory())
local ok = err.pcall(migrate, db, {
  ["0.0.1"] = "create table a (n integer);",
  ["0.0.2"] = "this is not valid sql;",
})
print("migrate ok:", ok)
print("migrations table exists:", (err.pcall(db.exec, "select * from migrations")))
print("table a exists:", (err.pcall(db.exec, "select * from a")))
return ok
Details

On MySQL and MariaDB, DDL commits implicitly. So the migrations before the failing one stay applied and recorded.

Migrations are scripts

migrate runs each value through db.exec, which runs multi-statement scripts. So one migration can create tables, build indexes, backfill data, and drop what it replaced.

local migrate = require("santoku.migrate")
migrate(db, {
  ["0.0.2.sql"] = [=[
    alter table records add column parent_id text;
    create index records_parent on records(parent_id);
  ]=],
  ["0.0.6.sql"] = [=[
    drop table hlc_seq;
    create table hlc_state (
      id integer primary key check (id = 1),
      pt integer not null,
      c integer not null
    );
    insert into hlc_state values (1, 0, 0);
  ]=],
})
Illustrative: runs outside the browser.
Details
  • In the example, 0.0.2 adds a parent column and its index.
  • 0.0.6 replaces the sequence table with hybrid-logical-clock state and seeds it.

Migrations from files

At build time, the <module>/migrations.tk.lua that every toku init scaffold ships reads res/<component>/migrations. It keys each file by basename and serializes the table into the emitted module.

<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
Illustrative: runs outside the browser.
Details
  • Consumers keep migrations as numbered .sql files and inline them with a santoku template.
  • component is "server" or "client" in a web or api project, and "lib" in a lib project.
  • Every key ends in .sql, so the suffix doesn't change the order.
  • The shipped bundle carries its schema with no filesystem access at runtime. So the same pattern works inside a browser worker.
  • The module that opens the database calls migrate(db, require("my_lib.migrations")).

Two migration sets

A client with one small plaintext index database and many encrypted per-account databases migrates them at different times. The index migrates once at worker boot, right after its pragmas.

local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")

local index_migrations = {
  ["0.0.1"] = "create table accounts (id text primary key);",
}
local account_migrations = {
  ["0.0.1"] = "create table notes (id integer primary key, body text);",
}

local index_db = sql(err.assert(sqlite.open("index.db")))
index_db.exec("pragma journal_mode = TRUNCATE")
index_db.exec("pragma synchronous = NORMAL")
migrate(index_db, index_migrations)

local function open_account (path, key32, parent_vfs)
  local db = sql(err.assert(sqlite.open_encrypted(path, key32, parent_vfs)))
  local ok, e = err.pcall(function ()
    db.exec("pragma journal_mode = TRUNCATE")
    db.exec("pragma synchronous = NORMAL")
    migrate(db, account_migrations)
  end)
  if not ok then
    err.pcall(db.close)
    sqlite.key_clear(path, parent_vfs)
    err.error("account database open failed", tostring(e))
  end
  return db
end

return open_account
Illustrative: runs outside the browser.
Details
  • Each account database migrates at open, inside a pcall.
  • On failure the pcall closes the handle and clears the VFS key. So a bad migration never leaves a key registered for a broken database.

Migrate on connection open

A server wrapper opens its file database, sets pragmas, and migrates at every open unless the caller opts out.

local err = require("santoku.error")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")

local migrations = {
  ["0.0.1"] = "create table events (id integer primary key, at integer);",
}

return function (db_file, opts)
  opts = opts or {}
  local db = sql(err.assert(sqlite.open(db_file)))
  db.exec("pragma busy_timeout = 30000")
  db.exec("pragma journal_mode = WAL")
  db.exec("pragma synchronous = NORMAL")
  if not opts.no_migrate then
    migrate(db, migrations)
  end
  return db
end
Illustrative: runs outside the browser.
Details

The pragmas set WAL, and busy_timeout for concurrent writers.

MySQL and MariaDB

A santoku-mysql handle takes the same migrate call. The handle below uses the native santoku-socket transport, with TLS on by default over TCP.

local migrate = require("santoku.migrate")
local mysql = require("santoku.mysql")(require("santoku.socket.tcp"))
local db = mysql.open({
  host = "db.internal", port = 3306,
  user = "app", password = "secret", database = "app",
  tls = { cafile = "ca.pem" },
})
migrate(db, {
  ["0.0.1"] = "create table items (id int auto_increment primary key, name varchar(80));",
  ["0.0.2"] = "alter table items add column done int not null default 0;",
})
db.close()
Illustrative: runs outside the browser.
Details

The santoku-mysql page covers the OpenResty transport and the TLS options: https://santoku.dev/santoku-mysql

The schema epoch wipe

When a format change leaves existing rows unrepresentable, no SQL over them can produce valid new ones. Record a schema epoch in the migrated database instead.

local str = require("santoku.string")
local migrate = require("santoku.migrate")

local EPOCH = "4"

return function (db, index_migrations, store)
  migrate(db, index_migrations)
  local get_epoch = db.getter("select value from meta where key = 'schema_epoch'")
  local set_epoch = db.runner(
    "insert or replace into meta (key, value) values ('schema_epoch', ?)")
  if get_epoch() ~= EPOCH then
    local paths = store.list_files()
    for i = 1, #paths do
      if str.match(paths[i], "^/d%-%x+%.db$") then
        store.delete_file(paths[i])
      end
    end
    set_epoch(EPOCH)
  end
end
Illustrative: runs outside the browser.
Details
  • When the stored epoch is behind the code's, delete every derived database minted under the old epoch. Then let the source of truth rebuild them.
  • The same index migrations create the meta table that the code reads.

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 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