Sirannon records applied migrations in its migration history and mirrors the highest version into PRAGMA user_version. Each pending upward migration commits separately, so a failure leaves earlier successful migrations applied.
File-based migrations
Store SQL in files whose final path segment follows <version>_<name>.up.sql and <version>_<name>.down.sql. Down files are optional, but rolling back a version without one fails with MIGRATION_NO_DOWN.
For example, save these complete files under a migrations directory.
CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL);DROP TABLE notes;The complete migrate-files.ts file 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 scans matching files, pairs their directions, and sorts them by version. It skips unrelated file names. It loads up SQL immediately and reads down SQL when rollback needs it.
The loader rejects control characters and .. path segments. Duplicate versions, missing up files, and empty SQL also fail validation.
Versions must be integers from 1 to 2,147,483,647 because SQLite stores user_version as a signed 32-bit integer. A Unix-second version within that range is valid; a fourteen-digit calendar timestamp exceeds it.
Programmatic migrations
A Migration declares version, name, up, and optional down. SQL strings work across runtimes. An asynchronous function can also perform migration work through the supplied transaction handle, but the server cannot send that function through the device migration handshake.
The complete migrate.ts example applies two migrations to a temporary file, rolls back the second, and reads the remaining 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 applied entries and a skipped count. Repeating it with the same set skips versions already recorded. appliedMigrations() returns the recorded versions, names, and checksums in ascending order.
Rollback
db.rollback(migrations) reverses the latest applied migration. A target version reverses every applied version above that target. Target zero requests an empty migration history.
The selected versions need matching down definitions. A missing definition fails with MIGRATION_NO_DOWN. Treat destructive down SQL as a data-loss operation and retain a tested backup.
Migration checksums
Sirannon hashes each string-based up migration with 64-bit FNV-1a and stores a sixteen-character hexadecimal checksum. Before applying pending migrations, it compares supplied applied versions with their stored checksums. A mismatch fails with MIGRATION_CHECKSUM_MISMATCH.
The checksum normalises line endings and trims surrounding whitespace. Changes to internal whitespace can change it. Preserve applied SQL and add a new migration for a schema change. A function migration has a null checksum.
Schema version mirroring
After a migration or rollback changes history, Sirannon updates PRAGMA user_version in the same transaction. The example leaves version 1 after reversing version 2.
A failed upward migration rolls back that migration's schema work and history entry. Earlier committed migrations remain, so a later call resumes from those recorded versions.
Bundled migrations
migrationsFromFiles from the main package converts a map of file paths to SQL strings into migrations without filesystem access. A bundler can produce that map from raw SQL assets, or an application can declare it explicitly.
The complete bundled-migrations.ts file exports a set that both server and device code can 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',
})Only the final path segment determines the version and direction. Unlike the directory scanner, this map converter rejects an unrelated file name. It also rejects non-string values, empty SQL, missing up entries, and version collisions.
For Vite raw imports or webpack source assets, configure the bundler to produce string values before passing its map to this function.
Baseline migrations
A baseline expresses an existing schema in one migration. Set baseline: { through: N } on a migration whose version exceeds N. A fresh database applies that baseline and the later migrations.
A database whose history already reaches through skips the baseline. A database below that point needs the bridging migrations; otherwise it fails with MIGRATION_BASELINE_GAP.
Keep superseded migrations until every supported database can reach through. A non-baseline migration cannot occupy the version gap between through and the baseline version.
Both loaders accept a baseline: { version, through } option to mark a SQL file as the baseline. This keeps the file's contents as SQL. A synced device that lacks the required earlier history needs a full snapshot; see device sync recovery.
Concurrent migrations
When two processes migrate the same file, Sirannon checks recorded versions inside the write transactions before applying them. SQLite serialises those transactions.
Sirannon retries a recognised concurrency conflict once. A repeated conflict fails with MIGRATION_CONCURRENT. Retry after the competing migration work ends; earlier committed versions remain recorded.
Registry migrations
Pass a shared set in SirannonOptions.migrations to apply pending migrations before each opened database becomes visible through the registry. The same rule applies to databases opened through a lifecycle resolver.
The complete registry.ts example imports the bundled set above and resolves a tenant through the validated tenant resolver.
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 IDs and paths; authenticate and authorise a caller separately before resolving its tenant. Hooks and lifecycle explains idle eviction and the open-database cap.
Load the set from a function
The registry also accepts a synchronous or asynchronous function returning the migration array. It calls that function on the first open that needs it and caches a successful result for the registry's lifetime.
If the function throws, the open fails and a later open retries the function. A non-array return value fails with MIGRATION_SOURCE_INVALID.
When a migration fails
A migration failure closes the opening database and leaves it unregistered. The caller receives the migration error with its failing version. A later open can resume after the earlier committed migrations.
Concurrent resolve calls for the same unregistered ID share one open and its migration step. A read-only open skips registry migrations because it cannot change the schema or create migration history.