drizzle-kit and applied at runtime using the migrate() function.
Import
- PostgreSQL
- MySQL
- SQLite
migrate()
Apply pending migrations to your database:Database
required
The database instance (with schema type)
MigrationConfig
required
Migration configuration object
MigrationConfig
string
required
Path to the folder containing migration files (relative or absolute)
string
Custom name for the migrations tracking table (default:
__drizzle_migrations)string
Schema name for the migrations table (PostgreSQL only)
Basic Usage
PostgreSQL
MySQL
SQLite
SQLite migrations in Drizzle are synchronous, unlike PostgreSQL and MySQL which are asynchronous.
Migration Files Structure
Migrations are stored in the folder specified bymigrationsFolder. Drizzle Kit generates:
_journal.json
Tracks migration metadata:Migration SQL Files
Contain SQL statements to modify the schema:--> statement-breakpoint comment separates individual statements for proper execution.
Custom Migrations Table
Custom Table Name
my_migrations instead of the default __drizzle_migrations.
Custom Schema (PostgreSQL)
drizzle schema.
Migration Tracking
Drizzle automatically creates a migrations table to track which migrations have been applied:- id: Sequential identifier
- hash: SHA-256 hash of the migration SQL
- created_at: Unix timestamp in milliseconds
Application Startup Pattern
Common pattern for running migrations on application startup:Express.js Example
NestJS Example
Separate Migration Script
Create a dedicated script for running migrations:migrate.ts
package.json
Environment-Specific Migrations
Different migration configs for different environments:Error Handling
Graceful Error Handling
Validation Before Migration
Best Practices
1. Run Migrations Before App Starts
Ensure database schema is up-to-date before accepting requests:2. Use Version Control
Commit migration files to version control:3. Test Migrations
Test migrations in development/staging before production:4. Backup Before Migration
Always backup production databases before applying migrations:5. Use Transactions
Migrations run within transactions automatically (where supported), ensuring atomicity.Generating Migrations
Migrations are generated using Drizzle Kit:drizzle.config.ts
Migration Workflow
- Modify schema: Update your schema definitions
- Generate migration: Run
drizzle-kit generate - Review SQL: Check generated SQL files
- Apply migration: Run
migrate()function - Verify: Test that changes work as expected
Common Issues
Migration File Not Found
drizzle-kit generate to create migrations first.
Permission Denied
Concurrent Migrations
Multiple instances running migrations simultaneously can cause conflicts. Solution: Use migration locks or ensure only one instance runs migrations.Related APIs
- SQL - Custom SQL in migrations
- Transactions - Transaction behavior
- Schema Definition - Define database schema