Use row_factory for readable SQLite inspection output

Direct answer

sqlite3.Row is a row factory that lets a selected row be accessed by column name as well as position. Set it where inspection output is produced, then select explicit columns. The example reads row["id"] and row["state"], so a reviewer can connect the report field to the SQL projection without remembering tuple offsets.

The useful edge case is a changed query order. Name-based access keeps this rendering code correct when SELECT state, id replaces SELECT id, state, while an index-based formatter can silently swap meanings. The assertions prove the intended keys and values in a tiny database before JSON serialization.

A row factory does not validate that a column exists, sanitize values, or make arbitrary rows JSON serializable. Accessing a missing name still raises an error, and a query with duplicate column labels can make a report ambiguous. Keep aliases unique at the reporting boundary. This example also does not change how writes, commits, or transaction isolation behave; it only changes the Python representation of fetched rows.

Complete example

import json
import sqlite3

connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE jobs (id INTEGER, state TEXT)")
connection.execute("INSERT INTO jobs VALUES (7, 'queued')")
connection.row_factory = sqlite3.Row
row = connection.execute("SELECT id, state FROM jobs").fetchone()
assert row["id"] == 7
assert row["state"] == "queued"
reordered = connection.execute("SELECT state, id FROM jobs").fetchone()
assert reordered["id"] == 7 and reordered["state"] == "queued"
record = {"id": row["id"], "state": row["state"]}
assert record == {"id": 7, "state": "queued"}
print(json.dumps(record, sort_keys=True))

Expected stdout:

{"id": 7, "state": "queued"}

Sources

- sqlite3 documentation

- SQLite transaction documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic