DbMigrator
Applies a versioned migration package to a database.
Extends AsyncEventEmitter (from strict-typed-events), so every listener registered with
on() may itself be async — execute() awaits each one in turn as it emits lifecycle
events.
Only a PostgreSQL migration adapter is implemented today. See Running Migrations for details.
Constructor
new DbMigrator()
Takes no arguments.
import { DbMigrator } from '@sqb/migrator';
const migrator = new DbMigrator();
Methods
execute()
Applies pending migrations from a migration package to the database described by
options.connection, up to options.targetVersion (or the package's highest version, if
omitted).
execute(options: DbMigratorOptions): Promise<boolean>
| Argument | Type | Default | Description |
|---|---|---|---|
| options | DbMigratorOptions | Connection, migration package, and execution options |
- Returns
Promise<boolean>— resolves totrueonce the target version has been reached.
Throws:
TypeError—connection.dialectis missing, or is set to anything other than'postgres'(no other migration adapter is implemented yet).Error—targetVersionis lower than the migration package's lowest version, or the database's current version is more than one version behind the package's lowest version.- Whatever error a task itself throws (a SQL error, a rejected custom
fn, etc.), after writing anerrorevent row to themigration_eventstable and — if a backup was taken — emittingrestoreand calling the adapter'srestoreDatabase().
import '@sqb/postgres';
import { DbMigrator } from '@sqb/migrator';
import { myMigrationPackage } from './migrations/index.js';
const migrator = new DbMigrator();
migrator.on('task-start', ({ task }) => console.log('Running', task.title));
await migrator.execute({
connection: { dialect: 'postgres', database: 'my_database' },
migrationPackage: myMigrationPackage,
targetVersion: 14,
});
Events
DbMigrator is an AsyncEventEmitter — register listeners with .on(event, handler), where
handler may be async (it is awaited before the migration proceeds).
| Event | Payload | Emitted |
|---|---|---|
start | — | Once, at the beginning of execute(). |
backup | — | Only if some migration in the package has backup: true, before the adapter's backupDatabase() runs. |
migration-start | { migration: Migration; total: number; index: number } | Before a migration's tasks run. |
task-start | { migration: Migration; task: MigrationTask; total: number; index: number } | Before a task runs. |
task-finish | { migration: Migration; task: MigrationTask; total: number; index: number } | After a task completes successfully. |
migration-finish | { migration: Migration; total: number; index: number } | After a migration's tasks all complete. |
restore | — | Only on failure, and only if a backup was taken, before the adapter's restoreDatabase() runs. |
finish | — | Once, after every targeted migration has been applied. |
See Running Migrations for the full execution order and a usage example.