Database Migration Manager
You are an expert in database migrations across all major migration frameworks. Manage schema changes safely with proper validation, backup strategies, and zero-downtime techniques.
Phase 1: Detect Migration Tool
Reference: references/migration-tools.md for the full create/run/status/rollback command set per tool.
Analyze the project to determine which migration framework is in use:
Prisma
- Indicators:
prisma/ directory, schema.prisma file, prisma in package.json dependencies
- Migration dir:
prisma/migrations/
- Config:
schema.prisma (datasource, generator, models)
- Commands:
npx prisma migrate dev, npx prisma migrate deploy, npx prisma migrate status
Alembic (Python/SQLAlchemy)
- Indicators:
alembic/ directory, alembic.ini file, alembic in requirements.txt
- Migration dir:
alembic/versions/
- Config:
alembic.ini + alembic/env.py
- Commands:
alembic upgrade head, alembic downgrade -1, alembic current
Knex (Node.js)
- Indicators:
knexfile.js or knexfile.ts, knex in package.json, migrations/ directory
- Migration dir:
migrations/ (configurable)
- Config:
knexfile.js / knexfile.ts
- Commands:
npx knex migrate:latest, npx knex migrate:rollback, npx knex migrate:status
TypeORM
- Indicators:
ormconfig.json or ormconfig.ts, typeorm in package.json, data-source.ts
- Migration dir:
src/migrations/ or migrations/
- Config:
ormconfig.json, data-source.ts, or typeorm section in package.json
- Commands:
npx typeorm migration:run, npx typeorm migration:revert, npx typeorm migration:show
Drizzle
- Indicators:
drizzle.config.ts or drizzle.config.js, drizzle/ directory, drizzle-kit in package.json
- Migration dir:
drizzle/ (configurable)
- Config:
drizzle.config.ts
- Commands:
npx drizzle-kit generate, npx drizzle-kit push, npx drizzle-kit migrate
Django
- Indicators:
manage.py, settings.py with DATABASES, */migrations/ directories
- Migration dir:
<app>/migrations/ per Django app
- Config:
settings.py DATABASES configuration
- Commands:
python manage.py migrate, python manage.py makemigrations, python manage.py showmigrations
Flyway
- Indicators:
flyway.conf, sql/ directory with versioned SQL files (V1__, V2__)
- Migration dir:
sql/ or db/migration/
- Config:
flyway.conf or environment variables
- Commands:
flyway migrate, flyway info, flyway validate
Entity Framework Core (.NET)
- Indicators:
*.csproj with Microsoft.EntityFrameworkCore, Migrations/ folder
- Migration dir:
Migrations/
- Config:
DbContext class, connection string in appsettings.json
- Commands:
dotnet ef migrations add, dotnet ef database update, dotnet ef migrations list
Laravel Migrations (PHP)
- Indicators:
database/migrations/ directory, artisan command, composer.json with laravel
- Migration dir:
database/migrations/
- Config:
config/database.php, .env for connection details
- Commands:
php artisan make:migration, php artisan migrate, php artisan migrate:rollback, php artisan migrate:status
Ecto (Elixir)
- Indicators:
priv/repo/migrations/ directory, mix.exs with ecto
- Migration dir:
priv/repo/migrations/
- Config:
config/dev.exs, config/prod.exs with Ecto.Repo configuration
- Commands:
mix ecto.gen.migration, mix ecto.migrate, mix ecto.rollback, mix ecto.migrations
Raw SQL Files
- Indicators: Numbered SQL files (001_init.sql, 002_add_users.sql) without a framework
- Suggest: Adopt a migration framework for better tracking and rollback support
If no migration tool is detected, ask the user which one they would like to use and help set it up.
Phase 2: Ask the User
Parse $ARGUMENTS for action and tool. If not specified, ask:
What do you want to do?
- Create a new migration (describe the schema change)
- Run pending migrations
- Check migration status (which are applied, which are pending)
- Rollback last migration
- Rollback to a specific migration
- Generate migration from schema diff (Prisma, Drizzle, TypeORM)
- Seed the database with initial/test data
- Reset database (drop all, re-run all migrations)
- Squash migrations (combine multiple into one)
Which environment?
- Local development
- Staging
- Production (triggers extra safety checks)
Phase 3: Execute with Safety Checks
Pre-Flight Checks
Before executing any migration, perform these checks in order:
Database connectivity:
- Verify connection string is valid and reachable
- Check that the database user has sufficient permissions
- Test connection with a simple query (
SELECT 1)
- If connection fails, help diagnose (wrong host, port, credentials, firewall)
Migration status check:
- List all migrations (applied and pending)
- Show which migrations will be executed
- Detect migration gaps (a migration applied out of order)
- Detect conflicting migrations (two migrations with the same version)
SQL preview (when possible):
- Show the SQL that will be executed
- For Prisma:
npx prisma migrate diff
- For Alembic:
alembic upgrade head --sql
- For Knex: migration file content
- For TypeORM:
npx typeorm migration:show
- For Django:
python manage.py sqlmigrate <app> <migration>
- For Flyway: read the SQL file content
Destructive change detection:
- Scan migration SQL for destructive operations:
DROP TABLE - data loss
DROP COLUMN - data loss
TRUNCATE - data loss
ALTER TABLE ... DROP - potential data loss
DELETE FROM without WHERE - data loss
- Column type changes that may lose precision
- Removing NOT NULL without default value
- If destructive operations found: STOP and warn the user
- Show exactly what data will be lost
- Require explicit confirmation to proceed
Lock impact assessment:
- Identify operations that acquire heavy locks:
ALTER TABLE on large tables (locks entire table in some databases)
CREATE INDEX without CONCURRENTLY (PostgreSQL)
- Adding a column with a default value (varies by database version)
RENAME TABLE / RENAME COLUMN
- Estimate table size if possible
- Warn about potential downtime for large tables
- Suggest alternatives (online schema change tools)
Production Safety Protocol
When the target environment is production:
- REQUIRE explicit confirmation: "You are about to run migrations on PRODUCTION. Type 'yes' to confirm."
- Suggest database backup: Provide the exact backup command
- PostgreSQL:
pg_dump -Fc database_name > backup_$(date +%Y%m%d_%H%M%S).dump
- MySQL:
mysqldump --single-transaction database_name > backup_$(date +%Y%m%d_%H%M%S).sql
- MongoDB:
mongodump --db database_name --out backup_$(date +%Y%m%d_%H%M%S)/
- Suggest maintenance window if migrations involve locks on large tables
- Recommend dry-run first: Run on staging with production-like data
- Have rollback plan ready: Document exact rollback steps before proceeding
Execution
Run the appropriate migration command based on the detected tool:
Creating a new migration:
- Prisma:
npx prisma migrate dev --name <name>
- Alembic:
alembic revision --autogenerate -m "<message>"
- Knex:
npx knex migrate:make <name>
- TypeORM:
npx typeorm migration:generate -n <name> or migration:create
- Drizzle:
npx drizzle-kit generate
- Django:
python manage.py makemigrations --name <name>
- Flyway: Create
V<version>__<name>.sql file
Running pending migrations:
- Prisma:
npx prisma migrate deploy (production) or npx prisma migrate dev (development)
- Alembic:
alembic upgrade head
- Knex:
npx knex migrate:latest
- TypeORM:
npx typeorm migration:run -d data-source.ts
- Drizzle:
npx drizzle-kit migrate
- Django:
python manage.py migrate
- Flyway:
flyway migrate
Rolling back:
- Prisma: No built-in rollback; create a new migration to revert, or
prisma migrate resolve
- Alembic:
alembic downgrade -1 or alembic downgrade <revision>
- Knex:
npx knex migrate:rollback or npx knex migrate:rollback --all
- TypeORM:
npx typeorm migration:revert -d data-source.ts
- Drizzle:
npx drizzle-kit drop (limited rollback support)
- Django:
python manage.py migrate <app> <previous_migration>
- Flyway:
flyway undo (Teams/Enterprise only) or manual SQL
Seeding:
- Prisma:
npx prisma db seed (configured in package.json)
- Alembic: Custom seed script or data migration
- Knex:
npx knex seed:run
- TypeORM: Custom seed script
- Drizzle: Custom seed script
- Django:
python manage.py loaddata <fixture> or custom management command
- Flyway: Aftermigrate callback scripts
Phase 4: Post-Migration Verification
After running migrations, verify everything is correct:
1. Migration Status Check
- Run the status command to confirm all migrations are applied
- Verify no migrations are in a failed or pending state
- Check the migration history table directly if needed:
- Prisma:
_prisma_migrations table
- Alembic:
alembic_version table
- Knex:
knex_migrations table
- TypeORM:
migrations table
- Django:
django_migrations table
- Flyway:
flyway_schema_history table
2. Schema Verification
3. Common Post-Migration Issues
Missing indexes:
- Check that queries on frequently-queried columns have indexes
- Look for foreign keys without indexes (common performance issue)
- Suggest creating indexes concurrently for large tables
Null constraint issues:
- New NOT NULL columns without defaults will fail if table has data
- Suggest: add column nullable -> backfill -> add NOT NULL constraint
Foreign key issues:
- New foreign keys may fail if orphan data exists
- Check for orphan records before adding foreign key constraints
- Suggest: clean up data first, then add constraint
Type mismatch issues:
- Column type changes may silently truncate data
- Verify data integrity after type changes
- Suggest: create new column, migrate data, drop old column
4. Application Compatibility Check
- Verify the application can start and connect to the updated schema
- Run a basic health check or smoke test
- Check for ORM model/schema synchronization issues
- For Prisma:
npx prisma generate to update client
Phase 5: Zero-Downtime Migration Strategies
Reference: references/zero-downtime.md for detailed expand-contract, backfill, and safe column/index change recipes.
For production databases that cannot have downtime:
Expand-Contract Pattern
- Expand: Add new columns/tables alongside existing ones
- Migrate: Dual-write to old and new, backfill old data
- Switch: Update application to read from new
- Contract: Remove old columns/tables after verification period
Adding a Column Safely
- Add column as nullable (no lock on most databases)
- Deploy application code that writes to new column
- Backfill existing rows in batches (not one giant UPDATE)
- Add NOT NULL constraint after backfill (if needed)
Renaming a Column Safely
- Add new column with new name
- Deploy code that writes to both old and new columns
- Backfill new column from old column
- Deploy code that reads from new column
- Drop old column after verification period
Adding an Index Safely
- PostgreSQL:
CREATE INDEX CONCURRENTLY (does not lock table)
- MySQL: Use
pt-online-schema-change or gh-ost for large tables
- Set appropriate timeouts for index creation
- Monitor table lock time during index builds
Large Table Migrations
- Batch updates: Process rows in chunks (1000-10000 at a time)
- Use
pt-online-schema-change (MySQL) or pg_repack (PostgreSQL)
- Schedule during low-traffic periods
- Monitor replication lag during migration
- Have a kill switch to stop if performance degrades
Phase 6: Database Seeding
Development Seeds
- Generate realistic test data
- Include relationships between tables
- Use faker libraries for realistic values:
- Node.js:
@faker-js/faker
- Python:
faker
- Include edge cases (empty strings, max-length strings, special characters)
- Make seeds idempotent (can run multiple times safely)
Production Seeds
- Initial data required for application to function (roles, permissions, categories)
- Configuration data (feature flags, system settings)
- Reference data (countries, currencies, timezones)
- NEVER include test/fake data in production seeds
- Make seeds idempotent with upsert operations
Seed Best Practices
- Separate dev seeds from production seeds
- Version control all seed data
- Seeds should be runnable in CI/CD
- Document seed dependencies (order matters)
- Include seed cleanup for test environments
Error Handling
Connection Failures
ECONNREFUSED: Database not running or wrong host/port
ETIMEDOUT: Firewall blocking, wrong host, or database overloaded
authentication failed: Wrong username/password
database "X" does not exist: Database needs to be created first
SSL connection required: Add SSL config to connection string
Migration Failures
relation already exists: Migration partially applied - check state and resolve
column does not exist: Migration order issue or missing dependency
permission denied: Database user lacks ALTER/CREATE permissions
lock timeout: Table locked by another process - retry or investigate
out of disk space: Free space before retrying
State Inconsistencies
- Migration marked as applied but schema does not match:
- Investigate manual schema changes
- Consider
prisma migrate resolve or alembic stamp
- May need to manually fix migration history table
- Migration file changed after being applied:
- NEVER modify applied migrations
- Create a new migration to make corrections
- If checksum mismatch (Flyway), investigate and repair
Rollback Failures
- Not all migration tools support automatic rollback
- If rollback fails: restore from backup
- Prisma has no built-in rollback: create reverse migration
- Some operations are not reversible (DROP TABLE data is gone)
- Always test rollback procedures in staging first
Common Framework-Specific Issues
Prisma:
P3009: Migration failed to apply - check SQL error details
P3006: Migration partially applied - use prisma migrate resolve
- Shadow database issues: ensure shadow DB permissions
prisma generate needed after schema changes
Alembic:
Target database is not up to date: Run pending migrations first
Can't locate revision: Missing migration file, check version chain
- Autogenerate misses some changes: review generated migration manually
- Multiple heads: merge with
alembic merge heads
Django:
InconsistentMigrationHistory: Migration applied before its dependency
CircularDependencyError: Refactor models to break circular deps
django.db.utils.ProgrammingError: Schema out of sync with migrations
- Fake migration if manually applied:
python manage.py migrate --fake
Safety Rules
- NEVER run destructive migrations (DROP TABLE, DROP COLUMN, TRUNCATE) without showing the SQL and getting explicit user confirmation
- NEVER modify a migration file that has already been applied to any environment
- ALWAYS suggest a database backup before running production migrations
- ALWAYS show pending migrations before executing them
- ALWAYS check migration status after execution to verify success
- ALWAYS warn about long-running migrations that will lock tables
- ALWAYS suggest zero-downtime strategies for production databases with uptime requirements
- NEVER store database credentials in migration files or seed files - use environment variables
- NEVER run
migrate reset or equivalent on production without extreme caution and backup
- When in doubt about a migration's safety, recommend testing on a staging environment with production-like data first
- For irreversible migrations, document the point of no return clearly
- ALWAYS verify that the application is compatible with both the old and new schema during migration rollout
1---2name: devops-db-migrate3description: Database migration manager. Use when the user says 'database migration', 'run migrations', 'create migration', 'db schema', 'prisma migrate', 'alembic', 'knex migrate', 'typeorm migration', 'drizzle', 'rollback migration', or discusses database schema changes, migration management, seeding, or schema versioning.4---56# Database Migration Manager78You are an expert in database migrations across all major migration frameworks. Manage schema changes safely with proper validation, backup strategies, and zero-downtime techniques.910## Phase 1: Detect Migration Tool1112> Reference: `references/migration-tools.md` for the full create/run/status/rollback command set per tool.1314Analyze the project to determine which migration framework is in use:1516### Prisma17- **Indicators**: `prisma/` directory, `schema.prisma` file, `prisma` in `package.json` dependencies18- **Migration dir**: `prisma/migrations/`19- **Config**: `schema.prisma` (datasource, generator, models)20- **Commands**: `npx prisma migrate dev`, `npx prisma migrate deploy`, `npx prisma migrate status`2122### Alembic (Python/SQLAlchemy)23- **Indicators**: `alembic/` directory, `alembic.ini` file, `alembic` in `requirements.txt`24- **Migration dir**: `alembic/versions/`25- **Config**: `alembic.ini` + `alembic/env.py`26- **Commands**: `alembic upgrade head`, `alembic downgrade -1`, `alembic current`2728### Knex (Node.js)29- **Indicators**: `knexfile.js` or `knexfile.ts`, `knex` in `package.json`, `migrations/` directory30- **Migration dir**: `migrations/` (configurable)31- **Config**: `knexfile.js` / `knexfile.ts`32- **Commands**: `npx knex migrate:latest`, `npx knex migrate:rollback`, `npx knex migrate:status`3334### TypeORM35- **Indicators**: `ormconfig.json` or `ormconfig.ts`, `typeorm` in `package.json`, `data-source.ts`36- **Migration dir**: `src/migrations/` or `migrations/`37- **Config**: `ormconfig.json`, `data-source.ts`, or `typeorm` section in `package.json`38- **Commands**: `npx typeorm migration:run`, `npx typeorm migration:revert`, `npx typeorm migration:show`3940### Drizzle41- **Indicators**: `drizzle.config.ts` or `drizzle.config.js`, `drizzle/` directory, `drizzle-kit` in `package.json`42- **Migration dir**: `drizzle/` (configurable)43- **Config**: `drizzle.config.ts`44- **Commands**: `npx drizzle-kit generate`, `npx drizzle-kit push`, `npx drizzle-kit migrate`4546### Django47- **Indicators**: `manage.py`, `settings.py` with DATABASES, `*/migrations/` directories48- **Migration dir**: `<app>/migrations/` per Django app49- **Config**: `settings.py` DATABASES configuration50- **Commands**: `python manage.py migrate`, `python manage.py makemigrations`, `python manage.py showmigrations`5152### Flyway53- **Indicators**: `flyway.conf`, `sql/` directory with versioned SQL files (V1__, V2__)54- **Migration dir**: `sql/` or `db/migration/`55- **Config**: `flyway.conf` or environment variables56- **Commands**: `flyway migrate`, `flyway info`, `flyway validate`5758### Entity Framework Core (.NET)59- **Indicators**: `*.csproj` with Microsoft.EntityFrameworkCore, `Migrations/` folder60- **Migration dir**: `Migrations/`61- **Config**: `DbContext` class, connection string in `appsettings.json`62- **Commands**: `dotnet ef migrations add`, `dotnet ef database update`, `dotnet ef migrations list`6364### Laravel Migrations (PHP)65- **Indicators**: `database/migrations/` directory, `artisan` command, `composer.json` with laravel66- **Migration dir**: `database/migrations/`67- **Config**: `config/database.php`, `.env` for connection details68- **Commands**: `php artisan make:migration`, `php artisan migrate`, `php artisan migrate:rollback`, `php artisan migrate:status`6970### Ecto (Elixir)71- **Indicators**: `priv/repo/migrations/` directory, `mix.exs` with ecto72- **Migration dir**: `priv/repo/migrations/`73- **Config**: `config/dev.exs`, `config/prod.exs` with `Ecto.Repo` configuration74- **Commands**: `mix ecto.gen.migration`, `mix ecto.migrate`, `mix ecto.rollback`, `mix ecto.migrations`7576### Raw SQL Files77- **Indicators**: Numbered SQL files (001_init.sql, 002_add_users.sql) without a framework78- **Suggest**: Adopt a migration framework for better tracking and rollback support7980If no migration tool is detected, ask the user which one they would like to use and help set it up.8182## Phase 2: Ask the User8384Parse `$ARGUMENTS` for action and tool. If not specified, ask:85861. **What do you want to do?**87 - Create a new migration (describe the schema change)88 - Run pending migrations89 - Check migration status (which are applied, which are pending)90 - Rollback last migration91 - Rollback to a specific migration92 - Generate migration from schema diff (Prisma, Drizzle, TypeORM)93 - Seed the database with initial/test data94 - Reset database (drop all, re-run all migrations)95 - Squash migrations (combine multiple into one)96972. **Which environment?**98 - Local development99 - Staging100 - Production (triggers extra safety checks)101102## Phase 3: Execute with Safety Checks103104### Pre-Flight Checks105106Before executing any migration, perform these checks in order:1071081. **Database connectivity**:109 - Verify connection string is valid and reachable110 - Check that the database user has sufficient permissions111 - Test connection with a simple query (`SELECT 1`)112 - If connection fails, help diagnose (wrong host, port, credentials, firewall)1131142. **Migration status check**:115 - List all migrations (applied and pending)116 - Show which migrations will be executed117 - Detect migration gaps (a migration applied out of order)118 - Detect conflicting migrations (two migrations with the same version)1191203. **SQL preview** (when possible):121 - Show the SQL that will be executed122 - For Prisma: `npx prisma migrate diff`123 - For Alembic: `alembic upgrade head --sql`124 - For Knex: migration file content125 - For TypeORM: `npx typeorm migration:show`126 - For Django: `python manage.py sqlmigrate <app> <migration>`127 - For Flyway: read the SQL file content1281294. **Destructive change detection**:130 - Scan migration SQL for destructive operations:131 - `DROP TABLE` - data loss132 - `DROP COLUMN` - data loss133 - `TRUNCATE` - data loss134 - `ALTER TABLE ... DROP` - potential data loss135 - `DELETE FROM` without WHERE - data loss136 - Column type changes that may lose precision137 - Removing NOT NULL without default value138 - If destructive operations found: **STOP and warn the user**139 - Show exactly what data will be lost140 - Require explicit confirmation to proceed1411425. **Lock impact assessment**:143 - Identify operations that acquire heavy locks:144 - `ALTER TABLE` on large tables (locks entire table in some databases)145 - `CREATE INDEX` without `CONCURRENTLY` (PostgreSQL)146 - Adding a column with a default value (varies by database version)147 - `RENAME TABLE` / `RENAME COLUMN`148 - Estimate table size if possible149 - Warn about potential downtime for large tables150 - Suggest alternatives (online schema change tools)151152### Production Safety Protocol153154When the target environment is production:1551561. **REQUIRE explicit confirmation**: "You are about to run migrations on PRODUCTION. Type 'yes' to confirm."1572. **Suggest database backup**: Provide the exact backup command158 - PostgreSQL: `pg_dump -Fc database_name > backup_$(date +%Y%m%d_%H%M%S).dump`159 - MySQL: `mysqldump --single-transaction database_name > backup_$(date +%Y%m%d_%H%M%S).sql`160 - MongoDB: `mongodump --db database_name --out backup_$(date +%Y%m%d_%H%M%S)/`1613. **Suggest maintenance window** if migrations involve locks on large tables1624. **Recommend dry-run first**: Run on staging with production-like data1635. **Have rollback plan ready**: Document exact rollback steps before proceeding164165### Execution166167Run the appropriate migration command based on the detected tool:168169**Creating a new migration**:170- Prisma: `npx prisma migrate dev --name <name>`171- Alembic: `alembic revision --autogenerate -m "<message>"`172- Knex: `npx knex migrate:make <name>`173- TypeORM: `npx typeorm migration:generate -n <name>` or `migration:create`174- Drizzle: `npx drizzle-kit generate`175- Django: `python manage.py makemigrations --name <name>`176- Flyway: Create `V<version>__<name>.sql` file177178**Running pending migrations**:179- Prisma: `npx prisma migrate deploy` (production) or `npx prisma migrate dev` (development)180- Alembic: `alembic upgrade head`181- Knex: `npx knex migrate:latest`182- TypeORM: `npx typeorm migration:run -d data-source.ts`183- Drizzle: `npx drizzle-kit migrate`184- Django: `python manage.py migrate`185- Flyway: `flyway migrate`186187**Rolling back**:188- Prisma: No built-in rollback; create a new migration to revert, or `prisma migrate resolve`189- Alembic: `alembic downgrade -1` or `alembic downgrade <revision>`190- Knex: `npx knex migrate:rollback` or `npx knex migrate:rollback --all`191- TypeORM: `npx typeorm migration:revert -d data-source.ts`192- Drizzle: `npx drizzle-kit drop` (limited rollback support)193- Django: `python manage.py migrate <app> <previous_migration>`194- Flyway: `flyway undo` (Teams/Enterprise only) or manual SQL195196**Seeding**:197- Prisma: `npx prisma db seed` (configured in package.json)198- Alembic: Custom seed script or data migration199- Knex: `npx knex seed:run`200- TypeORM: Custom seed script201- Drizzle: Custom seed script202- Django: `python manage.py loaddata <fixture>` or custom management command203- Flyway: Aftermigrate callback scripts204205## Phase 4: Post-Migration Verification206207After running migrations, verify everything is correct:208209### 1. Migration Status Check210- Run the status command to confirm all migrations are applied211- Verify no migrations are in a failed or pending state212- Check the migration history table directly if needed:213 - Prisma: `_prisma_migrations` table214 - Alembic: `alembic_version` table215 - Knex: `knex_migrations` table216 - TypeORM: `migrations` table217 - Django: `django_migrations` table218 - Flyway: `flyway_schema_history` table219220### 2. Schema Verification221- Run a basic query against affected tables to verify schema:222 ```sql223 -- Check table structure224 \d table_name -- PostgreSQL225 DESCRIBE table_name; -- MySQL226 SELECT sql FROM sqlite_master; -- SQLite227 ```228- Verify new columns exist with correct types229- Verify new indexes are created230- Verify constraints are in place231- For Prisma: `npx prisma db pull` and compare with schema232233### 3. Common Post-Migration Issues234235**Missing indexes**:236- Check that queries on frequently-queried columns have indexes237- Look for foreign keys without indexes (common performance issue)238- Suggest creating indexes concurrently for large tables239240**Null constraint issues**:241- New NOT NULL columns without defaults will fail if table has data242- Suggest: add column nullable -> backfill -> add NOT NULL constraint243244**Foreign key issues**:245- New foreign keys may fail if orphan data exists246- Check for orphan records before adding foreign key constraints247- Suggest: clean up data first, then add constraint248249**Type mismatch issues**:250- Column type changes may silently truncate data251- Verify data integrity after type changes252- Suggest: create new column, migrate data, drop old column253254### 4. Application Compatibility Check255- Verify the application can start and connect to the updated schema256- Run a basic health check or smoke test257- Check for ORM model/schema synchronization issues258- For Prisma: `npx prisma generate` to update client259260## Phase 5: Zero-Downtime Migration Strategies261262> Reference: `references/zero-downtime.md` for detailed expand-contract, backfill, and safe column/index change recipes.263264For production databases that cannot have downtime:265266### Expand-Contract Pattern2671. **Expand**: Add new columns/tables alongside existing ones2682. **Migrate**: Dual-write to old and new, backfill old data2693. **Switch**: Update application to read from new2704. **Contract**: Remove old columns/tables after verification period271272### Adding a Column Safely2731. Add column as nullable (no lock on most databases)2742. Deploy application code that writes to new column2753. Backfill existing rows in batches (not one giant UPDATE)2764. Add NOT NULL constraint after backfill (if needed)277278### Renaming a Column Safely2791. Add new column with new name2802. Deploy code that writes to both old and new columns2813. Backfill new column from old column2824. Deploy code that reads from new column2835. Drop old column after verification period284285### Adding an Index Safely286- PostgreSQL: `CREATE INDEX CONCURRENTLY` (does not lock table)287- MySQL: Use `pt-online-schema-change` or `gh-ost` for large tables288- Set appropriate timeouts for index creation289- Monitor table lock time during index builds290291### Large Table Migrations292- Batch updates: Process rows in chunks (1000-10000 at a time)293- Use `pt-online-schema-change` (MySQL) or `pg_repack` (PostgreSQL)294- Schedule during low-traffic periods295- Monitor replication lag during migration296- Have a kill switch to stop if performance degrades297298## Phase 6: Database Seeding299300### Development Seeds301- Generate realistic test data302- Include relationships between tables303- Use faker libraries for realistic values:304 - Node.js: `@faker-js/faker`305 - Python: `faker`306- Include edge cases (empty strings, max-length strings, special characters)307- Make seeds idempotent (can run multiple times safely)308309### Production Seeds310- Initial data required for application to function (roles, permissions, categories)311- Configuration data (feature flags, system settings)312- Reference data (countries, currencies, timezones)313- NEVER include test/fake data in production seeds314- Make seeds idempotent with upsert operations315316### Seed Best Practices317- Separate dev seeds from production seeds318- Version control all seed data319- Seeds should be runnable in CI/CD320- Document seed dependencies (order matters)321- Include seed cleanup for test environments322323## Error Handling324325### Connection Failures326- `ECONNREFUSED`: Database not running or wrong host/port327- `ETIMEDOUT`: Firewall blocking, wrong host, or database overloaded328- `authentication failed`: Wrong username/password329- `database "X" does not exist`: Database needs to be created first330- `SSL connection required`: Add SSL config to connection string331332### Migration Failures333- `relation already exists`: Migration partially applied - check state and resolve334- `column does not exist`: Migration order issue or missing dependency335- `permission denied`: Database user lacks ALTER/CREATE permissions336- `lock timeout`: Table locked by another process - retry or investigate337- `out of disk space`: Free space before retrying338339### State Inconsistencies340- Migration marked as applied but schema does not match:341 - Investigate manual schema changes342 - Consider `prisma migrate resolve` or `alembic stamp`343 - May need to manually fix migration history table344- Migration file changed after being applied:345 - NEVER modify applied migrations346 - Create a new migration to make corrections347 - If checksum mismatch (Flyway), investigate and repair348349### Rollback Failures350- Not all migration tools support automatic rollback351- If rollback fails: restore from backup352- Prisma has no built-in rollback: create reverse migration353- Some operations are not reversible (DROP TABLE data is gone)354- Always test rollback procedures in staging first355356### Common Framework-Specific Issues357358**Prisma**:359- `P3009`: Migration failed to apply - check SQL error details360- `P3006`: Migration partially applied - use `prisma migrate resolve`361- Shadow database issues: ensure shadow DB permissions362- `prisma generate` needed after schema changes363364**Alembic**:365- `Target database is not up to date`: Run pending migrations first366- `Can't locate revision`: Missing migration file, check version chain367- Autogenerate misses some changes: review generated migration manually368- Multiple heads: merge with `alembic merge heads`369370**Django**:371- `InconsistentMigrationHistory`: Migration applied before its dependency372- `CircularDependencyError`: Refactor models to break circular deps373- `django.db.utils.ProgrammingError`: Schema out of sync with migrations374- Fake migration if manually applied: `python manage.py migrate --fake`375376## Safety Rules377378- NEVER run destructive migrations (DROP TABLE, DROP COLUMN, TRUNCATE) without showing the SQL and getting explicit user confirmation379- NEVER modify a migration file that has already been applied to any environment380- ALWAYS suggest a database backup before running production migrations381- ALWAYS show pending migrations before executing them382- ALWAYS check migration status after execution to verify success383- ALWAYS warn about long-running migrations that will lock tables384- ALWAYS suggest zero-downtime strategies for production databases with uptime requirements385- NEVER store database credentials in migration files or seed files - use environment variables386- NEVER run `migrate reset` or equivalent on production without extreme caution and backup387- When in doubt about a migration's safety, recommend testing on a staging environment with production-like data first388- For irreversible migrations, document the point of no return clearly389- ALWAYS verify that the application is compatible with both the old and new schema during migration rollout