Database migration framework for Node.js applications that enables developers to programmatically manage database schema changes and evolution over time.
npx @tessl/cli install tessl/npm-db-migrate@0.11.0db-migrate is a comprehensive database migration framework for Node.js applications that enables developers to programmatically manage database schema changes and evolution over time. It offers a unified API for creating, running, and tracking database migrations across multiple database systems including MySQL, PostgreSQL, SQLite3, and MongoDB, with support for both SQL and NoSQL databases.
npm install db-migrate (global) or npm install --save db-migrate (local)const dbMigrate = require('db-migrate');
const instance = dbMigrate.getInstance();For module usage:
const dbMigrate = require('db-migrate');
const instance = dbMigrate.getInstance(true, options, callback);Data types:
const { dataType } = require('db-migrate');
// or
const dbMigrate = require('db-migrate');
const dataType = dbMigrate.dataType;const dbMigrate = require('db-migrate');
// Create instance with default configuration
const instance = dbMigrate.getInstance();
// Run all pending migrations up
await instance.up();
// Create a new migration
await instance.create('add-users-table');
// Run migrations down (rollback)
await instance.down(1);
// Seed database
await instance.seed();Configuration with options:
const dbMigrate = require('db-migrate');
// Create instance with custom options
const instance = dbMigrate.getInstance(true, {
env: 'production',
config: './config/database.json',
cwd: process.cwd()
});
// Database operations
await instance.createDatabase('myapp_production');
await instance.up();
await instance.seed('vc');Using data types in migrations:
// Access data types from instance
const { dataType } = dbMigrate;
// Or from instance
const instance = dbMigrate.getInstance();
const types = instance.dataType;
// In migration file
exports.up = function(db) {
return db.createTable('products', {
id: { type: types.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: types.STRING, length: 255, notNull: true },
price: { type: types.DECIMAL, precision: 10, scale: 2 },
active: { type: types.BOOLEAN, defaultValue: true }
});
};db-migrate is built around several key components:
getInstance()) providing migration operations and configurationCore migration operations for running, creating, and managing database schema changes. Supports both CLI and programmatic usage with transaction support and rollback capabilities.
/**
* Execute up migrations to the latest or specified migration
* @param specification - Migration name (string), count (number), or callback (function)
* @param opts - Migration mode (string) or callback (function)
* @param callback - Completion callback (function)
* @returns Promise
*/
up(specification, opts, callback): Promise;
/**
* Execute down migrations (rollbacks) for specified count
* @param specification - Count (number) or callback (function)
* @param opts - Migration mode (string) or callback (function)
* @param callback - Completion callback (function)
* @returns Promise
*/
down(specification, opts, callback): Promise;
/**
* Create a new migration file with specified name
* @param migrationName - Name for the migration file
* @param scope - Migration scope/mode (string) or callback (function)
* @param callback - Completion callback (function)
* @returns Promise
*/
create(migrationName, scope, callback): Promise;Database-level operations for creating and dropping databases, useful for environment setup and teardown.
/**
* Create a database with the specified name
* @param dbname - Name of database to create
* @param callback - Completion callback (function)
* @returns Promise
*/
createDatabase(dbname, callback): Promise;
/**
* Drop a database with the specified name
* @param dbname - Name of database to drop
* @param callback - Completion callback (function)
* @returns Promise
*/
dropDatabase(dbname, callback): Promise;Data seeding functionality for populating databases with initial or test data. Supports both version-controlled and static seeding approaches.
/**
* Execute database seeding operations
* @param mode - Seeding mode: 'vc' (version controlled) or 'static'
* @param scope - Seeding scope/mode (string) or callback (function)
* @param callback - Completion callback (function)
* @returns Promise
*/
seed(mode, scope, callback): Promise;
/**
* Undo seed operations (rollback seeding)
* @param specification - Count (number) or callback (function)
* @param scope - Seeding scope/mode (string)
* @param callback - Completion callback (function)
* @returns Promise
*/
undoSeed(specification, scope, callback): Promise;Configuration system for setting up database connections, environments, and migration settings. Supports multiple configuration sources and runtime parameter modification.
/**
* Add a configuration option with CLI argument support
* @param description - Description of the configuration option
* @param args - Array of argument names, first is primary name
* @param type - Argument type: 'string' or 'boolean'
* @returns boolean - Success status
*/
addConfiguration(description, args, type): boolean;
/**
* Set a configuration parameter value
* @param param - Parameter name
* @param value - Parameter value
* @returns value - The set value
*/
setConfigParam(param, value): any;
/**
* Register and initialize API hooks for plugins
* @param callback - Completion callback (function)
* @returns Promise
*/
registerAPIHook(callback): Promise;
/**
* Control global log output
* @param isSilent - True to silence all output, false to enable
* @returns boolean - Previous silence state
*/
silence(isSilent): boolean;
/**
* Reset to default completion callback
*/
setDefaultCallback(): void;
/**
* Set custom completion callback
* @param callback - Custom completion callback function
*/
setCustomCallback(callback): void;
/**
* Execute default CLI routine
*/
run(): void;Database interface methods available within migration and seed files for database schema management and data manipulation. Provides unified API across different database drivers.
// DDL Operations
createTable(tableName, options, callback): Promise;
dropTable(tableName, callback): Promise;
addColumn(tableName, columnName, columnSpec, callback): Promise;
addIndex(tableName, indexName, columns, callback): Promise;
// DML Operations (Seeds)
insert(tableName, data, callback): Promise;
update(tableName, data, where, callback): Promise;
delete(tableName, where, callback): Promise;
// SQL Execution
runSql(sql, params, callback): Promise;Command-line interface providing comprehensive migration and database management tools. Supports all programmatic operations through terminal commands.
# Run migrations up
db-migrate up [migration-name]
# Run migrations down
db-migrate down [count]
# Create new migration
db-migrate create <migration-name>
# Database operations
db-migrate db:create <database-name>
db-migrate db:drop <database-name>/**
* Main db-migrate instance interface
*/
interface DbMigrateInstance {
/** Data type constants for migration definitions */
dataType: DataTypeConstants;
/** Package version */
version: string;
/** Internal configuration object */
internals: InternalsConfig;
/** Loaded configuration */
config: Config;
}
/**
* Internal configuration object containing runtime state
*/
interface InternalsConfig {
/** Whether running as module or CLI */
isModule: boolean;
/** Current migration protocol version */
migrationProtocol: number;
/** Plugin management functions */
plugins: object;
/** Command loader function */
load: Function;
/** Completion callback function */
onComplete: Function;
/** Current working directory */
cwd: string;
/** Current environment name */
currentEnv?: string;
/** Migration mode/scope */
migrationMode?: string;
/** Matching pattern for scoped migrations */
matching?: string;
/** Configuration file path */
configFile?: string;
/** Configuration object */
configObject?: object;
/** Command line options */
cmdOptions?: object;
/** CLI arguments */
argv: object;
}
/**
* Factory function options for creating db-migrate instance
*/
interface InstanceOptions {
/** Current working directory */
cwd?: string;
/** Disable plugin loading */
noPlugins?: boolean;
/** Custom plugins object */
plugins?: object;
/** Configuration file path or object */
config?: string | object;
/** Environment name */
env?: string;
/** Command options for module usage */
cmdOptions?: object;
/** Use static command loader */
staticLoader?: boolean;
/** Prevent error event registration */
throwUncatched?: boolean;
}
/**
* Data type constants for creating columns in migrations
*/
interface DataTypeConstants {
STRING: 'string'; // VARCHAR type
TEXT: 'text'; // TEXT/LONGTEXT type
INTEGER: 'int'; // INTEGER type
BIGINT: 'bigint'; // BIGINT type
DATE_TIME: 'datetime'; // DATETIME/TIMESTAMP type
DATE: 'date'; // DATE type
TIME: 'time'; // TIME type
BOOLEAN: 'boolean'; // BOOLEAN/TINYINT(1) type
DECIMAL: 'decimal'; // DECIMAL/NUMERIC type
FLOAT: 'real'; // FLOAT/REAL type
BINARY: 'binary'; // BINARY/VARBINARY type
BLOB: 'blob'; // BLOB type
}
/**
* Database interface available in migration and seed files
*/
interface DatabaseInterface {
// DDL Operations
createTable(tableName: string, options: TableSpec, callback?: Function): Promise<any>;
dropTable(tableName: string, callback?: Function): Promise<any>;
renameTable(tableName: string, newTableName: string, callback?: Function): Promise<any>;
addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback?: Function): Promise<any>;
removeColumn(tableName: string, columnName: string, callback?: Function): Promise<any>;
renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback?: Function): Promise<any>;
changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback?: Function): Promise<any>;
// Index Operations
addIndex(tableName: string, indexName: string, columns: string | string[], unique?: boolean, callback?: Function): Promise<any>;
removeIndex(tableName: string, indexName: string, callback?: Function): Promise<any>;
// Foreign Key Operations
addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: object, rules?: object, callback?: Function): Promise<any>;
removeForeignKey(tableName: string, keyName: string, callback?: Function): Promise<any>;
// SQL Operations
runSql(sql: string, params?: any[], callback?: Function): Promise<any>;
all(sql: string, params?: any[], callback?: Function): Promise<any[]>;
// Data Operations (Seeds)
insert(tableName: string, data: object | object[], callback?: Function): Promise<any>;
update(tableName: string, data: object, where: object, callback?: Function): Promise<any>;
delete(tableName: string, where: object, callback?: Function): Promise<any>;
lookup(tableName: string, column: string, value: any, callback?: Function): Promise<any[]>;
truncate(tableName: string, callback?: Function): Promise<any>;
}
/**
* Table specification for createTable operations
*/
interface TableSpec {
[columnName: string]: ColumnSpec;
}
/**
* Column specification for table operations
*/
interface ColumnSpec {
type: string;
length?: number;
precision?: number;
scale?: number;
notNull?: boolean;
defaultValue?: any;
primaryKey?: boolean;
autoIncrement?: boolean;
unique?: boolean;
foreignKey?: ForeignKeySpec;
}
/**
* Foreign key specification
*/
interface ForeignKeySpec {
name: string;
table: string;
rules?: {
onDelete?: 'CASCADE' | 'RESTRICT' | 'SET NULL';
onUpdate?: 'CASCADE' | 'RESTRICT' | 'SET NULL';
};
}