Header Ad Placement

SQLite Foreign Keys: Why a Declared Constraint May Still Be Inactive

DATABASE INTEGRITY

A schema declaration, an enabled connection and a clean data check answer different questions. None should silently stand in for the others.

By Hossam

The relationship exists in the schema. Does it protect this write?

An application defines a child table with REFERENCES, its migration finishes, and a developer assumes every later write must preserve that relationship. With SQLite, that conclusion skips an operational boundary: foreign-key enforcement is a connection setting, not merely a property visible in the table definition.

A second connection can use the same database file without the enforcement setting chosen on the first. A command intended to enable checking can also have no effect if it runs inside a transaction. Those cases can leave the schema looking correct while a particular write path admits an orphaned reference.

This guide combines official documentation with a small, sequential experiment on a disposable local database. It does not audit an application or reproduce a production incident. The test used Python 3.10.12 and SQLite 3.37.2, an old runtime that is not a recommendation for deployment. Results below are limited to that experiment; use a supported patched library and verify your own driver behavior.

Documentation: SQLite foreign key support, SQLite PRAGMA reference, Python sqlite3 documentation.

Verify the library and the connection, not the default

SQLite documents compile-time conditions as well as runtime activation. A build that omits the relevant foreign-key or trigger support does not have ordinary enforcement behavior. A declaration being parsed is therefore weaker evidence than a successful enforcement check on the actual library.

The documentation also warns against relying on the default setting. Builds can select a different default, and defaults can change. Establish the application-required value explicitly when a connection is initialized, then query PRAGMA foreign_keys on that connection. Do not turn a remembered default into a deployment assumption.

The query normally returns a row containing zero or one. SQLite says that no returned data indicates a library without the required support, rather than an ordinary disabled setting. Treat an unexpected result as something to investigate, not as a successful enable operation.

Documentation: SQLite foreign key support, SQLite PRAGMA reference.

One enabled connection does not configure a pool

The runtime setting must be established separately for each database connection. That matters when a web worker, background job, command-line import tool and migration runner all open the same file. A healthy check in one shell does not establish the state of those other writers.

SQLAlchemy makes this boundary explicit in its SQLite dialect guidance: the enabling statement belongs on all connections before use, including the initial schema-creation connection. Its connection-event example addresses that lifecycle rather than setting the flag once on an arbitrary checked-out connection.

Follow the guidance for the ORM and driver versions actually deployed. Connection reuse and new connection creation are different events. A useful application acceptance test exercises the real connection-creation path, then verifies the setting and an expected rejection without touching production data.

Documentation: SQLite foreign key support, SQLAlchemy SQLite dialect.

A successful enable statement can be a no-op

PRAGMA foreign_keys cannot change enforcement while a BEGIN or SAVEPOINT is pending. SQLite documents that such an attempt has no effect; it does not have to raise an error. This is why checking only that the initialization SQL executed without an exception is insufficient.

Place connection initialization at an appropriate transaction boundary and read the value back. If a transaction is already active, do not blindly commit real application work merely to make a configuration statement take effect. Fix the initialization path with an understanding of which component opens transactions.

Python illustrates why driver behavior matters. Its current documentation distinguishes the newer autocommit attribute from SQLite low-level autocommit state. Setting the Python attribute to True can commit a pending transaction. Copying a startup recipe into a live request can therefore do more than change a flag. The SQLAlchemy example temporarily adjusts driver state during connection setup; it is not general permission to commit at arbitrary points.

Documentation: SQLite foreign key support, SQLite PRAGMA reference, SQLAlchemy SQLite dialect, Python sqlite3 documentation.

What the disposable experiment actually showed

The experiment opened two connections, A and B, to one temporary database with explicit SQL transaction boundaries. It explicitly disabled enforcement on both before constructing a parent table p and child table c. The child had an integer pid referencing the parent primary key. This controlled starting state avoids claiming that every installation starts disabled.

Enabling A produced connection values of one for A and zero for B. B then began a transaction, attempted to enable enforcement, and still read zero. While disabled, B inserted child row 1 referencing missing parent 99 and committed. The point was to isolate connection scope and transaction timing, not to measure performance.

A reported ok from PRAGMA integrity_check. On that same database, PRAGMA foreign_key_check returned one violation identifying child c, row 1, parent p and foreign-key index zero. After enabling B outside a transaction, a new orphan insert was rejected. The existing orphan remained a separate data-quality finding.

The experiment was strictly sequential and local. It did not test connection pools, concurrent writers, crashes, migrations or the newer Python autocommit interface. Those limits matter: a controlled result can demonstrate the documented distinction without certifying every application path.

Documentation: SQLite foreign key support, SQLite PRAGMA reference, Python sqlite3 documentation.

Existing rows need their own check

Enabling enforcement should not be described as a repair of every relationship already stored in the file. The old orphan in the experiment was found by an explicit check. A corrected startup path and a cleanup of existing data are different pieces of work.

Use the appropriate scope of PRAGMA foreign_key_check to inspect declared relationships. SQLite documents a row per violation, with columns identifying the child table, the offending rowid when available, the parent table and the foreign-key index. A WITHOUT ROWID child table can produce NULL in the rowid column, so do not assume every result can be addressed through a rowid.

The table-specific form checks references declared by that child table, not every relationship throughout the database. Likewise, no returned violations says something about the constraints and data checked at that point. It does not invent missing business rules or guarantee that a later, differently configured writer will behave correctly.

Documentation: SQLite foreign key support, SQLite PRAGMA reference.

integrity_check is not foreign_key_check

The names invite an overly broad interpretation. SQLite describes integrity_check as a low-level formatting and consistency check that also covers several constraint classes. Its documentation explicitly says it does not find FOREIGN KEY errors.

An ok result is therefore useful evidence within that command's scope, not a general certificate that all declared parent-child relationships are valid. In the disposable test, ok and a reported orphan were both correct answers to different questions.

Record which check ran, its scope, its full result and the database state to which it applied. An operational report that says only integrity passed can hide whether relational checks were ever performed. Physical consistency, declared relationship validity and application correctness should stay separate in the acceptance record.

Documentation: SQLite PRAGMA reference.

NULL and mismatched keys are different cases

A child foreign-key value of NULL can satisfy the foreign-key rule without a matching parent. For a composite child key, SQLite similarly does not require a parent match when a child-key component is NULL. If the application requires the relationship to be present, express that requirement with the appropriate NOT NULL constraints as well.

The disposable experiment accepted a NULL child key with enforcement enabled. That was expected behavior, not proof that enforcement had switched off. Test a genuinely invalid non-NULL reference when checking rejection, and test missing required values separately.

Also distinguish a data violation from an invalid relationship definition. SQLite requires a suitable parent primary key or unique key, including the documented collation conditions. Some errors involving both table definitions surface when a modifying statement is prepared, rather than when CREATE TABLE runs. A successful schema-creation command is not a substitute for reviewing and exercising the relationship.

Documentation: SQLite foreign key support.

A deferred insert can pass while commit fails

Foreign-key constraints are immediate by default, but a declaration can make a constraint initially deferred. A temporary violation inside an explicit transaction can then be allowed until COMMIT. Testing only the insert result misses that final boundary.

In the disposable experiment, an insert into a separate table with a deferred reference succeeded before commit. COMMIT then failed because the parent was absent, and the transaction remained open until the test explicitly rolled it back. Do not report an accepted statement as a committed business operation.

Deferred timing is not permission to ignore configured referential actions. SQLite documents that RESTRICT acts immediately even when its associated constraint is deferred. More broadly, handle the actual transaction outcome rather than assuming every database error automatically ended the transaction.

Documentation: SQLite foreign key support, SQLite transactions.

Treat migrations as a separate integrity boundary

A migration runner is another database client with its own connection and transaction behavior. Merely adding an enable statement somewhere in its script does not establish that the statement took effect. The same no-op rule applies if the runner already opened a transaction.

SQLite documents a specific generalized table-rebuild procedure for schema changes beyond its direct ALTER TABLE operations. That procedure has an order for enforcement settings, transactions, data transfer, dependent objects and foreign-key checking. It is not equivalent to an improvised rename-and-copy sequence.

This article has not executed that migration procedure and is not a production migration recipe. Follow the current official procedure for the intended change, test it on an isolated copy, preserve a verified recovery path, and check both the resulting data and the settings on subsequent application connections. Do not use direct schema-text edits as a shortcut merely because a declaration looks simple.

Documentation: SQLite foreign key support, SQLite ALTER TABLE.

The useful acceptance record

A useful result names the library and driver, confirms enforcement on the actual connection path, exercises an expected rejection, checks existing declared relationships and records the final transaction result. Each item closes a different gap. A screenshot of REFERENCES in a schema browser closes very few of them.

Keep safety and completeness in proportion. Do not test rejection by inserting bogus rows into a production workflow, and do not automatically delete every child row reported by a checker. An orphan can represent missing parent data, an incorrect identifier, a migration error or an intended business state that the schema models badly. The checker identifies a relationship violation; it does not choose the business repair.

Documentation: SQLite foreign key support, SQLite PRAGMA reference, SQLAlchemy SQLite dialect.

Related reading

Relationship enforcement is separate from checkpoint progress. See why a successful SQLite WAL commit can leave the log growing. The two articles address different checks.

Sources and test scope

Official documentation supplies the semantics; the stated disposable local experiment checks a limited subset on the recorded older runtime. No application, production database, migration, connection pool or all-version compatibility was tested.


 

Comments

Docker Build Contexts: What .dockerignore Excludes and COPY Does Not

CONTAINER BUILD INPUTS The context decides which files a build can access. A copy instruction decides what one step puts into a stage. Review those boundaries separately. By Hossam Start with the input boundary, not the final image A Dockerfile that copies only application files can still have a wider build context than its author intended. The context is the set of files available to the build, while COPY describes one operation using a source. A selective copy is useful, but it is not the same control as excluding an input from the context. Docker documents .dockerignore as a way to remove matching files and directories from the context before it is sent to the builder. That makes context selection and ignore rules worth reviewing even when the final runtime image appears small. A final-image inspection answers a different question from a build-input review. This guide analyzes Docker documentation. Its example repository layout and review steps are illustrative, not captured b...

Editorial Governance & Pages