Knex Migrator

5.3.2 · active · verified Wed Apr 22

knex-migrator is a robust database migration tool built on top of knex.js, specifically designed to handle complex schema changes and initializations. Currently at version 5.3.2, it is known for its stability and is actively used in production by platforms like Ghost CMS. Key features include distinct differentiation between database initialization and subsequent migrations, support for a structured database schema, comprehensive rollback capabilities with auto-rollback on error, transactional migrations, and a migration lock mechanism to prevent concurrent execution. It supports MySQL and SQLite3. The tool emphasizes a strict separation of DDL (Data Definition Language) and DML (Data Manipulation Language) statements within migration scripts to ensure atomic operations and prevent implicit commits, which is a critical differentiator for maintaining data integrity during schema evolution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `knex-migrator` with an SQLite3 database, configure `MigratorConfig.js`, create a basic `init` migration file, and execute the initial migration using the CLI.

/* MigratorConfig.js */
module.exports = {
  database: {
    client: process.env.DB_CLIENT || 'sqlite3',
    connection: {
      filename: process.env.DB_FILENAME || './dev.sqlite3'
    }
  },
  migrationPath: __dirname + '/migrations',
  currentVersion: '1.0'
};

/* migrations/init/1-create-users-table.js */
exports.up = function (knex) {
  return knex.schema.createTable('users', function (table) {
    table.increments('id').primary();
    table.string('name').notNullable();
    table.string('email').unique().notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable('users');
};

// To run:
// 1. Install `knex` and `knex-migrator`, e.g., `npm install knex sqlite3 knex-migrator`
// 2. Create `MigratorConfig.js` and `migrations/init/1-create-users-table.js` as above.
// 3. Run initial migration:
//    npx knex-migrator init
// 4. Then run any subsequent migrations (e.g., after adding new migration files to `migrations/versions/1.0/`):
//    npx knex-migrator migrate

view raw JSON →