Migration Strategies

Learn how to manage database schema changes effectively with Stabilize ORM

Why Use Migrations?

Migrations provide a version-controlled way to manage database schema changes. They allow you to:

  • Track schema changes over time
  • Collaborate with team members safely
  • Deploy schema changes consistently across environments
  • Rollback changes if needed

Creating Your First Migration

Generate a new migration file:

stabilize-cli generate migration User

This creates a timestamped file in the migrations directory:

migrations/20240115120000_users.tstypescript
import { Migration } from "stabilize-orm";
export const up: Migration = async (orm) => {
await orm.rawQuery(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
};
export const down: Migration = async (orm) => {
await orm.rawQuery("DROP TABLE IF EXISTS users");
};

Running Migrations

stabilize-cli migrate

This runs all pending migrations in order. Stabilize tracks which migrations have been applied.

Rolling Back Migrations

stabilize-cli migration:rollback

Rolls back the last batch of migrations using the down function.

Migration Best Practices

  • Always write both up and down functions
  • Test migrations on a copy of production data
  • Keep migrations small and focused
  • Never modify existing migrations after they've been deployed
  • Use transactions for data migrations
  • Add indexes in separate migrations for large tables
  • Document complex migrations with comments
  • Back up your database before running migrations in production

Troubleshooting

Migration failed mid-way

If a migration fails, manually fix the database state and mark the migration as complete or rolled back.

Conflicts between branches

Use timestamps in migration filenames to avoid conflicts. Merge migrations carefully.

Long-running migrations

For large tables, consider running migrations during low-traffic periods or use online schema change tools.