Skip to main content

Database Migrations

The CoW Protocol BFF uses TypeORM for database management through the libs/repositories library. Migrations serve as version control for your database schema, enabling teams to track changes, apply them consistently across environments, and rollback when necessary.

Core Commands

Manual Migration Creation

Generate an empty file and write SQL directly:
This creates a migration file with up() and down() methods:

Auto-Generated Migrations

Define TypeORM entities first, then generate migration files based on schema differences:
This compares your entity definitions against the current database schema and produces the necessary SQL.

Running Migrations

Reverting Migrations

Important: Only the last migration can be reverted. To undo multiple migrations, run the revert command multiple times.

Common Patterns

Adding a Table

Adding a Column

Renaming a Column

Data Migration

Best Practices

  1. Always implement complete down() methods for rollback capability
  2. Test migrations bidirectionally before production deployment
  3. Never modify migrations after production deployment - create new migrations instead
  4. Use descriptive naming conventions (e.g., add-user-email-index)
  5. Back up databases before production migrations
  6. Make changes backward-compatible through staged deployments

Production Deployment

The recommended deployment sequence:
  1. Back up the database
  2. Run migrations before deploying application code:
  3. Deploy the new application version
  4. Monitor for issues post-deployment
  5. Rollback if needed:

Naming Conventions

Use clear, action-oriented file names:
  • add-user-table
  • add-order-status-column
  • create-notification-index
  • rename-user-name-to-display-name
  • migrate-order-status-data
Last modified on March 4, 2026