Typed Migration Runner Versions
Run versioned migrations in order with an idempotency check: a second pass applies nothing, and applied versions are recorded in state.
Code
// Versioned migration runner: applied versions live in state, migrations
// run in order, and a re-run skips everything already applied
interface Migration {
readonly version: number;
readonly up: (state: Map<number, string>) => void;
}
const migrations: readonly Migration[] = [
{ version: 1, up: (state) => state.set(1, "created orders table") },
{ version: 2, up: (state) => state.set(2, "added orders.status column") },
{ version: 3, up: (state) => state.set(3, "created orders_status index") },
];
function runMigrations(state: Map<number, string>, pending: readonly Migration[]): number {
let applied = 0;
for (const migration of pending) {
if (state.has(migration.version)) continue; // idempotent: skip applied
migration.up(state);
applied += 1;
}
return applied;
}
const schema = new Map<number, string>();
console.log("first run applied:", runMigrations(schema, migrations));
console.log("second run applied:", runMigrations(schema, migrations));
console.log("versions recorded:", [...schema.keys()].sort().join(","));Output
Captured from a sandboxed run of this snippet in the build pipeline.
first run applied: 3
second run applied: 0
versions recorded: 1,2,3What happens when it runs
Structurally, expect the function runMigrations and nothing else.
Iteration happens inside for (const migration of pending) — everything outside it runs once.
What to watch for
- Each symbol it touches is a language built-in — nothing to fetch.
Using it
The signature that matters most: function runMigrations(state: Map<number, string>, pending: readonly Migration[])
Output lines are prefixed (first run applied:, second run applied:, versions recorded:), which puts each step’s result in plain view.
Key statements
readonly up: (state: Map<number, string>) => void;
const schema = new Map<number, string>();
applied += 1;
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `runMigrations` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.