Menu

Why SQLite PRAGMA foreign_keys = ON Is Silently Ignored Inside an Active Transaction
📰

Why SQLite PRAGMA foreign_keys = ON Is Silently Ignored Inside an Active Transaction

DEV Community: database·CloudGPU·3 days ago
#6mOvcVHp
#devtodatabase#devto#dev#pragma#conn
Long article (335 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.