# santoku-migrate > versioned, idempotent, forward-only SQL migrations for santoku-sqlite and santoku-mysql handles, in one transaction This file is one tab of the santoku reference, at https://santoku.dev/santoku-migrate/llms.txt. https://santoku.dev/santoku-migrate is the same tab in a browser, https://santoku.dev/llms.txt indexes every tab, and https://santoku.dev/llms-small.txt summarizes them all on one page. 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. - 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. - 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". ```lua 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")() ``` ### 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. - 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. ```lua 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")() ``` ### 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. A key that is a prefix of another key sorts first. ```lua 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")() ``` ### 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. On MySQL and MariaDB, DDL commits implicitly. So the migrations before the failing one stay applied and recorded. ```lua 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 ``` ### 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. - 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. ```lua 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); ]=], }) ``` ### Migrations from files At build time, the /migrations.tk.lua that every toku init scaffold ships reads res//migrations. It keys each file by basename and serializes the table into the emitted module. - 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")). ```lua <% 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 %> ``` ### 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. - 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. ```lua 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 ``` ### Migrate on connection open A server wrapper opens its file database, sets pragmas, and migrates at every open unless the caller opts out. The pragmas set WAL, and busy_timeout for concurrent writers. ```lua 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 ``` ### 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. The santoku-mysql page covers the OpenResty transport and the TLS options: https://santoku.dev/santoku-mysql ```lua 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() ``` ### 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. - 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. ```lua 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 ``` ## Examples - [A JSON API](https://santoku.dev/examples#examples--api): An OpenResty server with no frontend, over a server-side sqlite database. `toku init --example api my-api` - [A library with a command](https://santoku.dev/examples#examples--lib): 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](https://santoku.dev/examples#examples--pwa): 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](https://santoku.dev/examples#examples--web): A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server. `toku init --example web my-app`