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
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
DBMigrate
✓ const DBMigrate = require('db-migrate');
✗ import DBMigrate from 'db-migrate';
db-migrate is a CommonJS module. Direct ES module `import` syntax is not officially supported and might require transpilation or dynamic `import()` in pure ESM environments.
getInstance (default)
✓ const dbmigrate = DBMigrate.getInstance(true);
✗ const dbmigrate = new DBMigrate();
The primary way to interact with db-migrate programmatically is by obtaining an instance through `getInstance()`. Passing `true` as the first argument loads a default instance with default options, typically reading `database.json` from `process.cwd()`.
getInstance (custom options)
✓ const dbmigrate = DBMigrate.getInstance(false, { cwd: __dirname, env: 'production' });
✗ const dbmigrate = DBMigrate.getInstance({ cwd: __dirname });
To create a custom db-migrate instance with specific options (e.g., custom current working directory `cwd` or environment `env`), pass `false` as the first argument to `getInstance()`, followed by an options object.
This quickstart demonstrates the programmatic use of db-migrate to define and run both 'up' and 'down' migrations against an in-memory SQLite database, cleaning up all generated files afterward.
import DBMigrate from 'db-migrate';
import path from 'path';
import fs from 'fs';
async function runExampleMigrations() {
const migrationsDirPath = path.join(__dirname, 'migrations');
// Ensure migrations directory exists for db-migrate to scan
if (!fs.existsSync(migrationsDirPath)) {
fs.mkdirSync(migrationsDirPath);
}
// Create a simple migration file (up and down)
const migrationName = `create-test-table-${Date.now()}`;
const migrationFilePath = path.join(migrationsDirPath, `${migrationName}.js`);
const migrationContent = `
'use strict';
var dbm;
var type;
var seed;
exports.setup = function(options) {
dbm = options.dbmigrate;
type = options.type;
seed = options.seed;
};
exports.up = function(db) {
console.log('Running UP migration: ${migrationName}');
return db.createTable('test_table', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
value: { type: 'string', length: 255 }
});
};
exports.down = function(db) {
console.log('Running DOWN migration: ${migrationName}');
return db.dropTable('test_table');
};
exports._meta = {
"version": 1
};
`;
fs.writeFileSync(migrationFilePath, migrationContent);
console.log(`Generated migration file: ${migrationName}.js`);
// Create a minimal database.json for an in-memory SQLite database
const configPath = path.join(__dirname, 'database.json');
const dbConfig = {
"dev": {
"driver": "sqlite3",
"filename": ":memory:", // Use in-memory SQLite for easy testing
"host": "localhost", // Required by some db-migrate internals even for sqlite3
"database": "testdb" // Required by some db-migrate internals
}
};
fs.writeFileSync(configPath, JSON.stringify(dbConfig, null, 2));
console.log('Generated database.json for in-memory SQLite.');
let dbmigrate;
try {
// Initialize db-migrate with options
dbmigrate = DBMigrate.getInstance(true, {
cwd: __dirname, // Important for db-migrate to find config and migrations
env: 'dev'
});
console.log('\n--- Running UP migrations ---');
await dbmigrate.up();
console.log('UP migrations complete.');
console.log('\n--- Running DOWN migrations ---');
await dbmigrate.down();
console.log('DOWN migrations complete.');
} catch (error) {
console.error('Migration failed:', error);
process.exit(1);
} finally {
// Cleanup generated files
if (fs.existsSync(migrationFilePath)) {
fs.unlinkSync(migrationFilePath);
}
if (fs.existsSync(configPath)) {
fs.unlinkSync(configPath);
}
if (fs.existsSync(migrationsDirPath)) {
fs.rmdirSync(migrationsDirPath, { recursive: true });
}
}
}
runExampleMigrations();
db-migrate --version
Errors
Common errors & fixes
Error: Cannot find module 'db-migrate-<driver>'
The required database driver package (e.g., 'db-migrate-pg' for PostgreSQL) is not installed or incorrectly named.
fixInstall the missing driver: `npm install db-migrate-<driver>` (e.g., `npm install db-migrate-pg`). Ensure the driver name in `database.json` matches the installed package suffix.
Error: No database config found!
db-migrate could not find a `database.json` file in the current working directory or the directory specified by the `cwd` option.
fixCreate a `database.json` file in your project root or ensure the `cwd` option for `DBMigrate.getInstance()` points to the correct directory where `database.json` resides.
Error: db-migrate connection error. Please check your database credentials or connection string.
db-migrate failed to establish a connection to the database. This is typically due to incorrect credentials, host, port, database name in `database.json`, or the database server not running/being inaccessible.
fixVerify all connection details in your `database.json` for the selected environment. Ensure the database server is running and accessible from the machine running db-migrate.
TypeError: db.createTable is not a function (or similar for other DBMigrate API methods)
This error usually indicates an issue with how the migration file `exports.up` or `exports.down` is structured, specifically if the `db` object passed to these functions is not being correctly used.
fixEnsure your migration files correctly define `exports.setup = function(options) { dbm = options.dbmigrate; ... };` and that `exports.up = function(db) { ... };` and `exports.down = function(db) { ... };` use the `db` object passed to them, which contains the API methods like `createTable`, `addColumn`, etc. Audit
Dependencies
db-migrate-pgoptionalRequired for PostgreSQL database support.
db-migrate-mysqloptionalRequired for MySQL database support.
db-migrate-sqlite3optionalRequired for SQLite database support.
db-migrate-mssqloptionalRequired for Microsoft SQL Server database support.