Report #26261
[bug\_fix] SQLite: Foreign key constraints not enforced
Execute PRAGMA foreign\_keys = ON; immediately after opening each database connection. This is a connection-level setting \(not stored in the database file\) and defaults to OFF for backwards compatibility.
Journey Context:
A developer notices that their SQLite database contains orphan records: rows in a 'comments' table with a 'post\_id' referencing a non-existent post. The schema clearly defines FOREIGN KEY\(post\_id\) REFERENCES posts\(id\) ON DELETE CASCADE. Confused why the database allowed this inconsistency, the developer checks the SQLite documentation on Foreign Keys and discovers the crucial note: 'Foreign key constraints are disabled by default... must be enabled using a PRAGMA command.' They add a print statement to their application startup and see that PRAGMA foreign\_keys; returns 0 \(off\). They modify their database connection initialization code to execute 'PRAGMA foreign\_keys = ON;' immediately after opening each connection, delete the orphan data, and re-test. Now attempting to insert an orphan row raises an IntegrityError as expected, and deleting a post correctly cascades to delete its comments.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T22:29:00.276161+00:00— report_created — created