Product case study · November 23, 2026
Ask Claude Code to catch SQLite orphan rows
Build a SQLite orphan-row bug, ask Claude Code to fix connection setup, and verify foreign-key enforcement before a transaction begins.

A REFERENCES clause describes a relationship; test that every application connection actually enforces it.
Your database schema says every ticket belongs to a project. Your importer still saves a ticket for project 999, which does not exist. Asking an agent to add another REFERENCES clause won’t help: the relationship is already declared.
The useful debugging question is whether the connection doing the write enforces that relationship. This lab gives Claude Code a small bug where the order of two setup steps matters more than the SQL schema.
You need Python 3.12 or newer with SQLite support, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. The Python fixture and reference repair were tested locally with Python 3.14.4. The agent prompt is an authored exercise, not a recorded Claude run. Official sources were checked November 23, 2026.
Build the broken connection
Create a disposable folder containing only synthetic data:
foreign_key_lab=$(mktemp -d /tmp/claude-foreign-key.XXXXXX)
cd "$foreign_key_lab"
cat > storage.py <<'PY'
import sqlite3
def connect_db(path):
con = sqlite3.connect(path, autocommit=True)
con.execute("PRAGMA foreign_keys = OFF") # Deliberate lab defect.
con.autocommit = False
con.execute("PRAGMA foreign_keys = ON")
return con
PY
The explicit OFF makes the defect reproducible without relying on the SQLite build’s default. The later ON looks reassuring, but SQLite documents that changing this setting inside a transaction has no effect.
Python’s autocommit documentation explains the other half: setting autocommit=False opens a transaction. We have put the switch in the wrong place.
Save this as test_storage.py in the same folder:
import sqlite3
import tempfile
import unittest
from pathlib import Path
from storage import connect_db
class ForeignKeyTests(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.path = Path(folder.name) / "practice.db"
con = sqlite3.connect(self.path, autocommit=True)
try:
con.execute("PRAGMA foreign_keys = ON")
con.execute("CREATE TABLE projects(id INTEGER PRIMARY KEY)")
con.execute("""
CREATE TABLE tickets(
id INTEGER PRIMARY KEY,
project_id INTEGER NOT NULL REFERENCES projects(id)
)
""")
con.execute("INSERT INTO projects VALUES (1)")
finally:
con.close()
def test_each_connection_enforces_foreign_keys(self):
for _ in range(2):
con = connect_db(self.path)
try:
self.assertEqual(
con.execute("PRAGMA foreign_keys").fetchone(), (1,)
)
self.assertIs(con.autocommit, False)
finally:
con.close()
def test_existing_parent_is_accepted(self):
con = connect_db(self.path)
try:
con.execute("INSERT INTO tickets VALUES (?, ?)", (10, 1))
con.commit()
finally:
con.close()
check = connect_db(self.path)
try:
self.assertEqual(
check.execute("SELECT id, project_id FROM tickets").fetchall(),
[(10, 1)],
)
finally:
check.close()
def test_missing_parent_is_rejected(self):
con = connect_db(self.path)
try:
with self.assertRaises(sqlite3.IntegrityError):
con.execute("INSERT INTO tickets VALUES (?, ?)", (11, 999))
self.assertEqual(
con.execute("SELECT COUNT(*) FROM tickets").fetchone(), (0,)
)
finally:
con.rollback()
con.close()
Run the baseline:
python3 -m unittest -v test_storage
The local baseline produced two failures and one pass. The setting test found (0,); the orphan test did not receive the expected IntegrityError. The valid-parent test passed, which is why testing only successful inserts would miss this bug.
The setup connection enables foreign keys before creating the tables. That does not rescue connect_db: SQLite’s foreign-key guide says enforcement must be enabled separately for each connection.
Give Claude Code the repair boundary
Start claude from this practice folder. The first project session lesson covers workspace setup if you need it.
Paste:
Read storage.py and test_storage.py. Run the tests and report the baseline.
Repair only connect_db in storage.py. Each returned connection must enforce
SQLite foreign keys and use autocommit=False for callers' transactions.
Configure and verify enforcement before opening that transaction.
Remove the deliberate OFF setting. If enforcement cannot be enabled,
close the connection and raise an error rather than return it.
Do not edit tests, schema, or insert statements. Do not add application-level
parent lookups, suppress IntegrityError, or disable constraints.
Use only the standard library. Do not install packages, access other
databases, commit files, or delegate. Run the unchanged tests afterward
and explain why the original ON statement had no effect.
This uses Anthropic’s documented debugging workflow: give the agent a reproducible failure and ask it to fix and verify the cause. Review tool requests against this folder; a prompt is not a filesystem sandbox.
I would keep the connection-setting test even after the insert test turns green. It catches an agent that adds a Python parent lookup while leaving the database connection misconfigured.
Review the order, then run the proof
A reference repair for storage.py is:
import sqlite3
def connect_db(path):
con = sqlite3.connect(path, autocommit=True)
try:
con.execute("PRAGMA foreign_keys = ON")
if con.execute("PRAGMA foreign_keys").fetchone() != (1,):
raise RuntimeError("SQLite foreign-key enforcement unavailable")
con.autocommit = False
return con
except BaseException:
con.close()
raise
autocommit=True leaves room to configure enforcement before starting the caller’s transaction. The readback checks the actual setting; then False establishes the requested transaction mode. The broad exception handler only closes the connection and re-raises, including on interruption. It does not convert a failure into success.
Run the same test command yourself. The reference repair passed all three tests locally. Your acceptance evidence is the unchanged test file, the test output and the implementation diff, not the agent’s closing message.
Do not apply this pattern by switching a connection with pending application writes to autocommit=True. Python documents that this transition commits pending work. This helper configures a new connection before it receives any application writes.
Recover from the common wrong fixes
| Symptom | What to inspect |
|---|---|
Readback still returns (0,) | Check whether the agent enabled enforcement after setting autocommit=False or after an explicit BEGIN. |
| Readback returns no row | Check the SQLite library’s foreign-key support; the helper should raise instead of returning that connection. |
| Tests pass only after edits to the test file | Put the original tests back and rerun. Reject a repair that changed the contract. |
| Existing data still contains orphans | Enabling enforcement does not repair historical rows. Inspect a copy before planning a separate data cleanup. |
For an existing database copy, PRAGMA foreign_key_check reports violations:
violations = con.execute("PRAGMA foreign_key_check").fetchall()
Treat those rows as a report to investigate. Do not ask the agent to delete them automatically. A missing parent may mean the parent import failed, and deleting its children would lose the evidence you need to fix the importer.
Sources and verification
Checked November 23, 2026:
- SQLite: foreign-key support — per-connection enforcement and support detection.
- SQLite: PRAGMA reference — transaction restriction, setting readback and violation checks.
- Python: sqlite3 — transaction modes, connection lifecycle and
IntegrityError. - Anthropic: common Claude Code workflows — project-local debugging and verification.
Local testing covers the published Python baseline and reference repair. It does not establish how a particular Claude model will perform or certify a production database migration.
Put this to work
Why enabling SQLite foreign keys inside an open transaction can silently do nothing.
Try
Run a disposable Python lab with one parent table and one child table.
Prove it worked
Run three unchanged tests for connection settings, a valid insert and a rejected orphan.
Keep in view
- Reproduce an insert that accepts a nonexistent parent despite a foreign-key declaration.
- Ask Claude Code to repair connection setup without changing the schema or tests.
- Verify enforcement on fresh connections and reject an orphan row.