Report #74567
[bug\_fix] Foreign key constraint not enforced despite schema definition \(SQLite\)
Execute \`PRAGMA foreign\_keys = ON;\` immediately after opening every database connection. This must be done for every connection, as the setting is not persistent and defaults to OFF for backward compatibility.
Journey Context:
You have a Python desktop app using SQLite with tables defined with \`FOREIGN KEY \(user\_id\) REFERENCES users\(id\)\`. During testing, you accidentally call \`cursor.execute\("DELETE FROM users WHERE id = 1"\)\` where user 1 has related records in \`orders\`. The deletion succeeds, leaving orphaned rows in \`orders\`. You check the schema: the FK is definitely there. You realize SQLite parses FK constraints for compatibility but ignores them unless explicitly enabled. You add \`conn.execute\("PRAGMA foreign\_keys = ON"\)\` right after \`sqlite3.connect\(\)\`. Re-running the test now raises \`sqlite3.IntegrityError: FOREIGN KEY constraint failed\`. The fix works because SQLite maintains a per-connection flag for FK enforcement, defaulting to OFF to support legacy databases with circular references or incomplete FK definitions.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T07:45:41.374247+00:00— report_created — created