Registry / database / node-db-migration

node-db-migration

JSON →
library1.4.0jsnpmunverified

node-db-migration is a focused Node.js library designed for managing database schema evolution through simple SQL-based migration scripts. Currently at version 1.4.0, it offers robust support for popular relational databases including SQLite3, MySQL (or its modern fork `mysql2`), and PostgreSQL. Its core philosophy emphasizes using bare SQL files, allowing developers to maintain direct control over their database schemas without being tied to an ORM's migration DSL. The package operates by maintaining a dedicated `migrations` table within the database to track which scripts have been applied. It scans a specified directory for `.sql` files, enforcing a strict `YYYYMMDDHHmm-name.sql` naming convention to ensure chronological execution. Key features include sequential script execution, robust tracking of successful and failed migrations, and the ability to prevent further migrations upon failure until manual intervention. This helps ensure data consistency and provides a clear audit trail of schema changes. While its release cadence isn't rapid, it offers a stable and reliable solution for teams preferring a 'SQL-first' approach to database version control.

npm install node-db-migration
INSTALL
IMPORT
SIG · NODE-DB-MIGRATION
N
node-db-migration
databasejavascriptv1.4.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CommandsRunner
import { CommandsRunner } from 'node-db-migration';
const CommandsRunner = require('node-db-migration').CommandsRunner;
Primary class for orchestrating migrations. CommonJS users should destructure from `require`.
MysqlDriver
import { MysqlDriver } from 'node-db-migration';
import MysqlDriver from 'node-db-migration';
Specific driver for MySQL connections. Named import is required. Corresponding database client ('mysql' or 'mysql2') must be installed.
PsqlDriver
import { PsqlDriver } from 'node-db-migration';
let PsqlDriver = require('node-db-migration');
Specific driver for PostgreSQL connections. Named import is required. The 'pg' client must be installed.
SQLite3Driver
import { SQLite3Driver } from 'node-db-migration';
Specific driver for SQLite3 connections. Named import is required. The 'sqlite3' client must be installed.

This quickstart demonstrates how to set up and run database migrations using `node-db-migration` with a PostgreSQL database. It connects to a database, initializes the `CommandsRunner` with a `PsqlDriver` and a directory for SQL migration scripts, then executes the `migrate` command to apply pending changes.

import { CommandsRunner, PsqlDriver } from 'node-db-migration'; import { Client } from 'pg'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function runMigrations() { const client = new Client({ connectionString: process.env.DATABASE_URL ?? 'postgresql://postgres:@localhost:5432/test_db', }); try { await client.connect(); console.log('Connected to PostgreSQL database.'); const migrations = new CommandsRunner({ driver: new PsqlDriver(client), directoryWithScripts: path.join(__dirname, 'migrations'), // Ensure 'migrations' directory exists with .sql files migrationTable: 'my_app_migrations' // Optional: custom table name for migration tracking }); // Example: Create a dummy migration directory and file for demonstration // In a real app, these would be pre-existing. const fs = await import('fs/promises'); const migrationsDir = path.join(__dirname, 'migrations'); await fs.mkdir(migrationsDir, { recursive: true }); const migrationFileName = `${new Date().toISOString().replace(/[-:.]/g, '').substring(0, 14)}-create-users-table.sql`; await fs.writeFile(path.join(migrationsDir, migrationFileName), 'CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE);'); console.log('Running `migrate` command...'); await migrations.run('migrate'); console.log('Migrations completed successfully.'); // You can run other commands like 'list', 'getFailed', 'resolve' // console.log('\nListing unapplied migrations:'); // await migrations.run('list'); } catch (error) { console.error('Migration failed:', error); process.exit(1); } finally { await client.end(); console.log('Database connection closed.'); } } runMigrations();
node-db-migrate --version
Debug
Known issues
gotchaMigration SQL files must strictly adhere to the `YYYYMMDDHHmm-name.sql` naming convention (e.g., `201705231245-add-pets-table.sql`). Incorrect naming will prevent files from being recognized and executed.
fix
Ensure all `.sql` migration files in the `directoryWithScripts` follow the `date-name.sql` pattern, where the date is in `YYYYMMDDHHmm` format.
affects: >=1.0.0
breakingIf a migration script fails, `node-db-migration` will record the failure in the `migrations` table and *stop* further migrations until the failed entry is manually resolved. This is a design choice to ensure database consistency.
fix
Use the `resolve` command (`migrations.run('resolve')`) after fixing the SQL error, or manually update the `migrations` table to clear the failed status for the specific script, then rerun the `migrate` command.
affects: >=1.0.0
gotchaWhen using MySQL, if your migration scripts contain multiple SQL statements separated by semicolons, you *must* configure your `mysql` or `mysql2` connection with `multipleStatements: true`. Otherwise, only the first statement will execute.
fix
When creating your MySQL connection, add `{ multipleStatements: true }` to the connection options: `mysql.createConnection({ ..., multipleStatements: true });`
affects: >=1.0.0
gotchaThe database client (e.g., `pg`, `mysql`, `sqlite3`) must be separately installed as a dependency in your project, as `node-db-migration` only provides the drivers, not the underlying database connectors.
fix
Install the appropriate database client: `npm install pg`, `npm install mysql` (or `mysql2`), or `npm install sqlite3`.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Cannot find module 'pg'
The PostgreSQL client library ('pg') is not installed in your project.
fix
Install the 'pg' package: `npm install pg`
Error: ER_PARSE_ERROR: You have an error in your SQL syntax...
One of your `.sql` migration files contains invalid SQL syntax.
fix
Carefully review the SQL code in the indicated migration file for syntax errors specific to your database (e.g., MySQL, PostgreSQL, SQLite).
Error: SQLITE_ERROR: no such table: migrations
The `migrations` table (or your custom `migrationTable` name) does not exist in the database, meaning the `init` command was not run or failed.
fix
Execute the `init` command to create the migration tracking table: `migrations.run('init');`
Upgrade
Version history
1.4.0latest on npm
Audit
Dependencies
mysqloptionalRequired for MySQL database connections. 'mysql2' can also be used.
pgoptionalRequired for PostgreSQL database connections.
sqlite3optionalRequired for SQLite database connections.
Agent activity
6 hits · last 30 days
node
6
Resources
node-db-migration — npm install node-db-migration · libregistry