Treat PRAGMA foreign_keys = ON as connection bootstrap, not as a property that a schema file automatically carries everywhere. To review a coding-agent patch, open the same kind of SQLite connection the application uses, enable enforcement before a transaction begins, read the setting back, and prove both an invalid child insert and an invalid parent delete are rejected. If the check passes only in a command-line shell or on a freshly created database, the patch is not proven.

SQLite documents that foreign-key declarations may be parsed while enforcement remains disabled, and that enforcement is disabled by default in builds that support it. The setting is made separately for each database connection. That makes connection lifecycle part of the data-integrity contract: a pool, test fixture, migration command, and background worker can each have a different result if they do not run the same bootstrap.

Last reviewed: November 24, 2026 (Asia/Shanghai; November 23, 2026 UTC).

Define the relationship contract before reviewing the diff

Start by writing down what the patch promises. Name the parent table, child table, referenced key, nullable behavior, and actions for parent deletion or key updates. Decide whether a child without a parent must fail, whether deleting a parent should fail or cascade, and whether an update should be rejected or propagated. Do not let the agent’s table names stand in for these decisions.

Then inspect the actual schema change. A FOREIGN KEY clause can be present while enforcement is off. A declaration can also point at the wrong parent key, omit part of a composite identity, or specify an action that does not match the application contract. SQLite’s foreign-key documentation separates declaration from runtime enforcement and describes the parent and child sides of the relationship.

Keep this task distinct from a general migration review. The site’s review workflow for database migrations written by coding agents covers data preservation, deployment order, and recovery. This article’s narrower question is whether the running SQLite connection will reject the relationship violations that the schema is meant to prevent.

Build a connection-level fixture that can fail loudly

The smallest useful fixture checks the connection before it creates data. This Python example is a proposed acceptance test; it has not been run against a reader’s repository. Adapt the connection factory, database path, and intended delete action to the application, but keep the read-back assertion.

import sqlite3


def connect_for_test():
    connection = sqlite3.connect(":memory:")
    connection.execute("PRAGMA foreign_keys = ON")
    enabled = connection.execute("PRAGMA foreign_keys").fetchone()[0]
    if enabled != 1:
        connection.close()
        raise AssertionError("SQLite foreign-key enforcement is not enabled")
    return connection


def build_schema(connection):
    connection.executescript(
        """
        CREATE TABLE parent (
            id INTEGER PRIMARY KEY
        );
        CREATE TABLE child (
            id INTEGER PRIMARY KEY,
            parent_id INTEGER NOT NULL,
            FOREIGN KEY (parent_id) REFERENCES parent (id)
        );
        """
    )


connection = connect_for_test()
try:
    build_schema(connection)
finally:
    connection.close()

The important sequence is connect, enable, read back, and only then create or use the transaction. SQLite’s PRAGMA reference states that foreign_keys is a no-op while a transaction or savepoint is active. A wrapper that begins a transaction before running its connection bootstrap can therefore report success while leaving enforcement unchanged. Test the wrapper through the real application path, not through a helper that bypasses the pool.

Python’s sqlite3 documentation documents connect(), execute(), and the module’s transaction controls. Those controls matter here because an implicit transaction can begin on a write, while an explicit BEGIN or a framework-managed transaction changes when the pragma can take effect. If the project configures autocommit or an isolation level explicitly, preserve that configuration in the fixture and record it in the review evidence.

Prove valid and invalid writes on the same connection

A declaration-only test is weak. The acceptance fixture should make the database reject a child that names no parent, accept a child that names an existing parent, and exercise the intended parent-delete behavior. Use bound parameters so the test is about relational behavior rather than SQL construction.

import sqlite3


def test_foreign_key_contract():
    connection = sqlite3.connect(":memory:")
    try:
        connection.execute("PRAGMA foreign_keys = ON")
        assert connection.execute("PRAGMA foreign_keys").fetchone() == (1,)
        connection.executescript(
            """
            CREATE TABLE parent (id INTEGER PRIMARY KEY);
            CREATE TABLE child (
                id INTEGER PRIMARY KEY,
                parent_id INTEGER NOT NULL,
                FOREIGN KEY (parent_id) REFERENCES parent (id)
            );
            """
        )

        connection.execute("INSERT INTO parent (id) VALUES (?)", (7,))
        connection.execute("INSERT INTO child (id, parent_id) VALUES (?, ?)", (1, 7))
        connection.commit()

        try:
            connection.execute(
                "INSERT INTO child (id, parent_id) VALUES (?, ?)",
                (2, 999),
            )
        except sqlite3.IntegrityError:
            connection.rollback()
        else:
            raise AssertionError("orphan child insert was accepted")

        try:
            connection.execute("DELETE FROM parent WHERE id = ?", (7,))
        except sqlite3.IntegrityError:
            connection.rollback()
        else:
            raise AssertionError("parent delete bypassed the foreign key")
    finally:
        connection.close()

The delete assertion is correct only for a restrictive relationship. If the patch intentionally specifies ON DELETE CASCADE, change the expected result to a committed delete followed by an empty child query, and assert that the cascade is limited to the intended rows. Do the same for ON UPDATE CASCADE; never turn a failing test green by weakening the expected behavior after the fact.

Run the fixture against the application’s connection factory, not just sqlite3.connect() in isolation. If the application opens multiple connections, repeat the read-back assertion on every new connection. The setting is connection-scoped; a database file does not make a later connection inherit the earlier connection’s pragma state. Include a reopen or pool-reuse case, because a test suite can accidentally verify only the first connection.

Check the transaction and migration edges

Add a negative bootstrap test that makes the timing mistake visible. On a fresh connection, read the setting, explicitly set it to 0 while no transaction is active, and confirm the read-back is 0. Then begin a transaction, issue the pragma, and read it back; the expected result is that the setting did not change. Roll back and repeat the bootstrap before BEGIN. This is not an application pattern to copy. It is a regression test for wrappers that reorder initialization.

Also check the upgrade path. Create the prior schema, apply the agent’s migration, seed a valid parent and child, and then run the invalid insert and delete cases. A fresh in-memory schema can prove that the new CREATE TABLE text is coherent while missing a migration that leaves existing installations without the constraint. Use PRAGMA foreign_key_list('child') to inspect the declared relationship, and use PRAGMA foreign_key_check as a diagnostic for existing violations. A clean diagnostic does not replace the attempted violating writes: it finds stored problems, while the write tests prove prevention.

For composite keys, test every column and their null behavior. For a referenced key that is not the primary key, verify the required uniqueness and collation assumptions in the actual schema. For deferred constraints, move the assertion to commit: an insert may be temporarily allowed inside the transaction but must fail if the transaction ends with an unresolved relationship. The SQLite CREATE TABLE reference documents foreign-key declarations and constraint behavior; use its rules rather than assuming another database engine’s defaults.

Record evidence and choose the merge decision

Keep the review artifact small and reproducible: SQLite library version, Python or driver version, connection-factory path, result of PRAGMA foreign_keys, declared foreign-key list, fixture schema hash, valid-write result, orphan-write result, parent-action result, and transaction outcome. Do not log full application rows when counts and synthetic identifiers are enough.

Block approval when the pragma read-back is 0, returns no row, or differs between application connections. Block when an orphan insert succeeds, when a restrictive parent delete succeeds, when a cascade deletes unrelated children, or when the migration works only on an empty database. Treat a timeout, unavailable database file, or fixture setup error as inconclusive rather than as a passing constraint test.

The result should also say what was not tested. A static schema inspection does not prove runtime enforcement. A passing local fixture does not prove a production connection pool initializes the same way. A foreign_key_check result does not prove future writes fail. Separate documented SQLite behavior from commands you actually ran, and attach command output only when the review environment produced it.

For CI, make the invalid cases fail the job and preserve the connection setting in the test output. The site’s SQL injection review for coding-agent database patches reinforces the same boundary-first habit: inspect the actual data-access path and test the behavior at the database interface, rather than trusting a helper’s name. For this database task, the “consumer” is the live connection and its transaction lifecycle.

Failure modes

Review gapCheck that exposes it
The schema declares a foreign key but the runtime never enables it.Read PRAGMA foreign_keys on every application connection and require 1.
Bootstrap runs after BEGIN.Start a controlled transaction, run the pragma, and verify the setting remains unchanged.
Only a fresh database is tested.Upgrade a prior schema containing representative parent and child rows.
A cascade is assumed to be restrictive.Delete a parent and assert the explicitly documented action and affected-row set.
A composite relationship omits one identity column.Seed matching and mismatching combinations and inspect the declared key list.
Existing violations are mistaken for future prevention.Run foreign_key_check, then separately attempt invalid writes.
A pool reuses a connection with different initialization.Reopen or reuse connections and repeat the pragma and write assertions.

FAQ

Is a FOREIGN KEY clause enough?

No. The declaration describes the relationship, but SQLite enforcement must be enabled for each supported connection. Prove both the declaration and the runtime rejection behavior.

Is PRAGMA foreign_key_check enough?

No. It is useful for finding existing violations. It does not demonstrate that a future orphan insert or parent action will be rejected on the connection used by the application.

Should every parent delete fail?

Only if that is the contract. CASCADE, SET NULL, SET DEFAULT, and restrictive behavior have different expected outcomes. The test must name the selected action and verify its scope.

What if the pragma returns no row?

Treat it as an environment or library capability failure and block the merge until the supported SQLite build and driver behavior are understood. Do not interpret missing evidence as disabled enforcement or as success.

Sources checked

These official references were checked on November 23, 2026 UTC and remain appropriate for this evergreen runtime task:

Reader next step

Choose one agent-written SQLite schema change and write its relationship contract beside the diff. Run the connection read-back, valid insert, orphan insert, parent-action, reopen, and migration-upgrade cases through the real connection factory. Approve the patch only when the observed outcomes match the explicit contract and the evidence states which tests were actually executed.