1.5 KiB
1.5 KiB
Database Migrations & Schema Modification Rules
1. Defensive Migrations
When making database schema changes, you must ensure that generated migrations are resilient against environmental discrepancies.
- Review Generated SQL: Always review the
.sqlfiles generated bynpx prisma migrate dev. - Add "IF EXISTS" clauses: SQLite and Prisma can sometimes produce brittle drop statements (
DROP INDEX "my_index"). To prevent migrations from crashing if a state desynchronization occurs (e.g., the index was already dropped or never created), manually edit the migration file to useDROP INDEX IF EXISTS "my_index";orDROP TABLE IF EXISTS "table_name";. - Data Preservation: When dropping columns or renaming, SQLite does not cleanly support it and requires table recreation. Carefully review the
INSERT INTO "new_table" SELECT ...clauses to ensure data is correctly mapped.
2. Managing Failed Migrations
If a migration fails in production:
- Never blindly mark as resolved: Do not run
prisma migrate resolve --applied <migration_name>unless you have explicitly verified that the database schema precisely matches the expected state. - If you use
resolve --applied, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
3. Backups Before DDL
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database (via Prisma or direct SQLite access) without first confirming an automated backup exists, or manually taking a backup of the wwv.db file.