db/migrate.ts

Version-gated database migration runner.

Migrations are functions in ordered arrays, grouped by namespace. A schema_version table tracks progress per namespace. Each migration runs in its own transaction.

Forward-only: No down-migrations. Schema changes are additive. For pre-release development, collapse migrations into a single v0.

Named migrations: Migrations can be bare functions or {name, up} objects. Names appear in error messages for debuggability.

Advisory locking: Per-namespace PostgreSQL advisory locks serialize concurrent migration runs, preventing double-application in multi-instance deployments.

Declarations
#

5 declarations

view source

Migration
#

db/migrate.ts view source

Migration

A migration: either a bare function or a named object with an up function.

Named migrations include their name in error messages for debuggability.

MigrationFn
#

db/migrate.ts view source

MigrationFn

A single migration function that receives a Db and applies DDL/DML.

Runs inside a transaction — throw to rollback.

MigrationNamespace
#

db/migrate.ts view source

MigrationNamespace

A named group of ordered migrations.

Array index = version number: migrations[0] is version 0, etc.

namespace

type string

migrations

type Array<Migration>

MigrationResult
#

db/migrate.ts view source

MigrationResult

Result of running migrations for a single namespace.

namespace

type string

from_version

type number

to_version

type number

migrations_applied

type number

run_migrations
#

db/migrate.ts view source

(db: Db, namespaces: MigrationNamespace[]): Promise<MigrationResult[]>

Run pending migrations for each namespace.

Creates the schema_version tracking table if it does not exist, then for each namespace: acquires an advisory lock, reads the current version, runs pending migrations in order (each in its own transaction), updates the stored version, and releases the lock.

Concurrency: Uses PostgreSQL advisory locks to serialize concurrent callers on the same namespace. Safe for multi-instance deployments.

db

the database instance

type Db

namespaces

migration namespaces to process in order

type MigrationNamespace[]

returns

Promise<MigrationResult[]>

results per namespace (only includes namespaces that had work to do)

Imported by
#