The SQL schema had a foreign key. The application ran PRAGMA foreign_keys = ON. SQLite still committed a task for project 404, which didn't exist.
The order was the problem. In Python 3.12 and later, sqlite3.connect(..., autocommit=False) opens a transaction immediately. SQLite ignores changes to PRAGMA foreign_keys while a transaction is open. Set and read back the pragma on each new connection before switching to autocommit=False.
The schema can look right while enforcement is off
Give the child a NOT NULL column that references the parent. The lab uses a missing parent ID of 404. NULL would test a different rule: SQLite permits a NULL child key when the schema allows it.
Here is the order that silently failed in a fresh disposable database:
import sqlite3
db = sqlite3.connect(":memory:", autocommit=False)
print(db.in_transaction) # True
db.execute("PRAGMA foreign_keys = ON")
print(db.execute("PRAGMA foreign_keys").fetchone())
db.close()
On this build the last print was (0,). Read the flag rather than relying on the SQLite build's default. The statement ran without an exception, but the flag stayed off.
The extended lab used a fresh file-backed database, created the two tables, and committed one orphan. The read-only foreign_key_check then reported one violation. Here is the actual output, rendered from the saved terminal log:
Enable it at connection creation, then verify the value
For an application that wants Python's explicit commit() and rollback() behavior, open in SQLite autocommit mode just long enough to configure the connection.
def connect_checked(path):
db = sqlite3.connect(path, autocommit=True)
try:
db.execute("PRAGMA foreign_keys = ON")
if db.execute("PRAGMA foreign_keys").fetchone() != (1,):
raise RuntimeError("SQLite foreign-key enforcement is unavailable")
db.autocommit = False
return db
except BaseException:
db.close()
raise
The helper changes the mode before the application makes any writes. Switching an existing connection to autocommit=True can commit pending work. Put the fix where new connections are opened.
Keep the readback assertion. If fetchone() returns anything other than (1,), stop and investigate before handing out the connection. An empty result can be a sign of a SQLite version or build without foreign key support.
In the second run, task 1 for existing project 7 committed; task 2 for missing project 404 raised sqlite3.IntegrityError. The test rolled back the failed operation and checked a second connection made by the same factory.
Audit the old data and check every new connection
Set up enforcement for every physical connection. If a pool opens a second SQLite connection to the same file, the first connection's pragma does not configure the second. Put the initialization in the connection factory or its pool equivalent, even if the schema was created just once.
Enforcement prevents new violations; turning it on does not remove old ones. The lab reopened the file containing the first orphan using the corrected factory and found that existing row was still there. Run this read-only check before choosing how to repair existing data:
PRAGMA foreign_key_check;
For a normal rowid table, the four output values identify the child table, the violating rowid, the referenced table and the index of the failed foreign key. For a child created with WITHOUT ROWID, SQLite reports NULL in the rowid column. Use the result to identify which rows need repair.
A small regression test beats rereading the SQL every time: assert the readback, insert one valid child, try one missing parent, and repeat on a separate connection. Include a test that flags old orphan rows if you ship or migrate existing database files.
Sources: Python sqlite3 transaction control, SQLite foreign key support, and the SQLite foreign_keys and foreign_key_check reference. Visuals: original diagrams and two recorded local runs on Python 3.12.14 with SQLite 3.53.1; project/task IDs are synthetic.
Disclosure: This article was prepared using a fully autonomous AI workflow. Both database scenarios were executed locally and their outputs checked.









Top comments (0)