Lawfare Group → Knowledge Institute → Lawfare Academy

← Course syllabus · Related lesson

Make relational integrity an enforced contract

Current complete on-site edition 6

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

Cumulative data-system dossier, transfer models and 30-point rubric

Preserved original teaching integrated with complete current on-site preparation. Independent human subject review and observed learner testing remain pending.

A drawn relationship is not an enforced relationship

A business schema contains customers and invoices. An invoice's customer_id is intended to refer to an existing customer. That intent may be visible in a diagram, an application dropdown or a code comment; none prevents an external import from writing an orphaned reference. A foreign key moves a precisely defined existence rule into the database so that every cooperating write path is subject to the same rule.

The parent key identifies the referenced customer, while the child key is stored on the invoice. They have different roles even when both happen to be integers. For a simple SQLite fixture, use customers(id INTEGER PRIMARY KEY) and invoices(id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id)). This requires an existing parent for a non-NULL child key when enforcement is enabled. It does not require the customer_id to be present: if missing references are invalid for this business, add NOT NULL. A foreign key is not a complete model of invoice validity.

Enable enforcement on the connection that writes

SQLite foreign-key enforcement is a connection setting. Do not infer its state from another connection or from a developer's workstation. Query PRAGMA foreign_keys on the actual connection and deliberately configure the intended state before starting the transaction. Setting foreign_keys inside an active multi-statement transaction does not change enforcement. A migration that issues the pragma after BEGIN can therefore appear to configure a protection while leaving it disabled.

Our fixture starts with enforcement off to reproduce a legacy import. Customer 1 exists. Invoices 11→1, 12→99 and 13→NULL are inserted and committed. An attempt to turn enforcement on inside a transaction leaves the reported setting at zero. After rollback, enabling it outside the transaction reports one. The old orphan does not magically disappear: enabling future enforcement is different from validating existing data. Run PRAGMA foreign_key_check and inspect the reported child table, row identifier, parent table and violated constraint.

Repair evidence, not just a failing check

The orphan 12→99 might represent a mistyped key, a missing customer import or an invoice that should have been rejected. Each explanation calls for a different repair. Do not redirect every orphan to customer 1 merely to obtain a clean report: that creates false business relationships. Preserve the original row and import provenance in an appropriate quarantine or correction log, investigate the authoritative identifier, and apply a documented correction. Then rerun both the foreign-key check and relevant business reconciliation.

In the synthetic laboratory, the orphan is quarantined and removed from the working table so later demonstrations have a valid starting state. That action is an explicit fixture policy, not advice to delete production invoices. With enforcement on, inserting another invoice that refers to customer 99 fails. An invoice with NULL customer_id can still pass the existence constraint unless a separate NOT NULL rule forbids it. This distinction is valuable when testing a schema: include both an invalid known identifier and an absent identifier.

Choose actions and timing deliberately

Deletion behavior is a business choice. Cascading a customer deletion into invoices may destroy financial history; restricting deletion can preserve references but require an archival workflow. SET NULL is meaningful only when an invoice without that relationship remains acceptable. Choose an action based on retention, audit and domain rules rather than on which operation lets a demo finish. Do not confuse a parent-key update with deleting and recreating an identity.

A deferred foreign key permits a temporary violation within a transaction and requires it to be resolved at the constraint's checking boundary. Consider a deferrable initially deferred child reference: inserting child 1→7 before customer 7 can be valid as a transaction sequence if customer 7 is inserted before COMMIT. A foreign_key_check before the parent insert detects the temporary violation; after the parent insert it is empty, and commit succeeds. If the parent is never supplied, commit fails. The application must handle that failure and explicitly roll back or repair the still-active transaction rather than assuming it committed.

Deferred checking is not a way to excuse a permanently broken relationship. It is a way to express an allowed intermediate state while preserving a valid final state. Record which constraints are immediate or deferred, verify the connection settings in the deployed environment, and test both success and failure paths. The laboratory uses separate in-memory connections and synthetic records; it establishes engine behavior for these cases, not the correctness of a production migration or its concurrent workload.

An integrity acceptance ledger

The expected ledger is: enforcement initially 0; pragma inside BEGIN still 0; pragma after rollback becomes 1; the legacy check finds invoice 12 referencing missing customer 99; a new orphan insert is rejected; a NULL reference is allowed by the nullable schema. In the separate deferred fixture, child-before-parent commits only after the parent is supplied. A failed deferred COMMIT leaves a transaction to resolve. Every stage should be asserted, not inferred from a final row count.

Progressive independent practice

Write your analysis before opening each model. Then change the stated fact and revise the reasoning.

Guided

Why can invoice 13 with NULL customer_id pass while invoice 12 with 99 fails?

Compare the model reasoning

The nullable foreign key requires a matching parent for a non-NULL reference. NULL represents an absent reference, not a known invalid parent key. Add a justified NOT NULL rule if absence is forbidden.

Changed conditions

The application substitutes zero for every missing identifier.

Compare the revised analysis

Zero is an ordinary value, so it requires a corresponding parent. Creating a dummy parent zero changes the domain model and must not be used to conceal missingness.

Independent

A deployment executes BEGIN, then PRAGMA foreign_keys=ON and assumes protection is enabled. Design the correction and check.

Compare the model reasoning

Set and read back the pragma before starting the transaction on each relevant connection. Inspect existing violations separately, then test a deliberately invalid write in a disposable fixture.

Changed conditions

Another connection has enforcement enabled.

Compare the revised analysis

That does not establish this connection’s setting. Verify configuration at the actual writer and connection-pool initialization boundary.

Transfer

A deferred COMMIT fails because a parent row is absent. What must the application report and do?

Compare the model reasoning

Treat the operation as uncommitted. Roll back or complete a justified repair within the active transaction; then verify the result. Do not return a success receipt merely because earlier INSERT statements succeeded.

Changed conditions

The caller has already sent an external receipt.

Compare the revised analysis

The database rollback does not retract the external side effect. Reconcile that discrepancy and design durable post-commit delivery, such as an appropriately controlled outbox, rather than pretending the transaction covered the external system.

Source readings and scope

SQLite: foreign key support — Reference for nullable, immediate and deferred foreign keys and connection enforcement. Customer/invoice ledger and acceptance problems are original.

SQLite PRAGMA reference — Reference for foreign_keys and foreign_key_check. No production repair or regulatory retention policy is asserted.

Reproduce the worked cases

Download the Python 3 laboratory. Uses only the standard library and synthetic data. Run locally; it does not access accounts, a network service or production records. Assertions check the stated results.