Knex Migrator
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
-
Error: Migration lock already exists. Please run 'knex-migrator rollback' or delete the lock table manually.
cause A previous migration process died or was interrupted, leaving a lock entry in the database.fixRun `npx knex-migrator rollback --force` to try and clear the lock and potentially revert partially applied migrations, or manually inspect and clear the `migrations_lock` table. -
Error: connect ECONNREFUSED 127.0.0.1:<PORT>
cause The database server is not running, is inaccessible, or the connection details in `MigratorConfig.js` are incorrect.fixVerify that the database server is running and reachable from the application's host, and double-check all connection parameters (host, port, user, password, database name) in `MigratorConfig.js`. -
Error: Knex client not installed: <client_name>. Install by: npm install <client_name>
cause The specified `client` in `MigratorConfig.js` (e.g., 'mysql2', 'sqlite3') does not have its corresponding npm package installed.fixInstall the necessary database client driver using `npm install <client_name>` or `yarn add <client_name>`. -
Error: No MigratorConfig.js found in the current directory or specified path.
cause The `MigratorConfig.js` file is missing, misspelled, or located in a directory not discoverable by `knex-migrator`.fixEnsure `MigratorConfig.js` is present in the project root or specify its path using the `--mgpath` CLI option.
Warnings
- gotcha knex-migrator does not support database replicas directly due to limitations in knex.js. Configure your application to handle replicas outside of the migration process.
- gotcha SQLite databases do not support read locks by default, which can lead to concurrency issues if multiple processes try to run migrations simultaneously.
- breaking Mixing DDL (Data Definition Language) and DML (Data Manipulation Language) statements within a single migration script is highly discouraged, especially in MySQL, where DDL statements implicitly commit transactions. This can lead to partial changes and data inconsistency if an error occurs.
- gotcha If the migration process terminates unexpectedly (e.g., process crash), the migration lock in the database might not be released. This prevents further migrations until manually cleared.
- gotcha It is highly recommended to implement both `up` (for applying) and `down` (for reverting) functions in every migration script. This ensures a reliable and complete rollback capability.
Install
-
npm install knex-migrator -
yarn add knex-migrator -
pnpm add knex-migrator
Imports
- KnexMigrator
import { KnexMigrator } from 'knex-migrator';import KnexMigrator from 'knex-migrator'; // Or for CommonJS: const KnexMigrator = require('knex-migrator'); - CLI Usage
npx knex-migrator init npx knex-migrator migrate npx knex-migrator rollback
- MigratorConfig.js
export default { /* ... config object ... */ };module.exports = { /* ... config object ... */ };
Quickstart
/* 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