Test SQLite Foreign Keys Through Your Connection Factory

Test your real SQLite connection factory for orphan rejection, then disable enforcement to verify that the test catches the regression.

OpenThunder Editorial · 2026-12-03

For example, a connection-factory refactor can preserve every migration while removing the statement that enables foreign keys. A schema review still passes, but the application can accept a child row whose parent does not exist.

Test through the application’s real connection factory: accept a valid parent-child pair, reject an orphan, then check that the verifier detects disabled enforcement.

The schema declares the relationship; the connection determines whether SQLite enforces it.

Connection factory checklist

SQLite foreign-key enforcement is a connection-level setting. Enabling it on the migration connection does not establish that later application connections enforce it.

Use these four checks:

Connection check What it establishes
Open through the application factory The test exercises application initialization, not a test-only substitute.
Accept a valid parent-child pair The schema and basic write path work.
Reject an orphan with the expected integrity error Foreign-key enforcement is responsible for the rejection.
Repeat on another open connection Enforcement is not verified on only one connection.

For code review, I would require this behavioral regression test whenever connection initialization changes. Inspecting the schema or finding PRAGMA foreign_keys = ON in a source file does not prove that the application executes it successfully on the connections it uses.

A small factory and an isolated regression test

This template uses Python 3.11 or later, only the standard library, and a temporary SQLite database. It contains no production database path or credentials. It assumes ordinary sqlite3 connections without an already-active transaction; factories with different transaction settings need an adapted fixture.

The synthetic schema tests connection enforcement, not whether production migrations declare the intended foreign keys. Keep schema review as the complementary check.

If your application already has a connection factory, import it instead of copying its implementation into the test suite. Adapt its configuration to accept the temporary database path. Do not add a test-only PRAGMA that repairs the connection before checking it.

For a minimal project, the application factory in app_db.py could look like this:

import sqlite3


def connect_database(database_path):
    connection = sqlite3.connect(database_path)
    try:
        # Set this before starting application transactions.
        connection.execute("PRAGMA foreign_keys = ON")
        return connection
    except BaseException:
        connection.close()
        raise

The orphan must fail for the right reason

A failed insert is not enough evidence.

The valid insert establishes that the tables exist and ordinary writes work. The orphan then uses a fresh child primary key and a non-null parent identifier absent from the parent table. That removes primary-key collisions and nullability violations as explanations for rejection.

The decisive assertion catches only sqlite3.IntegrityError, then checks sqlite_errorname for SQLITE_CONSTRAINT_FOREIGNKEY rather than matching exception-message text. Python added the sqlite_errorname and sqlite_errorcode attributes in version 3.11. A missing table, locked database, or unrelated integrity failure therefore fails the test rather than masquerading as success.

Save the following as test_foreign_keys.py:

import sqlite3
import tempfile
import unittest
from contextlib import ExitStack, closing
from pathlib import Path

from app_db import connect_database


SCHEMA = """
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)
);
"""


def verify_foreign_keys(factory, database_path):
    with ExitStack() as stack:
        connections = []
        for _ in range(2):
            connection = stack.enter_context(
                closing(factory(database_path))
            )

            # Refuse to create tables if the factory ignored the test path.
            databases = connection.execute(
                "PRAGMA database_list"
            ).fetchall()
            main_path = next(
                row[2] for row in databases if row[1] == "main"
            )
            if Path(main_path).resolve() != database_path.resolve():
                raise AssertionError("Factory ignored temporary database path")

            connections.append(connection)

        connections[0].executescript(SCHEMA)

        for number, connection in enumerate(connections, start=1):
            # This must succeed before testing rejection.
            with connection:
                connection.execute(
                    "INSERT INTO parent (id) VALUES (?)", (number,)
                )
                connection.execute(
                    "INSERT INTO child (id, parent_id) VALUES (?, ?)",
                    (number, number),
                )

            try:
                with connection:
                    connection.execute(
                        "INSERT INTO child (id, parent_id) VALUES (?, ?)",
                        (100 + number, 10000 + number),
                    )
            except sqlite3.IntegrityError as error:
                if error.sqlite_errorname != "SQLITE_CONSTRAINT_FOREIGNKEY":
                    raise AssertionError(
                        "Insert failed for the wrong integrity constraint"
                    ) from error
            else:
                raise AssertionError(
                    f"Connection {number}: orphan insert accepted"
                )

            enabled = connection.execute(
                "PRAGMA foreign_keys"
            ).fetchone()
            if enabled != (1,):
                raise AssertionError("Foreign-key setting is not enabled")


def disabled_factory(database_path):
    connection = sqlite3.connect(database_path)
    connection.execute("PRAGMA foreign_keys = OFF")
    return connection


class ForeignKeyTests(unittest.TestCase):
    def test_application_connections_reject_orphans(self):
        with tempfile.TemporaryDirectory() as directory:
            verify_foreign_keys(
                connect_database, Path(directory) / "application.sqlite"
            )

    def test_check_detects_disabled_enforcement(self):
        with tempfile.TemporaryDirectory() as directory:
            with self.assertRaisesRegex(
                AssertionError, "orphan insert accepted"
            ):
                verify_foreign_keys(
                    disabled_factory, Path(directory) / "disabled.sqlite"
                )


if __name__ == "__main__":
    unittest.main()

Run it locally and add the same command to CI:

python -m unittest -v test_foreign_keys.py

The intended outcome is two passing tests: the application factory rejects orphans, and the negative-control test confirms that the verifier catches disabled enforcement.

The final PRAGMA foreign_keys query checks configuration as well as behavior. Keeping it after the insert means the negative control demonstrates an accepted orphan, rather than merely detecting a setting value.

Enable enforcement before a transaction starts

SQLite documents that changing PRAGMA foreign_keys inside an active transaction has no effect. The statement can appear in initialization code without producing the intended setting.

This ordering is therefore unsafe:

connection.execute("BEGIN")
connection.execute("PRAGMA foreign_keys = ON")

Set and verify the pragma before starting application transactions. If enforcement is discovered to be disabled during an active transaction, do not silently commit it as a repair. Resolve that transaction according to the application’s semantics, then configure the connection outside a transaction or replace it with a correctly initialized connection.

Enabling enforcement also does not retroactively reject existing orphan rows. Auditing an existing database is a separate task; SQLite’s PRAGMA foreign_key_check can identify violations already present.

Extend coverage to pools and deferred constraints

This test checks immediate foreign-key enforcement on two connections to one isolated database. If the application has separate read-write factories, pool initialization hooks, or reconnect logic, exercise those paths too. For a pool, make sure the test actually obtains distinct underlying connections rather than repeatedly checking out the same one.

The fixture deliberately uses an immediate constraint. If your application declares deferred foreign keys, test rejection at transaction commit as well: requiring every invalid statement to fail immediately would encode the wrong expectation.

Keep this behavioral check alongside static analysis and schema review. Those checks answer different questions: whether the declarations and initialization code look correct, and whether the resulting connection actually rejects an invalid relationship.

Check that the application test depends on initialization

Point this fixture at your real factory using only a temporary database. Then temporarily remove its foreign-key initialization and confirm that the application test fails with orphan insert accepted; restore the initialization before committing.

These two negative checks serve different purposes. The automated disabled factory verifies the helper. Temporarily removing initialization verifies that the application test depends on the real factory’s enforcement setup.

The fixture assumes it can create its own tables in an empty temporary database. Factories that run migrations on connection need an adapted fixture, not this template unchanged.