{"id":16409,"library":"knex-umzug","title":"Knex Umzug Storage Adapter","description":"knex-umzug is a storage adapter for the umzug database migration library, designed to integrate umzug with knex.js for database interactions. It allows umzug to persist and manage migration states within a relational database using knex as the underlying query builder. The package is currently stable at version 4.1.1, with releases primarily driven by compatibility updates for umzug and knex, alongside bug fixes. A key feature is its support for namespacing and custom migration table names, which enables multiple isolated migration setups to share the same database while maintaining distinct migration states. Furthermore, it tracks comprehensive migration metadata including the current state, all migration paths, the hostname, and the system user who executed each migration, providing a detailed audit trail. This offers enhanced visibility and control over the migration process compared to simpler storage solutions.","status":"active","version":"4.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/marcbachmann/knex-umzug","tags":["javascript","umzug","knex","migration","database"],"install":[{"cmd":"npm install knex-umzug","lang":"bash","label":"npm"},{"cmd":"yarn add knex-umzug","lang":"bash","label":"yarn"},{"cmd":"pnpm add knex-umzug","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as the core migration orchestrator. knex-umzug provides the database storage mechanism for umzug.","package":"umzug","optional":false}],"imports":[{"note":"knex-umzug is a CommonJS package and exports its class as the default. For ESM/TypeScript, use a default import. For CommonJS, use `const KnexUmzug = require('knex-umzug');`","wrong":"import { KnexUmzug } from 'knex-umzug';","symbol":"KnexUmzug","correct":"import KnexUmzug from 'knex-umzug';"},{"note":"This is the standard CommonJS import for knex-umzug, which exports its class directly as `module.exports`.","symbol":"KnexUmzug (CJS)","correct":"const KnexUmzug = require('knex-umzug');"},{"note":"While umzug v3+ has a CJS fallback, its primary usage for modern projects, especially with TypeScript, is via ESM named imports. For CommonJS-only environments, `const { Umzug } = require('umzug');` can be used.","wrong":"const Umzug = require('umzug');","symbol":"Umzug (from peer dep)","correct":"import { Umzug } from 'umzug';"}],"quickstart":{"code":"import KnexUmzug from 'knex-umzug';\nimport { Umzug, migrator } from 'umzug';\nimport knex from 'knex';\n\nconst db = knex({\n  client: 'sqlite3',\n  connection: { filename: './migrations.sqlite' },\n  useNullAsDefault: true // Recommended for sqlite3 with knex\n});\n\n// Define your migrations directory\nconst migrationsPath = `${process.cwd()}/migrations`;\n\nconst umzug = new Umzug({\n  migrations: {\n    glob: `${migrationsPath}/*.js`,\n    // Optional: context can be passed to migration files\n    // context: db\n  },\n  storage: new KnexUmzug({\n    context: 'default',\n    connection: db,\n    tableName: 'umzug_migrations_table'\n  }),\n  logger: console // Or your preferred logger\n});\n\nasync function runMigrations() {\n  console.log('Starting migrations...');\n  try {\n    const migrations = await umzug.up();\n    console.log('Migrations finished successfully!', migrations);\n  } catch (error) {\n    console.error('Migration failed:', error);\n    process.exit(1);\n  } finally {\n    await db.destroy(); // Close the database connection\n  }\n}\n\n// Example migration file content (e.g., migrations/001-create-users-table.js)\n/*\nexport const up = async ({ context: sequelize }) => {\n  // Or knex object if passed via context\n  // await knex.schema.createTable('users', (table) => {\n  //   table.increments('id').primary();\n  //   table.string('name').notNullable();\n  //   table.timestamps(true, true);\n  // });\n};\n\nexport const down = async ({ context: sequelize }) => {\n  // await knex.schema.dropTable('users');\n};\n*/\n\n// Create a dummy migration file for demonstration\nimport fs from 'fs/promises';\nimport path from 'path';\nconst dummyMigrationContent = `\nexport const up = async ({ context: knexInstance }) => {\n  console.log('Running 001-create-test-table migration UP');\n  await knexInstance.schema.createTableIfNotExists('test_table', (table) => {\n    table.increments('id').primary();\n    table.string('name').notNullable();\n    table.timestamps(true, true);\n  });\n};\n\nexport const down = async ({ context: knexInstance }) => {\n  console.log('Running 001-create-test-table migration DOWN');\n  await knexInstance.schema.dropTableIfExists('test_table');\n};\n`;\n\nasync function setupAndRun() {\n  await fs.mkdir(migrationsPath, { recursive: true });\n  await fs.writeFile(path.join(migrationsPath, '001-create-test-table.js'), dummyMigrationContent);\n  await runMigrations();\n  // Clean up dummy migration file and directory\n  await fs.unlink(path.join(migrationsPath, '001-create-test-table.js'));\n  await fs.rmdir(migrationsPath);\n}\n\nsetupAndRun();","lang":"javascript","description":"Demonstrates initializing a Knex.js connection, configuring Umzug with KnexUmzug as its storage adapter, and running migrations. It also includes a runnable setup for a dummy migration file to illustrate the full flow."},"warnings":[{"fix":"Upgrade Node.js to version 12 or higher, or explicitly install `knex-umzug@^3.0.0` if Node.js 8/10 support is required.","message":"Version 4.0.0 of knex-umzug dropped official support for Node.js versions 8 and 10. Users on these older Node.js versions must remain on knex-umzug v3.x or upgrade their Node.js environment.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure your migration table (default: `migrations`) has an `id` column with a primary key constraint. If upgrading from an older version, review your database schema and add the primary key manually if necessary.","message":"With version 4.0.0, a primary key was added to the migrations table by default. While this improves data integrity, existing tables without a primary key might require manual alteration if an issue arises with index creation.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Most users are unlikely to be affected by this. If you encounter issues related to migration history not being found after upgrading from v2.x, ensure your `storageOptions` align with the `KnexUmzug` class constructor expectations rather than older string-based storage options.","message":"Version 3.0.0 removed 'legacy storage support' which was originally used internally at livingdocsIO. Although the release notes state it 'won't affect regular users at all', it's a fundamental change in how storage is handled.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"For `umzug` v3+, pass an instance of `new KnexUmzug(...)` to the `storage` property of the `Umzug` constructor. For `umzug` v2, pass the string `'knex-umzug'` to `storage` and `storageOptions` to the `Umzug` constructor. Always refer to the `knex-umzug` README for the correct `umzug` version-specific setup.","message":"Compatibility with `umzug` v2 vs. `umzug` v3+ requires different initialization patterns. `knex-umzug` v4.1.0 specifically addressed compatibility with `umzug@3`, but the usage in `storageOptions` differs significantly.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Configure your `package.json` with `\"type\": \"module\"` if all your files are ESM, or use `.mjs` extensions for ESM files. If using CommonJS for migrations, `module.exports.up = ...` will still work, but `umzug` v3+ documentation primarily shows ESM examples.","message":"When using `knex-umzug` with `umzug` v3+, the migration files themselves should often use ESM syntax (`export const up`, `export const down`). Ensure your Node.js environment is configured to handle ESM, or use a transpiler.","severity":"gotcha","affected_versions":">=4.1.0"},{"fix":"Ensure you are on `knex-umzug@4.1.1` or higher, especially if you use a custom table name for your `umzug_migrations_table` and encounter schema creation errors for the `id` column.","message":"The fix in v4.1.1 for 'add support for custom table name when adding id column' implies that prior versions might have had issues with creating the `id` column correctly when a non-default `tableName` was specified for the migration log.","severity":"gotcha","affected_versions":"<4.1.1"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For TypeScript/ESM projects, use `import { Umzug } from 'umzug';`. For CommonJS, ensure you're using `const { Umzug } = require('umzug');` (note the destructuring) as `umzug` v3 provides a CJS fallback that exports a named `Umzug`.","cause":"Attempting to `new Umzug()` using CommonJS `require` when `umzug` v3+ is primarily an ESM package, or when using an incorrect import style.","error":"TypeError: Umzug is not a constructor"},{"fix":"Use `import KnexUmzug from 'knex-umzug';` for ESM/TypeScript. For CommonJS, use `const KnexUmzug = require('knex-umzug');`.","cause":"Incorrect import statement for `KnexUmzug`, especially when trying to use named import syntax for a default export.","error":"TypeError: KnexUmzug is not a constructor"},{"fix":"Ensure your database user has sufficient permissions to create tables. KnexUmzug will create the table if it doesn't exist upon first `umzug.up()` call, but if there are underlying database connection or permission errors, it might fail silently or with a generic Knex error before reaching this point.","cause":"The configured migration table does not exist in the database and Umzug/KnexUmzug has not been configured to create it, or there are permission issues.","error":"Error: Migration table \"umzug_migrations_table\" does not exist."},{"fix":"Verify the `connection` details passed to `knex()` constructor are correct, including hostname, port, username, and password. Ensure the database server is running and accessible from where the application is hosted.","cause":"The Knex connection string or configuration points to a database host that cannot be resolved or reached.","error":"Error: getaddrinfo ENOTFOUND <database_host>"}],"ecosystem":"npm"}