Configuration

Complete guide to configuring Migration Script Runner

Table of contents

  1. Overview
  2. Quick Start
    1. Basic Configuration
  3. Config Class
    1. Creating a Config
    2. Config Categories
  4. Configuration Workflow
    1. 1. Choose Your Rollback Strategy
    2. 2. Configure Migration Discovery
    3. 3. Configure Validation
    4. 4. Configure Transactions
    5. 5. Configure Backup (if using BACKUP strategy)
  5. Complete Example
  6. Waterfall Configuration Loading
    1. Loading Priority
    2. Automatic Loading
    3. Manual Loading with ConfigLoader
  7. Environment Variables
  8. Configuration Files
    1. Supported Formats
    2. JavaScript Configuration
    3. JSON Configuration
    4. YAML Configuration
    5. TOML Configuration
    6. XML Configuration
    7. Specifying Config File
  9. Environment-Specific Configuration (Legacy)
  10. Default Values
  11. Configuration Patterns
    1. Development Configuration
    2. CI/CD Configuration
    3. Production Configuration
  12. Configuration Topics
  13. Next Steps

Overview

Migration Script Runner uses the Config class to control all aspects of migration behavior. Configuration is organized into several categories:


Quick Start

Basic Configuration

import { Config, MigrationScriptExecutor } from '@migration-script-runner/core';
import { MyDatabaseHandler } from './database-handler';

// Create configuration
const config = new Config();

// Set migration folder
config.folder = './migrations';

// Initialize and run
const handler = new MyDatabaseHandler();
const executor = new MigrationScriptExecutor({ handler }, config);

await executor.up();

Config Class

The Config class controls the behavior of the migration system.

Creating a Config

import { Config } from '@migration-script-runner/core';

const config = new Config();

Config Categories

Category Properties Description
🎯 Migration Settings folder, filePattern, tableName, displayLimit, beforeMigrateName, recursive Control how migrations are discovered and tracked
🎚️ Logging Settings logLevel, showBanner Configure output verbosity and display options
Validation Settings validateBeforeRun, strictValidation, downMethodPolicy, customValidators Control validation behavior and rules
🔄 Rollback Settings rollbackStrategy Choose backup, down(), both, or none
💾 Backup Settings backup (BackupConfig) Configure backup file naming and storage
🔒 Transaction Settings transaction (TransactionConfig) Configure transaction mode, isolation level, and retry behavior

Configuration Workflow

1. Choose Your Rollback Strategy

Start by deciding how you want to handle rollback:

import { RollbackStrategy } from '@migration-script-runner/core';

// Option 1: Backup/restore (default)
config.rollbackStrategy = RollbackStrategy.BACKUP;

// Option 2: Use down() methods
config.rollbackStrategy = RollbackStrategy.DOWN;

// Option 3: Try down() first, fallback to backup
config.rollbackStrategy = RollbackStrategy.BOTH;

// Option 4: No rollback (development only)
config.rollbackStrategy = RollbackStrategy.NONE;

See Rollback Settings for detailed comparison.

2. Configure Migration Discovery

Set where and how to find migration files:

// Migration folder
config.folder = './database/migrations';

// File pattern
config.filePatterns = [/^V(\d+)_(.+)\.ts$/];

// Enable recursive scanning
config.recursive = true;

See Migration Settings for all options.

3. Configure Validation

Control validation behavior:

import { DownMethodPolicy } from '@migration-script-runner/core';

// Enable validation (recommended)
config.validateBeforeRun = true;

// Choose down() policy based on rollback strategy
config.downMethodPolicy = DownMethodPolicy.AUTO;

// Add custom validators
config.customValidators = [new MyValidator()];

See Validation Settings for validation options.

4. Configure Transactions

Control how migrations are wrapped in database transactions:

import { TransactionMode, IsolationLevel } from '@migration-script-runner/core';

// Standard approach: Each migration in its own transaction
config.transaction.mode = TransactionMode.PER_MIGRATION;
config.transaction.isolation = IsolationLevel.READ_COMMITTED;
config.transaction.retries = 3;

// Batch mode: All migrations in one transaction
config.transaction.mode = TransactionMode.PER_BATCH;

// No automatic transactions (for NoSQL or custom logic)
config.transaction.mode = TransactionMode.NONE;

See Transaction Settings for all transaction options.

5. Configure Backup (if using BACKUP strategy)

If using BACKUP or BOTH strategies:

import { BackupConfig } from '@migration-script-runner/core';

config.backup = new BackupConfig();
config.backup.folder = './backups';
config.backup.deleteBackup = true;

See Backup Settings for backup options.


Complete Example

Production-ready configuration:

import {
    Config,
    BackupConfig,
    RollbackStrategy,
    DownMethodPolicy,
    TransactionMode,
    IsolationLevel,
    MigrationScriptExecutor
} from '@migration-script-runner/core';
import { MyDatabaseHandler } from './database-handler';

// Create configuration
const config = new Config();

// Migration settings
config.folder = './database/migrations';
config.filePatterns = [/^V(\d+)_(.+)\.ts$/];
config.tableName = 'migration_history';
config.displayLimit = 20;
config.beforeMigrateName = 'beforeMigrate';
config.recursive = true;

// Validation settings
config.validateBeforeRun = true;
config.strictValidation = process.env.CI === 'true';
config.downMethodPolicy = DownMethodPolicy.AUTO;

// Transaction settings
config.transaction.mode = TransactionMode.PER_MIGRATION;
config.transaction.isolation = IsolationLevel.READ_COMMITTED;
config.transaction.retries = 3;
config.transaction.retryDelay = 100;
config.transaction.retryBackoff = true;

// Rollback strategy
config.rollbackStrategy = RollbackStrategy.BOTH;

// Backup settings (for BACKUP/BOTH strategies)
config.backup = new BackupConfig();
config.backup.folder = './database/backups';
config.backup.deleteBackup = true;
config.backup.timestamp = true;
config.backup.timestampFormat = 'YYYYMMDD-HHmmss';
config.backup.prefix = 'db-backup';

// Custom validators (optional)
if (process.env.NODE_ENV === 'production') {
    config.customValidators = [
        new NamingValidator(),
        new DocumentationValidator()
    ];
}

// Initialize executor
const handler = new MyDatabaseHandler();
const executor = new MigrationScriptExecutor({ handler }, config);

// Run migrations
await executor.migrate();

Waterfall Configuration Loading

MSR supports automatic configuration loading using a waterfall approach with environment variables and config files. This follows 12-Factor App principles for production-ready applications.

Loading Priority

Configuration is loaded in this order (highest priority last):

  1. Built-in defaults - From Config class defaults
  2. Config file - Auto-detected or from MSR_CONFIG_FILE Supported formats: .js, .json, .yaml, .yml, .toml, .xml
  3. Environment variables - MSR_* environment variables
  4. Constructor overrides - Passed directly to MigrationScriptExecutor

Automatic Loading

With v0.5.0+, configuration is loaded automatically if not provided:

import { MigrationScriptExecutor } from '@migration-script-runner/core';
import { MyDatabaseHandler } from './database-handler';

// Automatically loads config from env vars, files, or defaults
const handler = new MyDatabaseHandler();
const executor = new MigrationScriptExecutor({ handler });

await executor.up();

Manual Loading with ConfigLoader

For more control, use ConfigLoader.load():

import { ConfigLoader, MigrationScriptExecutor } from '@migration-script-runner/core';

// Load with waterfall approach (auto-detect config file)
const config = ConfigLoader.load();

// Load with overrides (highest priority)
const config = ConfigLoader.load({
    folder: './migrations',
    dryRun: true
});

// Load from specific directory
const config = ConfigLoader.load({}, { baseDir: '/app' });

// Use specific config file (any format)
const config = ConfigLoader.load({}, {
    configFile: './config/production.yaml'
});

const handler = new MyDatabaseHandler();
const executor = new MigrationScriptExecutor({ handler }, config);

Environment Variables

Configure MSR using MSR_* environment variables - the recommended approach for production deployments following 12-Factor App principles.

Quick Example:

export MSR_FOLDER=./database/migrations
export MSR_TABLE_NAME=migration_history
export MSR_LOGGING_ENABLED=true
export MSR_BACKUP_FOLDER=./backups

Complete Documentation:


Configuration Files

MSR supports multiple configuration file formats to fit your project’s ecosystem. Config files are loaded automatically from your project root using the waterfall approach.

Supported Formats

MSR supports the following configuration file formats (searched in this priority order):

Format Files Status Optional Dependency
JavaScript msr.config.js ✅ Always available None
JSON msr.config.json ✅ Always available None
YAML msr.config.yaml, msr.config.yml 📦 Optional js-yaml
TOML msr.config.toml 📦 Optional @iarna/toml
XML msr.config.xml 📦 Optional fast-xml-parser

Core is lightweight: Format parsers for YAML, TOML, and XML are optional peer dependencies. Install only the ones you need.

JavaScript Configuration

// msr.config.js
module.exports = {
    folder: './database/migrations',
    tableName: 'migration_history',
    validateBeforeRun: true,
    transaction: {
        mode: 'PER_MIGRATION',
        retries: 3
    },
    backup: {
        folder: './backups',
        timestamp: true
    }
};

JSON Configuration

{
    "folder": "./database/migrations",
    "tableName": "migration_history",
    "validateBeforeRun": true,
    "transaction": {
        "mode": "PER_MIGRATION",
        "retries": 3
    },
    "backup": {
        "folder": "./backups",
        "timestamp": true
    }
}

YAML Configuration

Installation:

npm install js-yaml

Configuration:

# msr.config.yaml
folder: ./database/migrations
tableName: migration_history
validateBeforeRun: true

transaction:
  mode: PER_MIGRATION
  retries: 3

backup:
  folder: ./backups
  timestamp: true

TOML Configuration

Installation:

npm install @iarna/toml

Configuration:

# msr.config.toml
folder = "./database/migrations"
tableName = "migration_history"
validateBeforeRun = true

[transaction]
mode = "PER_MIGRATION"
retries = 3

[backup]
folder = "./backups"
timestamp = true

XML Configuration

Installation:

npm install fast-xml-parser

Configuration:

<!-- msr.config.xml -->
<msr>
  <folder>./database/migrations</folder>
  <tableName>migration_history</tableName>
  <validateBeforeRun>true</validateBeforeRun>

  <transaction>
    <mode>PER_MIGRATION</mode>
    <retries>3</retries>
  </transaction>

  <backup>
    <folder>./backups</folder>
    <timestamp>true</timestamp>
  </backup>
</msr>

Specifying Config File

You can specify a config file explicitly using ConfigLoaderOptions:

import { ConfigLoader } from '@migration-script-runner/core';

// Use specific config file
const config = ConfigLoader.load({}, {
    configFile: './config/production.yaml'
});

// Search in different directory
const config = ConfigLoader.load({}, {
    baseDir: './config'
});

// Backward compatible: baseDir as string
const config = ConfigLoader.load({}, './config');

Complete Documentation:


Environment-Specific Configuration (Legacy)

Note: Using ConfigLoader and environment variables (above) is the recommended approach for v0.5.0+.

For manual configuration in code:

const config = new Config();

// Different folders per environment
config.folder = process.env.NODE_ENV === 'production'
    ? './migrations'
    : './migrations-dev';

// Strict validation in CI
config.strictValidation = process.env.CI === 'true';

// Different rollback strategies
config.rollbackStrategy = process.env.NODE_ENV === 'production'
    ? RollbackStrategy.BOTH
    : RollbackStrategy.DOWN;

// Environment-specific backup naming
config.backup.custom = process.env.NODE_ENV || 'dev';

// Different backup retention
config.backup.deleteBackup = process.env.NODE_ENV === 'production';

Default Values

If you don’t configure these settings, MSR uses these defaults:

Setting Default Value
folder ./migrations
filePattern /^V(\d{12})_/
tableName 'schema_version'
displayLimit 0 (show all)
beforeMigrateName 'beforeMigrate'
recursive true
rollbackStrategy RollbackStrategy.BACKUP
validateBeforeRun true
strictValidation false
downMethodPolicy DownMethodPolicy.AUTO
customValidators []

See individual configuration pages for backup defaults.


Configuration Patterns

Development Configuration

Fast iteration with minimal overhead:

const config = new Config();
config.folder = './migrations';
config.rollbackStrategy = RollbackStrategy.DOWN;  // Fast rollback
config.validateBeforeRun = true;
config.strictValidation = false;  // Allow warnings
config.downMethodPolicy = DownMethodPolicy.OPTIONAL;

CI/CD Configuration

Strict validation and quality checks:

const config = new Config();
config.folder = './migrations';
config.rollbackStrategy = RollbackStrategy.BOTH;
config.validateBeforeRun = true;
config.strictValidation = true;  // Block on warnings
config.downMethodPolicy = DownMethodPolicy.REQUIRED;
config.customValidators = [
    new NamingValidator(),
    new DocumentationValidator(),
    new SqlSafetyValidator()
];

Production Configuration

Safety-first with backups:

const config = new Config();
config.folder = './migrations';
config.rollbackStrategy = RollbackStrategy.BOTH;
config.validateBeforeRun = true;
config.strictValidation = false;  // Allow warnings (but log them)
config.downMethodPolicy = DownMethodPolicy.RECOMMENDED;

// Reliable backup configuration
config.backup = new BackupConfig();
config.backup.folder = '/var/backups/database';
config.backup.deleteBackup = true;
config.backup.timestamp = true;

Configuration Topics

Explore detailed configuration options:


Next Steps



Table of contents