Class Migrator

A class for running migrations.

Example

This example uses the FileMigrationProvider that reads migrations files from a single folder. You can easily implement your own MigrationProvider if you want to provide migrations some other way.

import { promises as fs } from 'fs'
import path from 'path'

const migrator = new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
// Path to the folder that contains all your migrations.
migrationFolder: 'some/path/to/migrations'
})
})

Hierarchy

  • Migrator

Constructors

Methods

  • Migrate up/down to a specific migration.

    This method returns a MigrationResultSet instance and never throws. error holds the error if something went wrong. results contains information about which migrations were executed and which failed.

    Examples

    await migrator.migrateTo('some_migration')
    

    If you specify the name of the first migration, this method migrates down to the first migration, but doesn't run the down method of the first migration. In case you want to migrate all the way down, you can use a special constant NO_MIGRATIONS:

    await migrator.migrateTo(NO_MIGRATIONS)
    

    Parameters

    Returns Promise<MigrationResultSet>

  • Runs all migrations that have not yet been run.

    This method returns a MigrationResultSet instance and never throws. error holds the error if something went wrong. results contains information about which migrations were executed and which failed. See the examples below.

    This method goes through all possible migrations provided by the provider and runs the ones whose names come alphabetically after the last migration that has been run. If the list of executed migrations doesn't match the beginning of the list of possible migrations an error is returned.

    Examples

    const db = new Kysely<Database>({
    dialect: new PostgresDialect({
    host: 'localhost',
    database: 'kysely_test',
    }),
    })

    const migrator = new Migrator({
    db,
    provider: new FileMigrationProvider(
    // Path to the folder that contains all your migrations.
    'some/path/to/migrations'
    )
    })

    const { error, results } = await migrator.migrateToLatest()

    results?.forEach((it) => {
    if (it.status === 'Success') {
    console.log(`migration "${it.migrationName}" was executed successfully`)
    } else if (it.status === 'Error') {
    console.error(`failed to execute migration "${it.migrationName}"`)
    }
    })

    if (error) {
    console.error('failed to run `migrateToLatest`')
    console.error(error)
    }

    Returns Promise<MigrationResultSet>

Generated using TypeDoc