Part 07 / Stage 2
SQL and data modeling for integrations
Goal: Get customer data into a shape people can query — modelled, loaded idempotently with upserts, reconciled against the source, and safe to migrate later. Time: ~3 hours · Needs: Python 3.14+ (the examples use the stdlib's sqlite3, so they run anywhere; the SQL shown is standard and carries to Postgres)
What you will learn
- Modeling the target: tables, keys and relationships for the use case
- Staging and core tables: validating a batch before it reaches users
- Upserts:
INSERT … ON CONFLICT, and last-write-wins by timestamp - Reconciliation: counts, missing, extra and mismatched rows
- Indexes for the queries users run
- Migrations: changing schemas safely once people depend on them
Topics in this part
Practice
Work in the course venv (the stdlib's sqlite3 is enough). Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Design and create
Create the shipments core table plus a shipments_staging table with the same columns but no constraints. Insert one invalid row (negative weight) into staging, show a check query that finds it, and confirm core stays empty.
Show the solution to Exercise 1
# Exercise 1: staging catches the bad row before core sees it
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE shipments (
id TEXT PRIMARY KEY, status TEXT NOT NULL, weight_kg REAL CHECK (weight_kg > 0),
updated_at TEXT NOT NULL)""")
# staging has the same columns but no constraints: the raw batch lands here first
db.execute("CREATE TABLE shipments_staging (id TEXT, status TEXT, weight_kg REAL, updated_at TEXT)")
db.execute("INSERT INTO shipments_staging VALUES ('S-2009', 'in_transit', -5.0, '2025-04-10T10:00Z')")
bad = list(db.execute("SELECT id, weight_kg FROM shipments_staging WHERE weight_kg IS NULL OR weight_kg <= 0"))
print("failed checks in staging:", bad)
print("core rows:", db.execute("SELECT count(*) FROM shipments").fetchone()[0])
Exercise 2: Prove the upsert is idempotent
Load the same 3-row batch into the core table three times with the lesson's guarded upsert and assert the row count is 3 and the contents equal a single load.
Show the solution to Exercise 2
# Exercise 2: three loads, one result
import sqlite3
UPSERT = """INSERT INTO shipments VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET status = excluded.status, weight_kg = excluded.weight_kg,
updated_at = excluded.updated_at
WHERE excluded.updated_at > shipments.updated_at"""
BATCH = [("S-2001", "in_transit", 300.5, "2025-04-02T10:00Z"),
("S-2002", "delivered", 85.0, "2025-04-03T10:00Z"),
("S-2003", "delayed", 40.0, "2025-04-04T10:00Z")]
def load_n_times(n):
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE shipments (id TEXT PRIMARY KEY, status TEXT, weight_kg REAL, updated_at TEXT)")
for _ in range(n):
db.executemany(UPSERT, BATCH)
return list(db.execute("SELECT * FROM shipments ORDER BY id"))
assert load_n_times(3) == load_n_times(1)
print("rows after three loads:", len(load_n_times(3)), "- idempotent")
Exercise 3: Out-of-order batches
Craft two batches where batch A has newer data for one id and older data for another (relative to batch B). Apply them in both orders (A then B; fresh table, B then A) and prove the final table is identical either way.
Show the solution to Exercise 3
# Exercise 3: batch order must not matter
import sqlite3
UPSERT = """INSERT INTO shipments VALUES (?, ?, ?)
ON CONFLICT(id) DO UPDATE SET status = excluded.status, updated_at = excluded.updated_at
WHERE excluded.updated_at > shipments.updated_at"""
# A: newer for S-1, older for S-2. B: older for S-1, newer for S-2.
A = [("S-1", "delivered", "2025-04-09"), ("S-2", "in_transit", "2025-04-01")]
B = [("S-1", "in_transit", "2025-04-02"), ("S-2", "delivered", "2025-04-08")]
def apply(batches):
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE shipments (id TEXT PRIMARY KEY, status TEXT, updated_at TEXT)")
for b in batches:
db.executemany(UPSERT, b)
return list(db.execute("SELECT * FROM shipments ORDER BY id"))
ab, ba = apply([A, B]), apply([B, A])
print("A then B:", ab)
print("B then A:", ba)
assert ab == ba
print("order-independent: True")
Exercise 4: Reconciliation function
Write reconcile(source: dict, target: dict) returning {"missing": [...], "extra": [...], "mismatched": [...]}. Test it on a case with one of each, and a clean case that returns three empty lists.
Show the solution to Exercise 4
# Exercise 4: the four reconciliation checks as one function
def reconcile(source, target):
return {
"missing": sorted(source.keys() - target.keys()),
"extra": sorted(target.keys() - source.keys()),
"mismatched": sorted(k for k in source.keys() & target.keys() if source[k] != target[k]),
}
source = {"S-1": "delivered", "S-2": "delayed", "S-3": "in_transit"}
target = {"S-1": "delivered", "S-2": "in_transit", "S-4": "delivered"}
print("dirty case:", reconcile(source, target))
clean = reconcile(source, dict(source))
print("clean case:", clean)
assert all(not v for v in clean.values())
Mini-project: The Acme database
One script: create staging and core tables, load the API shipments (fdelab._API_SHIPMENTS shape — fetch them through the client you built in Part 5 or inline them) through staging with the guarded upsert, run it twice to prove idempotency, then reconcile against the source and print the report.
A solution is in solutions/mini_acme_database.py.
Stretch: add a migration that introduces an origin column without downtime (expand -> backfill -> contract), with a test that runs it.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Modeling the source, not the questions | Users join five tables to answer "where is X?" | Model the customer's queries |
| Loading straight into core tables | A bad batch lands in every dashboard | Stage, validate, then upsert into core |
| Plain INSERTs in a retried job | Every re-run duplicates rows | Upsert on the natural key |
| Last write wins without a timestamp guard | A late old batch overwrites fresh data | WHERE excluded.updated_at > current.updated_at |
| Declaring success without reconciling | Missing rows surface in the customer's monthly report | Counts, missing, extra, mismatched — every load |
| Dropping a column in one release | Running code still reads it; outage | Expand → migrate → contract |
Quick recap
- Model for the customer's questions; keep the natural key and
updated_at. - Staging tables keep bad batches away from the tables people query.
- An upsert makes the load idempotent, and the timestamp guard makes it safe against out-of-order batches.
- Reconcile every load by checking counts and listing the missing, extra and mismatched records.
- Index what the query plan says needs it, and nothing more.
- Migrate in phases; test against a copy of their data.
Checklist
- I designed the shipments table and can defend each column.
- I ran the upsert three times and got the same two rows, newest data winning.
- I can write the four reconciliation checks from memory.
- I read a query plan and know what SCAN vs SEARCH/Index Scan means.
- I can describe expand–migrate–contract in order.
Read more: SQLite ON CONFLICT (upsert) · PostgreSQL INSERT … ON CONFLICT