A common SQLite bug in Python services is running PRAGMA foreign_keys = ON inside a connection setup helper after a transaction has already started. SQLite does not raise an error when you do this—it silently ignores the statement and leaves foreign key enforcement turned off.
According to the official SQLite documentation, it is not possible to enable or disable foreign key constraints in the middle of a multi-statement transaction. If your driver or wrapper starts a transaction implicitly before your pragma runs, your schema constraints stay inactive until you issue the pragma outside a transaction.
The script below reproduces this behavior locally on Python's sqlite3 module with an in-memory database:
import sqlite3
conn = sqlite3.connect(":memory:", isolation_level=None)
try:
conn.execute("PRAGMA foreign_keys = OFF")
assert conn.execute("PRAGMA foreign_keys").fetchone() == (0,)
conn.execute("BEGIN")
assert conn.in_transaction is True
# Silently ignored inside an active transaction
conn.execute("PRAGMA foreign_keys = ON")
assert conn.execute("PRAGMA foreign_keys").fetchone() == (0,)
conn.execute("COMMIT")
assert conn.in_transaction is False
conn.execute("PRAGMA foreign_keys = ON")
assert conn.execute("PRAGMA foreign_keys").fetchone() == (1,)
print("verified: ignored in BEGIN, active after COMMIT")
finally:
conn.close()
Two practical safeguards prevent this from slipping into production:
-
Check
conn.in_transactionbefore setting pragmas: RunPRAGMA foreign_keys = ONimmediately aftersqlite3.connect(...)and before any query orBEGIN. -
Always read the pragma back: Query
PRAGMA foreign_keysright after setting it and fail startup if the result is not(1,).
Reference: SQLite Documentation · PRAGMA foreign_keys
Disclosure: Drafted with AI assistance; code executed and verified locally on SQLite 3.54.0 using synthetic in-memory data only.
Top comments (0)