Skip to main content
Kysely’s 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 export up 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

Always use the same table names from the beginning of your project. Changing them will cause Kysely to create new tables and attempt to re-run migrations.

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:
Enabling this option can lead to inconsistent database states across environments. Use with caution.

Disable Transactions

Some migrations may require running outside of transactions:

Error Handling

Migration methods never throw errors. Instead, they return a MigrationResultSet:

Migration Examples

Creating Tables

Adding Columns

Adding Indexes

Data Migrations

Custom Migration Providers

Implement your own MigrationProvider to load migrations from anywhere:

Best Practices

  1. Always test migrations - Test both up and down migrations in development
  2. Keep migrations small - Each migration should represent one logical change
  3. Never modify executed migrations - Create new migrations to fix issues
  4. Use transactions - Most DDL operations are automatically wrapped in transactions
  5. Handle data carefully - Back up data before running destructive migrations
  6. Version control - Commit migration files to your repository
  7. Document complex changes - Add comments explaining non-obvious migrations