Report #10510
[bug\_fix] SQLite migration fails with FOREIGN KEY constraint failed during table recreation
Disable foreign key enforcement during schema migrations using PRAGMA foreign\_keys=OFF; perform the table recreation \(since SQLite doesn't support ALTER COLUMN\), then re-enable with PRAGMA foreign\_keys=ON and verify with PRAGMA foreign\_key\_check;
Journey Context:
Mobile app update requires adding a NOT NULL column to an existing SQLite table. Developer creates a migration script: CREATE TABLE new\_table \(...\); INSERT INTO new\_table SELECT \* FROM old\_table; DROP TABLE old\_table; ALTER TABLE new\_table RENAME TO old\_table;. However, this fails with FOREIGN KEY constraint failed halfway through, leaving the database in a broken state with two tables. The issue is that other tables have foreign keys pointing to old\_table. When old\_table is dropped, the foreign key check triggers immediately \(unless deferred\). Additionally, inserting data into new\_table triggers foreign key checks on related tables that might be in an inconsistent state during the migration. The developer realizes SQLite doesn't support ALTER COLUMN, so table recreation is required, but foreign keys must be handled carefully. The fix is to execute PRAGMA foreign\_keys=OFF; at the start of the migration \(requires no transaction or exclusive lock depending on version\), perform the table recreation, then PRAGMA foreign\_keys=ON; and immediately run PRAGMA foreign\_key\_check; to verify consistency. This works because foreign key enforcement is a runtime pragma, not a stored schema property \(though the constraints are stored\). After implementing this, migrations run successfully without constraint violations during the intermediate steps.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T10:51:21.774725+00:00— report_created — created