Database Migration Manager
Overview
Create, validate, and execute database schema migrations with full rollback support across PostgreSQL, MySQL, and MongoDB.
Prerequisites
- Database credentials with DDL permissions (CREATE, ALTER, DROP TABLE)
- Migration framework installed and configured (Flyway, Alembic, Prisma, Knex, or raw SQL versioning)
- Version control for migration files (Git repository)
- Access to a staging database matching production schema for testing migrations
psql or mysql CLI for executing and verifying migrations
- Current schema baseline documented or captured via
pg_dump --schema-only
Instructions
- Capture the current schema state before making changes. Run
pgdump --schema-only -f schemabefore.sql (PostgreSQL) or mysqldump --no-data > schema_before.sql (MySQL) to create a reference point.
- Define the desired schema change clearly: specify table name, column additions/removals/modifications, constraint changes, and index updates. Document whether the change is additive (safe) or destructive (requires data migration).
- Generate a versioned migration file following the framework's naming convention:
- Flyway:
V20240115001addstatuscolumnto_orders.sql
- Alembic:
alembic revision --autogenerate -m "add status column to orders"
- Prisma: Edit
schema.prisma then npx prisma migrate dev --name addstatusto_orders
- Knex:
npx knex migrate:make addstatusto_orders
- Write the UP migration (forward change) with these safety practices:
- Add new columns as nullable first, then backfill, then set NOT NULL
- Use
IF NOT EXISTS for CREATE operations to make migrations idempotent
- Add explicit transaction wrapping:
BEGIN; ... COMMIT;
- Include comments explaining the business reason for each change
- Write the DOWN migration (rollback) that exactly reverses the UP migration. For column additions, the DOWN drops the column. For table renames, the DOWN renames back. For data transformations, the DOWN must restore original data (store it in a backup column or table if needed).
- Validate the migration on staging by running the full migration sequence:
- Apply the UP migration and verify schema matches expectations
- Run the application test suite against the migrated schema
- Apply the DOWN migration and verify the schema returns to its original state
- Re-apply the UP migration to confirm idempotency
- For zero-downtime migrations on production, follow the expand-contract pattern: