SQLite is an embedded relational database that stores structured tables and answers SQL queries without a separate database server.
Bind query values safely, group changes into transactions and check how failures affect a batch of writes.
A batch contains three records; the third repeats an earlier primary key. Should the first two remain stored? SQLite lets us make that a transaction decision. First keep query structure separate from input values, then inspect what commits and what rolls back when the batch fails.
You'll build store_batch(raws), the vault itself: a batch goes in as one
transaction, all of it or none of it.

Look up a customer by a name with an apostrophe
The obvious way to put a value into a query is an f-string, and it's the one way you must never use — it breaks on an ordinary surname before anyone attacks anything:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE people (name TEXT)")
conn.execute("INSERT INTO people VALUES ('Siobhan')")
name = "O'Brien"
rows = conn.execute(f"SELECT * FROM people WHERE name = '{name}'").fetchall()
print(len(rows))Fix the lookup so a real surname works, using a parameter instead of a pasted string:
OperationalErrorRun it, then rewrite the SELECT so the name travels as a parameter.
Preparing this topic’s interactive investigation…
Stop a hostile "source name" from rewriting the query
That's the accidental version. The deliberate version is SQL injection: a value crafted to change what the query means without breaking its syntax:
The formatted query returns every row, because the value rewrote the
WHERE clause into something always true. The parameterised query returns
none, because it looked for a source literally named nobody' OR '1'='1,
and there isn't one. That difference is structural: with ?, SQL text and
values travel separately — the statement compiles first and the value is
bound afterwards as data, so it can never become SQL, whatever characters it
holds. Two placeholder styles work: ? with a tuple, and :name with a dict
— handy because Quarry's records already are dicts:
Placeholders stand for values only — you can't parameterise a table or column name. If one really has to vary, choose it from a fixed allow-list in your code, never straight from input.
Insert a batch where one row breaks a rule
A batch of 500 records where record 312 duplicates a primary key should not
leave 311 stored — the next run couldn't tell what landed and what didn't.
With the transaction mode used below, with conn: commits an open
transaction on a normal exit and rolls back if the block raises:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, ms INTEGER)")
batch = [(1, 120), (2, 95), (1, 40)] # id 1 appears twice
try:
with conn:
conn.executemany("INSERT INTO records VALUES (?, ?)", batch)
except sqlite3.IntegrityError:
pass
print(conn.execute("SELECT COUNT(*) FROM records").fetchone()[0])Constraints are what make "bad" detectable: PRIMARY KEY refuses
duplicates, NOT NULL refuses missing values, CHECK (level IN (...))
refuses a level Quarry doesn't know — each raises sqlite3.IntegrityError at
insert time, instead of turning up in a report next week. executemany takes
one statement and an iterable of parameter sets, and conn.row_factory = sqlite3.Row lets a row behave like both a tuple and a mapping:
Put the exception outside the transaction boundary
The context manager observes how its block exits. The position of except therefore changes whether a partial batch commits. If the duplicate-key error escapes the with conn: block, the connection context manager can roll back. If you swallow it inside that block, the context manager sees a normal exit and may commit earlier successful inserts.
The two outputs are [ (1,) ] and [] apart from display spacing. The difference is not whether SQLite detected the duplicate—it did in both cases—but whether the transaction owner learned that the batch failed.
These examples use Python's legacy transaction-control default. Python 3.12+ exposes Connection.autocommit; choosing True means with conn: does not create an all-or-nothing transaction for you. Read the selected transaction mode before generalizing this pattern. The connection context manager also does not close the connection; closing is a separate resource-lifetime responsibility.
Try a new boundary: first commit id 9, then attempt a batch containing ids 1, 2, 1. After rollback, predict whether id 9 survives. It should: rollback undoes the failed transaction, not all database history. Ask SQL for the remaining rows rather than trusting a Python-side counter that incremented before rollback.
Reference: SQLite transaction control and connection contexts.
Traps worth knowing
SQLite stores five kinds of value: NULL, integer, real, text, blob —
None, int, float, str, bytes. Anything else needs a decision, the
same kind JSON forced on you: a datetime becomes value.isoformat() as
TEXT (sqlite3's automatic datetime conversion is deprecated since 3.12 —
be explicit); a list or set, like Quarry's tags, becomes
json.dumps(sorted(tags)) as TEXT; a Decimal becomes str(value).
SQLite doesn't enforce column types by default. A column declared
INTEGER will quietly store the string "slow" unless you add STRICT
after the table definition, a CHECK constraint, or convert before
inserting.
Quick practice
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, note TEXT NOT NULL)")
try:
conn.execute("INSERT INTO t (id) VALUES (1)")
except sqlite3.IntegrityError as exc:
print(type(exc).__name__)ProgrammingErrorRun it and read which type the driver refuses to bind. Pack the list as JSON text before inserting.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE t (n INTEGER)")
with conn:
conn.execute("INSERT INTO t VALUES (?)", (5,))
try:
with conn:
conn.execute("UPDATE t SET n = n + 1")
raise ValueError("boom")
except ValueError:
pass
print(conn.execute("SELECT n FROM t").fetchone()[0])🎯 Your turn
Write store_batch(raws). Each raw record has id, source, level and
ms.
- Connect to
":memory:", setrow_factory = sqlite3.Row, and create the table with the starter'sSCHEMA. - Insert the whole batch with
executemanyand:nameplaceholders, insidewith conn:. - If that raises
sqlite3.IntegrityError, note the error's class name. Thewithblock has already rolled back. - Read everything back with
SELECT id, source, level, ms FROM records ORDER BY id, turning each row into a dict. - Return
{"rows": [...], "error": None}, or with"error": "IntegrityError"when the batch was refused, in which caserowsis[].
A source named web'); DROP TABLE records; -- must be stored exactly as
written.
Hint: set error = None before the try, and do the SELECT after the
try/except, so both paths share it.
Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write count_rows(values). Make a :memory: database with a table t (v), insert each value as its own row with executemany and a ? placeholder, and return SELECT COUNT(*) FROM t as an int.
Write find_by_level(raws, level). Store the records (each has id, level, ms) in a :memory: table, then return the ids whose level equals level, in id order, using a ? parameter. The last test passes an injection attempt as the level: it must match nothing.
The starter fills a people table with Ada, O'Brien and Siobhan. Write injection_demo(name) that runs the same lookup twice: once with an f-string (WHERE name = '{name}') and once with a ? parameter. Return {"formatted": row count or the exception's class name, "param": row count}.
Write load_batches(batches). Each batch is a list of [id, ms] pairs. Use one :memory: table records (id INTEGER PRIMARY KEY, ms INTEGER NOT NULL) for all of them, and insert each batch in its own with conn: block. A batch that raises sqlite3.IntegrityError is rolled back on its own. Return {"stored": total rows in the table, "failed": [indexes of failed batches]}.
Quarry reruns a batch whenever a source file changes, so storing must be idempotent. Write upsert_runs(first, second): create records (id INTEGER PRIMARY KEY, level TEXT NOT NULL, ms INTEGER), then store first and then second, each in its own transaction, with INSERT ... ON CONFLICT(id) DO UPDATE SET level = excluded.level, ms = excluded.ms. Return all rows as dicts (id, level, ms) in id order.
A teammate proposes fixing the f-string queries by writing name.replace("'", "''") before formatting them in. Explain what the ? placeholder does differently, why that makes it safe in a way escaping isn't, and why the O'Brien crash matters even though nobody was attacking.