Skip to main content

DbMigrator

Applies a versioned migration package to a database. Extends AsyncEventEmitter (from strict-typed-events), so every listener registered with on() may itself be asyncexecute() awaits each one in turn as it emits lifecycle events.

warning

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>

ArgumentTypeDefaultDescription
optionsDbMigratorOptionsConnection, migration package, and execution options
  • Returns Promise<boolean> — resolves to true once the target version has been reached.

Throws:

  • TypeErrorconnection.dialect is missing, or is set to anything other than 'postgres' (no other migration adapter is implemented yet).
  • ErrortargetVersion is 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 an error event row to the migration_events table and — if a backup was taken — emitting restore and calling the adapter's restoreDatabase().
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).

EventPayloadEmitted
startOnce, at the beginning of execute().
backupOnly 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.
restoreOnly on failure, and only if a backup was taken, before the adapter's restoreDatabase() runs.
finishOnce, after every targeted migration has been applied.

See Running Migrations for the full execution order and a usage example.

See also