Database Migration Create Workflow
Create a new database migration file with up and down scripts, test it locally, and verify rollback works.
Objective
Create and test a reversible database migration before applying it to staging or production.
Environment
- A project with a migration tool
- A local database for testing
- Migration tool CLI available
Steps
1. Generate migration
Use the migration tool to create a new migration file with a descriptive name.
Expected state: A new migration file is created with up and down functions.
2. Apply migration
Run the migration tool to apply the new migration to the local database.
Expected state: The local database schema is updated.
3. Test rollback
Run the rollback command to revert the migration and confirm the database returns to the previous state.
Expected state: The database schema is restored to the pre-migration state.
4. Re-apply
Apply the migration again to confirm it is idempotent.
Expected state: The migration applies cleanly after rollback.
Decision points
Should migrations be reversible?
- Yes, always include down
- No, only for schema changes
Always include a down migration; data migrations may need special handling.
Expected outcome
A tested migration that can be safely applied and rolled back in production.
Verification
Apply the migration, rollback, and re-apply; confirm the database state is correct at each step.
Cleanup
Roll back the migration if you do not want it applied locally.
Always test rollback
A migration that cannot be rolled back is a production risk. Test the down path every time.
npx prisma migrate dev --name add_users
npx prisma migrate rollback
Implementation Notes
-
Generate migration — Use the migration tool to create a new migration file with a descriptive name. Expected state: A new migration file is created with up and down functions.
-
Apply migration — Run the migration tool to apply the new migration to the local database. Expected state: The local database schema is updated.
-
Test rollback — Run the rollback command to revert the migration and confirm the database returns to the previous state. Expected state: The database schema is restored to the pre-migration state.
-
Re-apply — Apply the migration again to confirm it is idempotent. Expected state: The migration applies cleanly after rollback.
Common Pitfalls
- Should migrations be reversible? Options: Yes, always include down / No, only for schema changes. Recommendation: Always include a down migration; data migrations may need special handling.