migr
Database migration runner - register versioned up/down migration functions, run all pending migrations in version order, roll back the last applied migration, migrate forward or backward to a specific version, query current version and status, and list pending migrations.
Load with: use migr
What this module does
migr implements a simple, database-agnostic migration runner.
Migrations are plain ilusm functions - you supply an up(db)
thunk that applies the schema change and an optional down(db)
thunk that reverses it. The runner tracks which versions have been applied
and runs only pending migrations, sorted numerically by version number.
The db parameter is any object you pass in - typically a
database connection handle from your SQL or NoSQL module.
Quick example
use migr
m = mignw()
m = migad(m, 1, "create users",
\(db) db.exec("CREATE TABLE users (id INT, name TEXT)"),
\(db) db.exec("DROP TABLE users"))
m = migad(m, 2, "add email column",
\(db) db.exec("ALTER TABLE users ADD COLUMN email TEXT"),
\(db) db.exec("ALTER TABLE users DROP COLUMN email"))
# Run all pending migrations
db = my_db_connection()
m = migup(m, db)
# Status
prn(migst(m)) # {cur:2, applied:2, pending:0, total:2}
# Roll back last
m = migdn(m, db)
# Migrate to specific version
m = migto(m, db, 1)
Functions
Setup
mignw() / migr.new()Creates a new migration runner state {migs:[], applied:[]}.
migad(m, ver, name, up, down) / migr.add(m, ver, name, up, down)Registers a migration. ver is an integer version number, name is a description string, up(db) applies the migration, down(db) reverses it (may be nil to make it irreversible).
Running
migup(m, db) / migr.up(m, db)Runs all unapplied migrations in ascending version order. Records each applied migration with a timestamp. Returns the updated runner state.
migdn(m, db) / migr.dn(m, db)Rolls back the most recently applied migration by calling its down(db) function (if present). Returns the updated state.
migto(m, db, ver) / migr.to(m, db, ver)Migrates to a specific version - runs pending up-migrations if ver > current, or rolls back in reverse order if ver < current.
Status
migcv(m) / migr.ver(m)Returns the current version number (0 if no migrations applied).
migst(m) / migr.st(m)Returns a status object {cur, applied, pending, total}.
migpd(m) / migr.pnd(m)Returns the list of pending (unapplied) migration records sorted by version.
Notes
- Applied migrations are tracked in memory - persist
m.appliedto your database if you need durability across restarts. - Requires
trl,txt, andtim.