Product case study · December 1, 2026

Ask Claude Code to fix a SQLite import that erases notes

Reproduce an import that resets saved notes, ask Claude Code for a scoped SQLite UPSERT repair, and verify updates, inserts and repeated imports.

Reading time
6 min
Checked
Dec 1, 2026
A paper database drawer keeps an ochre note card while an incoming blue tab replaces its title label.
Change the title. Keep the note.
Bottom line

Check the fields an import must preserve, as well as the fields it changes. A correct title can hide a lost note.

Your task importer reports success. The new title appears, the row count stays the same, and the note you wrote yesterday disappears.

A test that checks only the imported title will miss this bug. This exercise gives Claude Code a second requirement: the import owns the title; the user owns the note. Both have to survive the repair.

SQLite documents that REPLACE resolves a primary-key or uniqueness conflict by deleting the conflicting row before inserting the replacement. It is not a shorthand for updating only the supplied columns. See the official conflict-resolution reference.

Use Python 3.10 or newer with SQLite 3.24.0 or newer, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. No packages or real database are needed. The Python reproduction and reference repair below were tested locally; the Claude prompt is an authored exercise, not a recorded agent run. Sources checked December 1, 2026.

Make the missing-note bug visible

Create a disposable folder, then write the intentionally faulty importer:

import_lab=$(mktemp -d /tmp/claude-import.XXXXXX)
cd "$import_lab"
cat > task_import.py <<'PY'
def import_task(connection, task_id, title):
    connection.execute(
        "INSERT OR REPLACE INTO tasks (id, title) VALUES (?, ?)",
        (task_id, title),
    )
PY

Save this as test_task_import.py in the same folder:

import sqlite3
import unittest

from task_import import import_task


class ImportTests(unittest.TestCase):
    def setUp(self):
        self.db = sqlite3.connect(":memory:")
        self.addCleanup(self.db.close)
        self.db.execute("""
            CREATE TABLE tasks (
                id TEXT PRIMARY KEY,
                title TEXT NOT NULL,
                note TEXT NOT NULL DEFAULT ''
            )
        """)
        self.db.execute(
            "INSERT INTO tasks VALUES (?, ?, ?)",
            ("task-1", "Old title", "Call after lunch"),
        )

    def rows(self):
        return self.db.execute(
            "SELECT id, title, note FROM tasks ORDER BY id"
        ).fetchall()

    def test_update_preserves_note(self):
        import_task(self.db, "task-1", "New title")
        self.assertEqual(
            self.rows(),
            [("task-1", "New title", "Call after lunch")],
        )

    def test_new_task_uses_default_note(self):
        import_task(self.db, "task-2", "Second task")
        self.assertEqual(self.rows(), [
            ("task-1", "Old title", "Call after lunch"),
            ("task-2", "Second task", ""),
        ])

    def test_repeat_import_preserves_later_note(self):
        import_task(self.db, "task-1", "New title")
        self.db.execute(
            "UPDATE tasks SET note = ? WHERE id = ?",
            ("Use side entrance", "task-1"),
        )
        import_task(self.db, "task-1", "New title")
        self.assertEqual(
            self.rows(),
            [("task-1", "New title", "Use side entrance")],
        )


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

Run the tests before asking for a repair:

python3 -c 'import sqlite3; print(sqlite3.sqlite_version)'
python3 -m unittest -v test_task_import

The faulty implementation fails the two preservation tests. In each, the actual note is an empty string. The new-task test passes. That passing case matters: replacing the importer with a plain UPDATE would fix the existing-row path but stop creating new tasks.

These tests create a fresh in-memory database each time. They do not read, commit changes to, or repair any existing database file.

Give Claude Code the ownership rule

Launch claude from the lab directory. If setup is new to you, start with the Claude Code lesson. Then send:

Read task_import.py and test_task_import.py in this directory.
Run python3 -m unittest -v test_task_import and report the failures.

Repair only task_import.py. The importer owns id and title as incoming
values, but must preserve an existing task's user-written note.
New IDs must still insert with the schema's default note. Re-importing
an ID must preserve notes edited since the previous import.

Keep parameter binding and leave transaction ownership with the caller.
Do not modify tests, add dependencies, change the schema or open any
other database. Explain why the old SQL loses the note. Rerun the
unchanged tests and report the exact command and actual result.

This follows Anthropic’s advice to give Claude a concrete check and review against the specification. The prompt supplies a business rule the code cannot decide for you: who owns each field. Claude Code best practices.

Keep the initial failure output. If the agent reports success without running the tests, run the command yourself. If it changes the tests to expect empty notes, reject that change: the acceptance requirement has not changed.

Review the repair

A reference implementation is:

def import_task(connection, task_id, title):
    connection.execute(
        """
        INSERT INTO tasks (id, title) VALUES (?, ?)
        ON CONFLICT(id) DO UPDATE SET title = excluded.title
        """,
        (task_id, title),
    )

SQLite’s UPSERT reference explains the two relevant pieces: ON CONFLICT(id) selects the uniqueness conflict, and excluded.title refers to the incoming title. The update assigns only title, so the existing note stays in place. For a new ID, the ordinary insert still uses the note’s schema default.

Rerun:

python3 -m unittest -v test_task_import

The reference repair passes all three tests. Check the returned rows as well as the test count:

CaseRequired result
Existing taskNew title and original note
New taskNew row with an empty default note; existing row unchanged
Repeated importOne row for the ID, with the later user-written note preserved

An INSERT OR IGNORE patch is also insufficient: it would preserve the note but leave the old title. A patch that writes note = '' in the update defeats the ownership rule. The assertions check these observable outcomes without requiring a particular SQL spelling.

If the result still fails

If SQLite rejects the UPSERT syntax, check the version printed by Python, not just the system’s sqlite3 command. Python may use a different SQLite library. UPSERT first appeared in SQLite 3.24.0; use a Python environment linked to a supported version for this lab.

If the first run already passes, check that the starter file still contains INSERT OR REPLACE, that the test module imports that file, and that you ran the command from the practice folder. Do not weaken assertions to manufacture a passing result.

If the notes are already gone from a real database, this SQL change cannot recover them. It prevents this import path from replacing them again. Recovery needs an intact backup or another actual source of the lost values.

Before adapting the pattern, list your real import’s field ownership rules. Some feeds legitimately own every column; others should update only a subset. Add checks for the fields your users expect to keep. This small lab does not validate triggers, foreign-key effects, concurrent writers or disk persistence. The helper deliberately leaves commit and rollback decisions to its caller.

For a separate failure mode involving lost recent records in a backup, see the SQLite WAL backup lab.

Sources and test scope

Official primary sources checked December 1, 2026:

Local verification covers the supplied synthetic Python fixture and reference implementation. It does not establish that Claude will produce the same patch or that a production import is safe without its own tests.

Put this to work

Why INSERT OR REPLACE can discard values omitted from an import.

Try

Run a disposable Python task-import lab with synthetic records.

Prove it worked

Update the title while preserving the note, and keep new-task insertion working.

Keep in view

  • Reproduce a successful SQLite write that resets a saved note.
  • Give Claude Code an explicit rule for which fields the importer owns.
  • Verify existing rows, new rows and repeated imports with unchanged tests.
Learn the workflow: Start a scoped Claude Code project