Knex Umzug Storage Adapter

4.1.1 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import KnexUmzug from 'knex-umzug';
import { Umzug, migrator } from 'umzug';
import knex from 'knex';

const db = knex({
  client: 'sqlite3',
  connection: { filename: './migrations.sqlite' },
  useNullAsDefault: true // Recommended for sqlite3 with knex
});

// Define your migrations directory
const migrationsPath = `${process.cwd()}/migrations`;

const umzug = new Umzug({
  migrations: {
    glob: `${migrationsPath}/*.js`,
    // Optional: context can be passed to migration files
    // context: db
  },
  storage: new KnexUmzug({
    context: 'default',
    connection: db,
    tableName: 'umzug_migrations_table'
  }),
  logger: console // Or your preferred logger
});

async function runMigrations() {
  console.log('Starting migrations...');
  try {
    const migrations = await umzug.up();
    console.log('Migrations finished successfully!', migrations);
  } catch (error) {
    console.error('Migration failed:', error);
    process.exit(1);
  } finally {
    await db.destroy(); // Close the database connection
  }
}

// Example migration file content (e.g., migrations/001-create-users-table.js)
/*
export const up = async ({ context: sequelize }) => {
  // Or knex object if passed via context
  // await knex.schema.createTable('users', (table) => {
  //   table.increments('id').primary();
  //   table.string('name').notNullable();
  //   table.timestamps(true, true);
  // });
};

export const down = async ({ context: sequelize }) => {
  // await knex.schema.dropTable('users');
};
*/

// Create a dummy migration file for demonstration
import fs from 'fs/promises';
import path from 'path';
const dummyMigrationContent = `
export const up = async ({ context: knexInstance }) => {
  console.log('Running 001-create-test-table migration UP');
  await knexInstance.schema.createTableIfNotExists('test_table', (table) => {
    table.increments('id').primary();
    table.string('name').notNullable();
    table.timestamps(true, true);
  });
};

export const down = async ({ context: knexInstance }) => {
  console.log('Running 001-create-test-table migration DOWN');
  await knexInstance.schema.dropTableIfExists('test_table');
};
`;

async function setupAndRun() {
  await fs.mkdir(migrationsPath, { recursive: true });
  await fs.writeFile(path.join(migrationsPath, '001-create-test-table.js'), dummyMigrationContent);
  await runMigrations();
  // Clean up dummy migration file and directory
  await fs.unlink(path.join(migrationsPath, '001-create-test-table.js'));
  await fs.rmdir(migrationsPath);
}

setupAndRun();

view raw JSON →