Bound long SQLite reports with Python’s progress handler
Give a read-only SQLite report a time budget, distinguish interruption from lock errors, and verify the behavior on 50,000 rows.
In this article
Give the report its own budget
A support panel runs a small SQLite report that ranks customers by order value. The caller receives five rows. SQLite still has to read orders, group them by customer, and sort the groups before choosing those rows. Its work can grow while the result stays at five entries. This example gives a single read-only report its own time budget. It also distinguishes two kinds of delay. The connection’s `timeout` controls how long SQLite waits for a database lock. Once the query is running, a progress handler can monitor work such as scanning, grouping, and sorting. Keeping those paths distinct makes a slow report easier to diagnose.
When SQLite calls back
`Connection.set_progress_handler` registers a callback on one connection. The second argument approximates the interval in SQLite virtual-machine instructions. A setting of 1,000 refers to instructions. The time taken by those instructions varies with the query plan and SQLite version. We compute a deadline with Python’s `time.monotonic_ns()` so changes to the wall clock do not move that deadline. The callback returns zero to let SQLite continue and a nonzero value to ask it to stop. It reads the clock and updates one flag. Logging every callback, calling a network service, or executing SQL from inside it would change the workload being measured. The report owns its connection so its callback has a clear scope.
A read-only report you can run
The script creates a database in a temporary directory and distributes 50,000 orders worth 135 cents each evenly among 100 customers. Every customer has the same total, so the query uses the customer ID as a second sort key. The test can assert exactly which rows come first. Integer cents keep rounding out of this example. `Path.as_uri()` builds the file URI and `mode=ro` opens it read-only. An incorrect path produces a connection error instead of creating an empty database. The report executes a fixed SQL statement and calls `fetchall()` within the same budget. A `finally` block removes the handler after either success or failure.
from contextlib import closing
from pathlib import Path
import sqlite3
import time
from tempfile import TemporaryDirectory
REPORT = """
SELECT customer_id, COUNT(*) AS orders, SUM(total_cents) AS total_cents
FROM orders
GROUP BY customer_id
ORDER BY total_cents DESC, customer_id
LIMIT 5
"""
class ReportDeadlineExceeded(TimeoutError):
pass
def top_customers(database: Path, budget_ms: int = 150) -> list[tuple[int, int, int]]:
if budget_ms < 0:
raise ValueError("budget_ms must be non-negative")
uri = database.resolve().as_uri() + "?mode=ro"
with closing(sqlite3.connect(uri, uri=True, timeout=0.05)) as db:
deadline = time.monotonic_ns() + budget_ms * 1_000_000
deadline_triggered = False
def should_interrupt() -> int:
nonlocal deadline_triggered
deadline_triggered = time.monotonic_ns() >= deadline
return int(deadline_triggered)
db.set_progress_handler(should_interrupt, 1000)
try:
return db.execute(REPORT).fetchall()
except sqlite3.OperationalError as error:
code = getattr(error, "sqlite_errorcode", None)
if deadline_triggered and code == sqlite3.SQLITE_INTERRUPT:
raise ReportDeadlineExceeded("customer report deadline exceeded") from error
raise
finally:
db.set_progress_handler(None, 0)
if __name__ == "__main__":
with TemporaryDirectory() as folder:
database = Path(folder) / "sales.db"
with closing(sqlite3.connect(database)) as db, db:
db.execute("CREATE TABLE orders(customer_id INTEGER, total_cents INTEGER)")
db.executemany(
"INSERT INTO orders VALUES (?, ?)",
[(customer % 100, 135) for customer in range(50_000)],
)
rows = top_customers(database, budget_ms=2000)
assert rows == [(customer, 500, 67_500) for customer in range(5)]
print(rows)
try:
top_customers(database, budget_ms=0)
except ReportDeadlineExceeded as error:
assert error.__cause__.sqlite_errorcode == sqlite3.SQLITE_INTERRUPT
print(error)
else:
raise AssertionError("query was expected to be interrupted")
assert top_customers(database, budget_ms=2000) == rows
try:
top_customers(Path(folder) / "missing.db")
except sqlite3.OperationalError as error:
assert error.sqlite_errorcode == sqlite3.SQLITE_CANTOPEN
else:
raise AssertionError("read-only connection unexpectedly created a file")
Test completion and interruption separately
Running the script prints five rows, for customers 0 through 4, with 500 orders and 67,500 cents each. The next line records a deadline exception. Two seconds give the sample room to run. A budget of zero makes the handler ask SQLite to stop at its first callback on this workload. That check is deterministic about the requested cancellation and makes no speed claim. It inspects the underlying SQLite interruption code. A later call against the same file must produce the original five rows. Finally the missing-file test expects `SQLITE_CANTOPEN`, checking that the read-only connection never creates a database at that path.
Classify the error at the boundary
SQLite interruption reaches Python as an `OperationalError`. The example converts it to `ReportDeadlineExceeded` only when the callback marked the deadline as elapsed and SQLite returned `SQLITE_INTERRUPT`. Exception chaining preserves the SQLite error for diagnosis. Missing files, missing tables, and lock waits then keep their own error paths. A support panel can display a report-specific message, such as asking for a narrower date range, while its logs preserve the database result code. An API can count report deadlines independently from availability errors. Repeated deadline events give you a reason to inspect the query plan, narrow the scan, or evaluate a summary table against the same input.
Measure the callback interval and its limits
The handler is cooperative. If the deadline falls between callbacks, SQLite sees it at a later callback. A costly individual operation, a user-defined function, or a filesystem delay can widen that gap. Measure connection setup and lock waiting separately when you care about the full request duration. To tune the instruction interval, run the same fixture and record normal completion time and delay from the deadline to interruption as separate measurements. A smaller interval crosses into Python more often. A larger interval checks less frequently. Choose a production threshold from data representative of your reports. If grouping still dominates each run, the deadline improves request behavior while query design determines how much work is performed. Measure each scenario several times with a consistent database fixture.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment