Knex Automigrate
raw JSON →knex-automigrate is a database migration tool built on top of Knex.js, offering a schema-based approach instead of traditional sequential migrations. It allows developers to define the desired state of database tables and views in dedicated `table_*.js` and `view_*.js` files within their migration directory. The tool then automatically generates and applies the necessary SQL statements to bring the database schema in sync with these definitions, abstracting away the manual `up` and `down` migration logic. Currently at version 0.1.8, the project appears to be under active maintenance, with recent updates supporting newer Knex.js versions (e.g., peer dependency `^3.1.0`). Its key differentiator is its declarative, state-based migration model which simplifies schema evolution and avoids the complexity of managing explicit forward and backward migration scripts for each change, contrasting with Knex's traditional delta-based migration system.
Common errors
error Error: Cannot find module 'knexfile' ↓
knexfile.js exists in the current working directory, or specify its path using the --knexfile [path] option (e.g., knex-automigrate --knexfile ./config/knexfile.js migrate:auto). error Automigrate failed: Error: Migration schema file name must be started with `table_` or `view_` ↓
table_ for table schemas (e.g., table_your_table_name.js) or view_ for view schemas (e.g., view_your_view_name.js). error Automigrate failed: Error: Dialect 'postgres' is not supported for index migration. Currently supported dialects: mysql ↓
knex.schema.alterTable migrations until full support is added to knex-automigrate. Warnings
breaking As a pre-1.0 package (currently 0.1.8), the API and behavior of knex-automigrate are subject to change without adhering to strict semantic versioning rules, potentially introducing breaking changes in minor versions. ↓
gotcha Migration schema files must strictly follow a naming convention, starting with `table_` for table schemas or `view_` for view schemas. Files not adhering to this convention will be ignored. ↓
gotcha The documentation specifies that index migration support is currently limited, explicitly mentioning `mysql` as the only supported dialect for this feature. ↓
gotcha The README suggests global installation (`npm install -g knex-automigrate`). While convenient for CLI, global installations can lead to versioning conflicts and are generally discouraged in favor of local project dependencies (`npm install --save-dev knex-automigrate`) combined with `npx` or npm scripts. ↓
Install
npm install knex-automigrate yarn add knex-automigrate pnpm add knex-automigrate Imports
- MigrateAuto wrong
const MigrateAuto = require('knex-automigrate');correctimport { MigrateAuto } from 'knex-automigrate'; - knex-automigrate (CLI)
knex-automigrate migrate:auto - auto (migration file export)
exports.auto = function(migrator, knex) { ... };
Quickstart
import knex from 'knex';
import { MigrateAuto } from 'knex-automigrate';
import path from 'path';
import fs from 'fs';
// Create a minimal knexfile.js for demonstration
const knexfilePath = path.join(process.cwd(), 'knexfile.js');
const knexConfig = `
module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './dev.sqlite3'
},
migrations: {
directory: './migrations'
},
useNullAsDefault: true
}
};
`;
fs.writeFileSync(knexfilePath, knexConfig);
// Create a migrations directory and a sample table schema file
const migrationsDir = path.join(process.cwd(), 'migrations');
if (!fs.existsSync(migrationsDir)) fs.mkdirSync(migrationsDir);
const tableUsersPath = path.join(migrationsDir, 'table_users.js');
const tableUsersSchema = `
exports.auto = function(migrator, knex) {
return [
migrator('users', function(table) {
table.increments('user_id').unsigned().comment('PK');
table.string('email', 128).notNullable().comment('E-Mail');
table.string('name', 128).notNullable().comment('Name');
table.timestamps(true, true);
})
];
};
`;
fs.writeFileSync(tableUsersPath, tableUsersSchema);
console.log('knexfile.js and table_users.js created.');
// Programmatic usage example (mimicking CLI behavior)
const config = require(knexfilePath).development;
const knexInstance = knex(config);
async function runAutomigrate() {
try {
const migrator = new MigrateAuto(knexInstance, config.migrations.directory);
await migrator.migrateAuto();
console.log('Automigrate completed successfully.');
} catch (error) {
console.error('Automigrate failed:', error);
} finally {
await knexInstance.destroy();
// Clean up created files/dirs for isolated example
fs.unlinkSync(knexfilePath);
fs.unlinkSync(tableUsersPath);
fs.rmdirSync(migrationsDir);
fs.unlinkSync('./dev.sqlite3');
}
}
runAutomigrate();