or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-interface.mdconfiguration-management.mddata-seeding.mddatabase-interface.mddatabase-operations.mdindex.mdmigration-management.md
tile.json

migration-management.mddocs/

Migration Management

Core migration operations for running, creating, and managing database schema changes. db-migrate provides comprehensive migration functionality with support for both CLI and programmatic usage, transaction support, and rollback capabilities.

Capabilities

Execute Up Migrations

Run pending migrations forward to apply schema changes to the database.

/**
 * 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;

Usage Examples:

const dbMigrate = require('db-migrate');
const instance = dbMigrate.getInstance();

// Run all pending migrations
await instance.up();

// Run up to a specific migration by name
await instance.up('20231201120000-add-users-table');

// Run a specific number of migrations
await instance.up(3);

// With callback
instance.up((err) => {
  if (err) console.error('Migration failed:', err);
  else console.log('Migrations completed');
});

// With migration mode/scope
await instance.up('admin-schema');

Execute Down Migrations

Run migrations backward to rollback schema changes and undo database modifications.

/**
 * 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;

Usage Examples:

// Rollback the last migration
await instance.down(1);

// Rollback the last 3 migrations
await instance.down(3);

// With callback
instance.down(2, (err) => {
  if (err) console.error('Rollback failed:', err);
  else console.log('Rollback completed');
});

// With migration mode/scope
await instance.down(1, 'admin-schema');

Create Migration Files

Generate new migration files with proper naming and template structure.

/**
 * 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;

Usage Examples:

// Create a new migration
await instance.create('add-users-table');

// Create migration with specific scope
await instance.create('add-admin-users', 'admin-schema');

// With callback
instance.create('add-products-table', (err, migration) => {
  if (err) console.error('Failed to create migration:', err);
  else console.log('Created migration:', migration.title);
});

Sync to Specific Migration

Synchronize database to a specific migration state, running up or down as needed.

/**
 * Sync database to a specific migration state
 * @param specification - Target migration name (string)
 * @param opts - Migration mode (string) or callback (function)
 * @param callback - Completion callback (function)
 * @returns Promise
 */
sync(specification, opts, callback): Promise;

Usage Examples:

// Sync to specific migration
await instance.sync('20231201120000-add-users-table');

// Sync with migration scope
await instance.sync('20231201120000-add-users-table', 'admin-schema');

Reset All Migrations

Reset database by rolling back all applied migrations.

/**
 * Reset database by rolling back all migrations
 * @param scope - Migration scope/mode (string) or callback (function)
 * @param callback - Completion callback (function)
 * @returns Promise
 */
reset(scope, callback): Promise;

Usage Examples:

// Reset all migrations
await instance.reset();

// Reset with specific scope
await instance.reset('admin-schema');

// With callback
instance.reset((err) => {
  if (err) console.error('Reset failed:', err);
  else console.log('Database reset completed');
});

Check Migration Status

Check pending migrations without executing them and report their status.

/**
 * Check pending migrations without executing them
 * @param specification - Count (number) or callback (function)
 * @param opts - Migration mode (string) or callback (function)
 * @param callback - Completion callback (function)  
 * @returns Promise<string[]> - Array of pending migration names
 */
check(specification, opts, callback): Promise<string[]>;

Usage Examples:

// Check all pending migrations
await instance.check();

// Check specific number of pending migrations
await instance.check(5);

// With migration scope
await instance.check(null, 'admin-schema');

Transition Migration Protocol

Transition existing migrations to the latest migration protocol version.

/**
 * Transition migrations to the latest defined protocol
 */
transition(): void;

Usage Example:

// Transition to latest protocol
instance.transition();

Migration Template Types

db-migrate supports different template types for migration file generation:

/**
 * Migration template type constants
 */
const TemplateType = {
  DEFAULT_JS: 0,                          // Standard JavaScript migration
  DEFAULT_SQL: 1,                         // SQL file migration
  SQL_FILE_LOADER: 2,                     // SQL file loader migration
  DEFAULT_COFFEE: 3,                      // CoffeeScript migration
  COFFEE_SQL_FILE_LOADER: 4,              // CoffeeScript SQL file loader
  SQL_FILE_LOADER_IGNORE_ON_INIT: 5       // Conditional SQL file loader
};

Template Selection:

// Creating different migration types via CLI
db-migrate create add-users-table                    // DEFAULT_JS (default)
db-migrate create add-users-table --sql-file         // DEFAULT_SQL
db-migrate create add-users-table --coffee-file      // DEFAULT_COFFEE
db-migrate create add-users-table --ignore-on-init   // SQL_FILE_LOADER_IGNORE_ON_INIT

Migration File Structure

When creating migrations, db-migrate generates files with the following structure:

JavaScript Migration:

'use strict';

var dbm;
var type;
var seed;

/**
 * We receive the dbmigrate dependency from dbmigrate initially.
 * This enables us to not have to rely on NODE_PATH.
 */
exports.setup = function(options, seedLink) {
  dbm = options.dbmigrate;
  type = dbm.dataType;
  seed = seedLink;
};

exports.up = function(db) {
  return db.createTable('users', {
    id: { type: 'int', primaryKey: true, autoIncrement: true },
    name: { type: 'string', length: 255, notNull: true },
    email: { type: 'string', length: 255, unique: true },
    created_at: { type: 'datetime', defaultValue: 'now()' }
  });
};

exports.down = function(db) {
  return db.dropTable('users');
};

exports._meta = {
  "version": 1
};

SQL Migration:

-- Up migration
CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Down migration  
DROP TABLE users;

Migration Modes and Scoping

db-migrate supports migration scoping for organizing migrations into different contexts:

Directory Structure:

migrations/
├── admin-schema/
│   ├── config.json
│   ├── 20231201120000-add-admin-users.js
│   └── 20231201130000-add-admin-roles.js
├── user-schema/
│   ├── config.json
│   └── 20231201140000-add-user-profiles.js
└── 20231201100000-initial-setup.js

Scoped Operations:

// Run migrations in specific scope
await instance.up('admin-schema');
await instance.down(1, 'user-schema');
await instance.create('add-permissions', 'admin-schema');

Error Handling

All migration operations can throw errors for various conditions:

try {
  await instance.up();
} catch (error) {
  console.error('Migration failed:', error.message);
  // Handle specific error types
  if (error.code === 'ENOENT') {
    console.error('Migration file not found');
  } else if (error.code === 'ECONNREFUSED') {
    console.error('Database connection failed');
  }
}

Types

/**
 * Migration specification for targeting specific migrations
 */
type MigrationSpecification = string | number | (() => void);

/**
 * Migration options for scoping and mode selection
 */
type MigrationOptions = string | (() => void);

/**
 * Migration callback function signature
 */
type MigrationCallback = (error?: Error, result?: any) => void;