Knex Automigrate

raw JSON →
0.1.8 verified Thu Apr 23 auth: no javascript

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.

error Error: Cannot find module 'knexfile'
cause The knex-automigrate command-line tool or programmatic execution cannot locate your `knexfile.js` configuration file.
fix
Ensure 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_`
cause A migration file in your migrations directory does not follow the required naming convention (e.g., `users.js` instead of `table_users.js`).
fix
Rename your migration files to start with 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
cause You are attempting to use advanced index migration features with a database dialect (e.g., PostgreSQL) that knex-automigrate does not yet fully support for this specific functionality.
fix
For advanced index management on unsupported dialects, consider implementing these changes using traditional Knex.js knex.schema.alterTable migrations until full support is added to knex-automigrate.
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.
fix Always review the project's GitHub releases or changelog (if available) before upgrading, and thoroughly test migrations in non-production environments.
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.
fix Ensure all schema definition files are named like `table_your_table_name.js` or `view_your_view_name.js` and placed in the configured migrations directory.
gotcha The documentation specifies that index migration support is currently limited, explicitly mentioning `mysql` as the only supported dialect for this feature.
fix If using other dialects (e.g., PostgreSQL, SQLite) and requiring advanced index management, manual Knex migrations might still be necessary for those specific operations, or verify if support has been added in newer undocumented versions.
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.
fix Install `knex-automigrate` as a development dependency (`npm install --save-dev knex-automigrate`) and run it via `npx knex-automigrate` or by defining scripts in your `package.json` (e.g., `"migrate": "knex-automigrate migrate:auto"`).
npm install knex-automigrate
yarn add knex-automigrate
pnpm add knex-automigrate

This quickstart demonstrates how to programmatically use `knex-automigrate` by setting up a `knexfile.js`, creating a `table_users.js` schema, and then executing the auto-migration process. It simulates the CLI workflow for a SQLite database.

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();