Report #10289
[bug\_fix] FOREIGN KEY constraint failed or silently missing referential integrity
Root cause: SQLite disables foreign key enforcement by default \(PRAGMA foreign\_keys defaults to OFF\) for backward compatibility with legacy applications. Without this pragma, INSERT/UPDATE/DELETE statements that violate defined FOREIGN KEY constraints execute successfully, leaving orphaned rows and inconsistent data. The fix is mandatory execution of 'PRAGMA foreign\_keys = ON;' on every database connection immediately after opening it. This is a runtime setting and must be set for each connection; it is not stored persistently in the database file.
Journey Context:
A Python analytics pipeline used SQLite to stage data from CSVs before aggregation. Schema defined foreign keys from 'transactions' to 'accounts', but data loads succeeded even when account\_id values didn't exist in the parent table. Later aggregation queries produced incorrect totals because orphaned transaction rows were excluded from JOINs. Debugging revealed that 'SELECT \* FROM pragma\_foreign\_keys;' returned 0 \(disabled\). Checked the sqlite3 connection setup code; it opened the DB and immediately executed CREATE TABLE but never set the pragma. Modified the connection factory to execute 'cursor.execute\("PRAGMA foreign\_keys = ON"\)' immediately after each 'sqlite3.connect\(\)' call. Re-ran the data load; it now correctly raised 'sqlite3.IntegrityError: FOREIGN KEY constraint failed' on the first orphaned insert, allowing data cleaning upstream.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T10:16:22.807363+00:00— report_created — created