Report #37846
[bug\_fix] SQLite foreign key constraints not enforced despite being defined in schema
Execute PRAGMA foreign\_keys = ON immediately after opening every database connection; this setting is connection-local, defaults to OFF for backward compatibility, and cannot be configured globally.
Journey Context:
A developer builds a task management application using SQLite, defining tables with FOREIGN KEY constraints to maintain referential integrity between tasks and projects. During development, they notice that deleting a project row does not cascade or prevent deletion despite active task references, resulting in orphaned task records with invalid foreign keys. Initially suspecting a syntax error in the CREATE TABLE statements, they verify the schema definition is correct. Investigation into SQLite behavior reveals that the database engine parses and recognizes foreign key constraints for compatibility purposes but does not enforce them by default. This behavior stems from SQLite's historical commitment to backward compatibility with older versions that lacked foreign key support. The critical realization is that foreign key enforcement is controlled by a connection-specific pragma that defaults to OFF. The developer implements a connection initialization routine that executes PRAGMA foreign\_keys = ON immediately after opening each database connection. They also add PRAGMA foreign\_key\_check\(\) to their test suite to verify existing data integrity. Upon deployment, the application now properly rejects insertions violating foreign key constraints and performs cascade operations as defined in the schema, maintaining referential integrity across the dataset.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T18:00:03.287768+00:00— report_created — created