{"id":17734,"library":"knex-automigrate","title":"Knex Automigrate","description":"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.","status":"active","version":"0.1.8","language":"javascript","source_language":"en","source_url":"https://github.com/why2pac/knex-automigrate","tags":["javascript","nodejs","knexjs","database","orm","table","migration"],"install":[{"cmd":"npm install knex-automigrate","lang":"bash","label":"npm"},{"cmd":"yarn add knex-automigrate","lang":"bash","label":"yarn"},{"cmd":"pnpm add knex-automigrate","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core database query builder that knex-automigrate extends and depends upon for all database interactions.","package":"knex","optional":false}],"imports":[{"note":"Primarily a CLI tool, but the `MigrateAuto` class can be imported for programmatic usage. ESM is preferred.","wrong":"const MigrateAuto = require('knex-automigrate');","symbol":"MigrateAuto","correct":"import { MigrateAuto } from 'knex-automigrate';"},{"note":"The primary way to use knex-automigrate is via its command-line interface, typically after a global or local installation.","symbol":"knex-automigrate (CLI)","correct":"knex-automigrate migrate:auto"},{"note":"Within migration schema files (e.g., `table_users.js`), the `auto` function is exported, receiving `migrator` and `knex` instances from the tool.","symbol":"auto (migration file export)","correct":"exports.auto = function(migrator, knex) { ... };"}],"quickstart":{"code":"import knex from 'knex';\nimport { MigrateAuto } from 'knex-automigrate';\nimport path from 'path';\nimport fs from 'fs';\n\n// Create a minimal knexfile.js for demonstration\nconst knexfilePath = path.join(process.cwd(), 'knexfile.js');\nconst knexConfig = `\nmodule.exports = {\n  development: {\n    client: 'sqlite3',\n    connection: {\n      filename: './dev.sqlite3'\n    },\n    migrations: {\n      directory: './migrations'\n    },\n    useNullAsDefault: true\n  }\n};\n`;\nfs.writeFileSync(knexfilePath, knexConfig);\n\n// Create a migrations directory and a sample table schema file\nconst migrationsDir = path.join(process.cwd(), 'migrations');\nif (!fs.existsSync(migrationsDir)) fs.mkdirSync(migrationsDir);\n\nconst tableUsersPath = path.join(migrationsDir, 'table_users.js');\nconst tableUsersSchema = `\nexports.auto = function(migrator, knex) {\n  return [\n    migrator('users', function(table) {\n      table.increments('user_id').unsigned().comment('PK');\n      table.string('email', 128).notNullable().comment('E-Mail');\n      table.string('name', 128).notNullable().comment('Name');\n      table.timestamps(true, true);\n    })\n  ];\n};\n`;\nfs.writeFileSync(tableUsersPath, tableUsersSchema);\n\nconsole.log('knexfile.js and table_users.js created.');\n\n// Programmatic usage example (mimicking CLI behavior)\nconst config = require(knexfilePath).development;\nconst knexInstance = knex(config);\n\nasync function runAutomigrate() {\n  try {\n    const migrator = new MigrateAuto(knexInstance, config.migrations.directory);\n    await migrator.migrateAuto();\n    console.log('Automigrate completed successfully.');\n  } catch (error) {\n    console.error('Automigrate failed:', error);\n  } finally {\n    await knexInstance.destroy();\n    // Clean up created files/dirs for isolated example\n    fs.unlinkSync(knexfilePath);\n    fs.unlinkSync(tableUsersPath);\n    fs.rmdirSync(migrationsDir);\n    fs.unlinkSync('./dev.sqlite3');\n  }\n}\n\nrunAutomigrate();\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Always review the project's GitHub releases or changelog (if available) before upgrading, and thoroughly test migrations in non-production environments.","message":"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.","severity":"breaking","affected_versions":">=0.1.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"The documentation specifies that index migration support is currently limited, explicitly mentioning `mysql` as the only supported dialect for this feature.","severity":"gotcha","affected_versions":">=0.1.0"},{"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\"`).","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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`).","cause":"The knex-automigrate command-line tool or programmatic execution cannot locate your `knexfile.js` configuration file.","error":"Error: Cannot find module 'knexfile'"},{"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`).","cause":"A migration file in your migrations directory does not follow the required naming convention (e.g., `users.js` instead of `table_users.js`).","error":"Automigrate failed: Error: Migration schema file name must be started with `table_` or `view_`"},{"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.","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.","error":"Automigrate failed: Error: Dialect 'postgres' is not supported for index migration. Currently supported dialects: mysql"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}