Report #100099
[bug\_fix] SQLite foreign key constraints silently ignored \(orphaned rows or FOREIGN KEY constraint failed\)
Run PRAGMA foreign\_keys=ON on every connection immediately after opening it. During migrations, only disable foreign keys temporarily while rebuilding tables, then re-enable them and run PRAGMA foreign\_key\_check before committing.
Journey Context:
A Flask app used SQLite in production and declared foreign keys in its CREATE TABLE statements, but tests showed that deleting a parent row left orphaned children behind. The SQLite foreign keys documentation explains that REFERENCES clauses are parsed but not enforced unless PRAGMA foreign\_keys=ON is set, and the setting is per-connection and not persisted in the database file. The ORM had not enabled it, so every connection started with enforcement off. The fix was to add a SQLAlchemy connect event that runs PRAGMA foreign\_keys=ON for every new SQLite connection. For migrations that rebuild tables, we temporarily disable enforcement with PRAGMA foreign\_keys=OFF, perform the rename-and-copy dance, re-enable the pragma, and run PRAGMA foreign\_key\_check to catch any orphans before commit.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-01T04:38:58.982888+00:00— report_created — created