Build an idempotent CSV import with Python and SQLite
The nightly import finished just as its worker lost the connection. Should you run it again? A reliable importer leaves the same rows after the second run as after the first. You can build that property into a tiny catalog and measure it without waiting for an actual incident.
- Before you start
- Python 3 with sqlite3 backed by SQLite 3.24 or newer. Start in a new directory.
- What to verify
- After a replay, two products still exist. An updated title changes one row. A malformed record rolls back the batch.
Choose what identifies a product
Save this fixture exactly as catalog.csv, including the final newline. The supplier promises that its SKU stays stable when a title changes. That makes the SKU a useful identity. The quoted field in the second row contains a comma. A parser that splits each line at every comma will lose this product title.
sku,title
C-01,Desk chair
C-02,"Tissues, extra soft"Write down the replay rule for the AI. A repeated SKU may update its title. Products missing from this delivery keep their current data.
Let the database enforce the replay rule
Save the importer. A primary key implements the identity rule even if two input files contain the same SKU. The conflict clause updates a changed title. Its WHERE clause avoids a redundant write when nothing changed. The database transaction surrounds the entire batch.
import csv
import sqlite3
db = sqlite3.connect("catalog.db")
db.execute("CREATE TABLE IF NOT EXISTS products "
"(sku TEXT NOT NULL PRIMARY KEY, title TEXT NOT NULL)")
upsert = '''
INSERT INTO products(sku, title) VALUES (?, ?)
ON CONFLICT(sku) DO UPDATE SET title = excluded.title
WHERE products.title <> excluded.title
'''
with db, open("catalog.csv", newline="", encoding="utf-8") as source:
rows = csv.DictReader(source)
if rows.fieldnames != ["sku", "title"]:
raise ValueError("expected sku,title")
for row in rows:
sku = (row["sku"] or "").strip()
title = (row["title"] or "").strip()
if None in row or not sku or not title:
raise ValueError(f"invalid record at line {rows.line_num}")
db.execute(upsert, (sku, title))
print(db.total_changes, db.execute("SELECT COUNT(*) FROM products").fetchone()[0])
db.close()The input is checked before each write. A malformed row raises an exception and the connection context rolls back earlier changes from this batch.
Measure two identical deliveries
Run the importer twice against the same file and the same catalog.db. Each invocation opens its own connection and reports that connection’s change count, then the total number of products. The first run should print 2 2. The second prints 0 2.
python3 import_catalog.py
python3 import_catalog.pyIf the second run reports two writes, inspect the conflict clause. If it reports four products, inspect the key before changing the loop.
Break the last row on purpose
Save the checker and run python3 check_update.py after the two successful imports. It changes the first title and appends a row with an empty title. The failing subprocess prints the expected validation error. The checker then queries the database to verify that the first title stayed intact.
from pathlib import Path
import sqlite3
import subprocess
import sys
source = Path("catalog.csv")
original = source.read_text(encoding="utf-8")
edited = original.replace("Desk chair", "Desk chair V2")
try:
source.write_text(edited + "C-03,\n", encoding="utf-8")
run = subprocess.run([sys.executable, "import_catalog.py"])
assert run.returncode != 0
with sqlite3.connect("catalog.db") as db:
assert db.execute("SELECT title FROM products WHERE sku='C-01'").fetchone() == ("Desk chair",)
source.write_text(edited, encoding="utf-8")
subprocess.run([sys.executable, "import_catalog.py"], check=True)
finally:
source.write_text(original, encoding="utf-8")The valid amended delivery then prints 1 2. The checker restores the CSV fixture. Running the importer once more will restore the first title in the database too.
Try this prompt with your agent
Review this importer for three cases: identical replay, a corrected title for an existing SKU, and a bad final record after valid changes. For each, predict change count and stored values before running it.A trap worth catching
INSERT OR IGNORE would make the replay quiet but also keep the obsolete title forever. Test a corrected delivery as well as the identical one.