Sirannon records every applied migration in its migration history and copies the highest version into PRAGMA user_version. Each pending upward migration commits in a separate transaction, so when one fails, the history contains every migration that succeeded before it.
File-based migrations
Store the SQL in files whose last path segment follows <version>_<name>.up.sql and <version>_<name>.down.sql. A down file is optional, although a rollback of a version without one fails with MIGRATION_NO_DOWN.
For example, save these complete files in a migrations directory.
CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL);DROP TABLE notes;The complete migrate-files.ts program loads that directory and applies its pending SQL.
import { mkdir } from 'node:fs/promises'
import { Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { loadMigrations } from '@delali/sirannon-db/file-migrations'
await mkdir('./data', { recursive: true })
const migrations = loadMigrations('./migrations')
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('notes', './data/migrated-notes.db')
await db.migrate(migrations)
} finally {
await sirannon.shutdown()
}loadMigrations pairs the up and down files of each version and sorts the versions in order. It skips every file whose name follows neither pattern. It loads the up SQL at once and reads the down SQL only when you roll that version back.
The loader refuses control characters and .. path segments, as well as a repeated version, a missing up file, or empty SQL.
Use whole-number versions from 1 to 2,147,483,647, because SQLite stores user_version as a signed 32-bit integer. A version in Unix seconds fits that range, while a fourteen-digit calendar timestamp is too large.
Programmatic migrations
A Migration declares version, name, up, and an optional down. An SQL string works in every runtime. An asynchronous function can also do the work of a migration through the transaction handle that Sirannon passes it, although the server can't send a function to a device through the migration handshake.
The complete migrate.ts program applies two migrations to a temporary file and rolls the second one back before it reads the schema version.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { type Migration, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
const migrations: Migration[] = [
{
version: 1,
name: 'create_notes',
up: 'CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)',
down: 'DROP TABLE notes',
},
{
version: 2,
name: 'add_pinned',
up: 'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
down: 'ALTER TABLE notes DROP COLUMN pinned',
},
]
const directory = await mkdtemp(join(tmpdir(), 'sirannon-migrations-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('notes', join(directory, 'notes.db'))
await db.migrate(migrations)
await db.rollback(migrations)
const schema = await db.queryOne<{ user_version: number }>('PRAGMA user_version')
console.log(JSON.stringify(schema, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}migrate returns the applied entries and a skipped count. A second call with the same set applies nothing and counts every version that the history records in skipped. appliedMigrations() returns the recorded versions, names, and checksums in ascending order.
Leave the transaction to Sirannon
Sirannon opens and commits the transaction of each migration, so it refuses a pending migration whose SQL contains BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, or RELEASE. Sirannon also refuses a migration that creates or drops a temporary table, view, index, or trigger, because SQLite creates that object on the writer connection, where the object exists after the migration ends. Sirannon checks every pending migration before it applies the first one. When one of them breaks either rule, migrate fails with FORBIDDEN_SQL and applies none of the pending migrations.
When you want a scratch table inside a migration, create a regular table and drop it before the migration ends. Sirannon checks only pending migrations, so a database whose history contains a transaction-control statement or a temporary object in an applied migration opens and migrates as it did in earlier releases.
Copy a table to change a column
SQLite's ALTER TABLE adds, renames, and drops columns, so a migration that changes the type of a column, or places a new column between two others, has to copy the table into a new one. Sirannon opens every connection with foreign keys on, while SQLite ignores PRAGMA foreign_keys inside a transaction. Without further steps, dropping the old table can therefore delete or clear every row that refers to it.
Put PRAGMA foreign_keys = OFF anywhere among the statements of such a migration, as SQLite's procedure for other schema changes does. Sirannon then turns foreign keys off before the transaction of the migration begins and turns them back on after it ends. Before it commits, Sirannon checks every foreign key with PRAGMA foreign_key_check.
In the complete copy-table.ts program, the first migration stores each customer's score as text, which the second migration converts to an integer by copying the table. A third migration then copies only the first customer, which leaves an order without its customer.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { type Migration, Sirannon, SirannonError } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
const migrations: Migration[] = [
{
version: 1,
name: 'create_customers_and_orders',
up: `CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers (id) ON DELETE CASCADE, total INTEGER NOT NULL);
INSERT INTO customers (id, name, score) VALUES (1, 'customer-1', '87'), (2, 'customer-2', '64');
INSERT INTO orders (id, customer_id, total) VALUES (10, 1, 2400), (11, 2, 1800), (12, 1, 950);`,
},
{
version: 2,
name: 'store_score_as_integer',
up: `PRAGMA foreign_keys = OFF;
CREATE TABLE new_customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score INTEGER);
INSERT INTO new_customers SELECT id, name, CAST(score AS INTEGER) FROM customers;
DROP TABLE customers;
ALTER TABLE new_customers RENAME TO customers;`,
},
]
const keepOneCustomer: Migration = {
version: 3,
name: 'keep_first_customer',
up: `PRAGMA foreign_keys = OFF;
CREATE TABLE new_customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score INTEGER);
INSERT INTO new_customers SELECT id, name, score FROM customers WHERE id = 1;
DROP TABLE customers;
ALTER TABLE new_customers RENAME TO customers;`,
}
const directory = await mkdtemp(join(tmpdir(), 'sirannon-copy-table-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('shop', join(directory, 'shop.db'))
await db.migrate(migrations)
const customers = await db.query('SELECT id, name, score, typeof(score) AS stored FROM customers ORDER BY id')
const orders = await db.queryOne('SELECT count(*) AS orders FROM orders')
console.log(JSON.stringify({ customers, orders }, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
try {
await db.migrate([...migrations, keepOneCustomer])
} catch (error) {
if (!(error instanceof SirannonError)) throw error
console.log(`${error.code}: ${error.message}`)
}
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}The orders table contains all three orders after the second migration, although its foreign key deletes the orders of a deleted customer, because Sirannon drops the old table while foreign keys are off. The third migration leaves order 11 without its customer, so PRAGMA foreign_key_check finds that row. Sirannon rolls the migration back with a MIGRATION_ERROR whose message identifies the first row that breaks a foreign key.
Set withoutForeignKeys: true on a function migration for the same effect. When you set the flag on a string migration, include PRAGMA foreign_keys = OFF in its up SQL as well, because a device receives only that SQL. Sirannon refuses a string migration that sets the flag without the pragma with MIGRATION_VALIDATION_ERROR. A PRAGMA foreign_keys = ON inside the migration has no effect, because SQLite applies that pragma only outside a transaction.
Change capture works through a migration or a rollback on every table that a process watches, including a table that the migration copies under the same name.
Rollback
db.rollback(migrations) reverses the latest applied migration. With a target version, it reverses every applied version above that target, so a target of zero empties the migration history.
Give each version that a rollback selects a down definition, because rollback fails with MIGRATION_NO_DOWN when one is missing. Destructive down SQL can lose data, so take a tested backup before you apply it.
Migration checksums
Sirannon hashes the SQL of each string up migration with 64-bit FNV-1a and stores the hash as a sixteen-character hexadecimal checksum. Before it applies pending migrations, it compares each supplied migration that the history records as applied with its stored checksum. On a mismatch, migrate fails with MIGRATION_CHECKSUM_MISMATCH.
Before it hashes, Sirannon normalises line endings and trims the whitespace around the SQL, although a change to whitespace inside the SQL can change the checksum. Leave the SQL of an applied migration unchanged, and add a new migration for each schema change. A function migration has a null checksum.
Schema version mirroring
When a migration or a rollback changes the history, Sirannon updates PRAGMA user_version in the same transaction, which is why the migrate.ts program reads version 1 after it reverses version 2.
When an upward migration fails, SQLite rolls back the schema work and the history entry of that migration. The history contains the migrations that committed before it, so a later call starts from those versions.
Bundled migrations
migrationsFromFiles from the main package turns a map from file paths to SQL strings into migrations without any filesystem access. A bundler can produce that map from raw SQL assets, or an application can declare it by hand.
The complete bundled-migrations.ts file exports a set that code on the server and on a device can both import.
import { migrationsFromFiles } from '@delali/sirannon-db'
export const migrations = migrationsFromFiles({
'001_create_notes.up.sql': 'CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)',
'001_create_notes.down.sql': 'DROP TABLE notes',
})The converter reads the version and the direction from the last path segment only. It refuses a file name that follows neither pattern, whereas the directory scanner skips such a file. The converter also refuses a value that is not a string, empty SQL, a missing up entry, and two entries for one version.
For raw imports in Vite or source assets in webpack, configure the bundler to produce string values before you pass its map to this function.
Baseline migrations
A baseline describes an existing schema in one migration. Set baseline: { through: N } on a migration whose version is above N, so that Sirannon applies that baseline and the later migrations to a new database.
Sirannon skips the baseline on a database whose history reaches through. A database below that point requires the migrations in between, because migrate fails with MIGRATION_BASELINE_GAP without them.
Include the superseded migrations in the set until every supported database can reach through. A migration that is not the baseline can't take a version between through and the version of the baseline.
Both loaders accept a baseline: { version, through } option, which marks the SQL file of that version as the baseline. A synced device that lacks the earlier history has to load a full snapshot, as device sync recovery explains.
Concurrent migrations
Two processes can migrate the same file at once. SQLite lets only one of their write transactions write at a time. Inside the transaction that writes, Sirannon checks the recorded versions before it applies a migration.
Sirannon retries once after a concurrency conflict that it recognises, so a second conflict fails with MIGRATION_CONCURRENT. Retry once the competing migration ends, because the history records the versions that committed before the conflict.
Registry migrations
When you pass a shared set in SirannonOptions.migrations, the registry applies the pending migrations to each database that it opens before it returns that database. The same rule applies to the databases that a lifecycle resolver opens.
The complete registry.ts program imports the bundled set above and resolves a tenant through the tenant resolver, which validates the ID and the path.
import { mkdir } from 'node:fs/promises'
import { createTenantResolver, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { migrations } from './bundled-migrations.js'
await mkdir('./data/tenants', { recursive: true })
const sirannon = new Sirannon({
driver: betterSqlite3(),
migrations,
lifecycle: {
autoOpen: {
resolver: createTenantResolver({ basePath: './data/tenants' }),
},
},
})
try {
const tenant = await sirannon.resolve('tenant-42')
if (tenant === undefined) throw new Error('The tenant could not be resolved')
console.log(tenant.id)
} finally {
await sirannon.shutdown()
}The resolver validates only IDs and paths, so authenticate and authorise each caller separately before you resolve its tenant. Hooks and lifecycle explains idle eviction and the cap on open databases.
Load the set from a function
The registry also accepts a function, synchronous or asynchronous, that returns the migration array. The registry calls that function on the first open that requires the set and caches a successful result for the lifetime of the registry.
When the function throws, the open fails, so a later open calls the function again. When the function returns something other than an array, the open fails with MIGRATION_SOURCE_INVALID.
When a migration fails
When a migration fails, the registry closes the database that it is opening, leaves it unregistered, and passes the caller the migration error with the version that failed. A later open starts from the migrations that committed before the failure.
Concurrent resolve calls for the same unregistered ID share one open and its migration step. The registry skips its migrations on a read-only open, because a read-only connection can't change the schema or write the migration history.