Lawfare Group → Knowledge Institute → Lawfare Academy

← Course syllabus · Related lesson

A schema migration is a transaction with obligations

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.

Define preservation before writing SQL

A billing table permits negative amounts and has no stable import key. An engineer proposes replacing it with a constrained table. The change is not complete when CREATE TABLE succeeds. A migration must state which records are preserved, which existing records violate the new rules, whether external references remain valid, and how failures leave the database. Treat the migration as a proof obligation about observable business facts.

Our synthetic fixture has invoices A=100 and B=250, stored in integer cents for a deliberately simple example. The intended invariant is two distinct invoice identifiers, total 350, and nonnegative amounts. Real monetary systems also need currency, rounding, tax and reversal policies. A negative amount might be a valid credit under a different model. Do not add a constraint until the business semantics justify it. A migration that deletes credits to satisfy a check is data loss disguised as validation.

Copy, compare, then commit

Within a transaction, create a candidate table with invoice_id TEXT PRIMARY KEY NOT NULL and amount_cents INTEGER NOT NULL CHECK(amount_cents>=0), copy the old rows, and compare invariants before replacing names. The explicit NOT NULL on the identifier avoids relying on historical SQLite behavior for some non-integer primary keys. Count and sum are necessary here but insufficient in general: two changed values can preserve their sum. Compare identifier-to-amount pairs or an exact difference query as well.

Use a fixture containing a violating row before running the real migration. An attempted copy of C=-5 must fail the CHECK. The application must then explicitly roll back the migration transaction. SQLite's default constraint conflict behavior can abort the failing statement without rolling back every earlier statement in the transaction. Catching an exception and proceeding to COMMIT can preserve an unwanted partial operation. Exception handling is part of transaction design, not cosmetic error reporting.

Schema has dependents

Renaming or reconstructing a table can affect indexes, triggers, views and foreign-key references. Inventory them first. The exact ALTER TABLE behavior depends on SQLite version and settings, so use the documented reconstruction procedure for the actual engine and test dependent queries. This lesson's executable fixture has no external references and deliberately proves only its stated invariants. It is not a universal production migration script.

An application may continue writing while a migration is planned. Choose a maintenance or compatibility strategy that prevents those writes from escaping the copy. BEGIN IMMEDIATE requests a write transaction at the start; it can fail with a busy condition. That is a scheduling outcome to handle, not permission to run the copy outside a transaction. WAL mode permits useful reader/writer concurrency but does not turn SQLite into a database with arbitrary simultaneous writers. Keep the write transaction short and retry according to an explicit policy.

Make a repeated import distinguishable from a new event

A client can time out after the database commits. Retrying the same import without a stable event key can insert a duplicate invoice. The absence of a response does not prove the absence of a commit. A uniqueness constraint on an import key lets the database arbitrate concurrent attempts, but the handler must compare the incoming payload with the stored event. Reusing a key for a different amount is a conflict, not a harmless replay.

Avoid a blind INSERT OR REPLACE as an idempotency strategy: replacement has deletion/insertion semantics that may interact with identities and dependent records. A robust design distinguishes first acceptance, identical replay and conflicting reuse. Persist the event and its business effect in one transaction. Return a stable result for identical replay; surface a conflict for a changed payload. The same key alone is not enough unless the system defines which operation it identifies and how long it remains reserved.

Failure and recovery ledger

Start with A=100, B=250. A candidate copy with C=-5 fails. After explicit ROLLBACK, query the original pairs and obtain exactly A=100, B=250; the total remains 350. In the successful path, compare every pair before committing the constrained replacement. A second insertion of import key batch-7 with the same amount is a replay; batch-7 with a different amount is a conflict. Neither should silently add another invoice.

Progressive independent practice

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

Guided

Why is count=2 and sum=350 not proof that the migration preserved both invoices?

Compare the model reasoning

A=150 and B=200 has the same count and sum but changes both facts. Compare exact keyed rows and dependent relationships.

Changed conditions

There are duplicate invoice identifiers in the original table.

Compare the revised analysis

Define a reconciliation policy before adding uniqueness. Do not arbitrarily keep the first row to make the migration pass.

Independent

The candidate copy fails, but a previous metadata UPDATE was successful inside the transaction. What must the handler do?

Compare the model reasoning

Explicitly roll back the whole migration, then inspect the original invariants. Do not assume a statement-level constraint error undoes earlier successful statements.

Changed conditions

The connection is lost before the caller sees COMMIT return.

Compare the revised analysis

The result is uncertain to the caller. Reconnect and inspect a durable migration/version marker and invariants before retrying; a timeout alone is not proof of rollback.

Transfer

An import retry uses the same event key and a changed amount. Specify the response and database checks.

Compare the model reasoning

Compare the immutable stored payload or a canonical payload digest. Return a conflict and preserve the accepted effect; do not treat changed content as an identical replay. Enforce uniqueness and atomically store effect and event.

Changed conditions

Two clients send the first request concurrently.

Compare the revised analysis

Let the database uniqueness constraint arbitrate, then read and compare the winning record after an appropriate transaction/retry boundary. A pre-insert existence check alone has a race.

Source readings and scope

SQLite ALTER TABLE — Schema change and reconstruction behavior.

SQLite transactions — Transaction modes, busy outcomes and statement versus transaction behavior. Laboratory and import policy are original.

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.