Migrator class provides a robust system for managing database schema changes. Migrations help you version control your database schema and apply changes consistently across environments.
Basic Setup
1
Create a Migrator instance
2
Create your first migration file
Create a file
src/migrations/001_initial_schema.ts:3
Run migrations
Migration Structure
The Migration Interface
Each migration file must exportup and optionally down functions:
If you don’t provide a
down method, the migration will be skipped when migrating down.Naming Conventions
Migration files are executed in alphabetical order. Common naming patterns:001_initial_schema.ts,002_add_users.ts(numbered)2024_03_01_create_posts.ts(dated)20240301120000_add_comments.ts(timestamp)
Migration Operations
Migrate to Latest
Run all pending migrations:Migrate to Specific Version
Migrate up or down to a specific migration:Migrate One Step
Migrate one step up or down:Check Migration Status
Get information about all migrations:Configuration Options
Custom Migration Table Name
Migration Schema
On PostgreSQL and MSSQL, specify a schema for migration tables:Allow Unordered Migrations
By default, migrations must be run in exact alphabetical order. To allow flexibility:Disable Transactions
Some migrations may require running outside of transactions:Error Handling
Migration methods never throw errors. Instead, they return aMigrationResultSet:
Migration Examples
Creating Tables
Adding Columns
Adding Indexes
Data Migrations
Custom Migration Providers
Implement your ownMigrationProvider to load migrations from anywhere:
Best Practices
- Always test migrations - Test both
upanddownmigrations in development - Keep migrations small - Each migration should represent one logical change
- Never modify executed migrations - Create new migrations to fix issues
- Use transactions - Most DDL operations are automatically wrapped in transactions
- Handle data carefully - Back up data before running destructive migrations
- Version control - Commit migration files to your repository
- Document complex changes - Add comments explaining non-obvious migrations