Retrieve structured answers with approved query plans, row-level permissions and verifiable source identifiers.
Database retrieval: link a question to schema and trace the rows
Retrieve a schema contract first
Database retrieval maps a question to tables, columns, joins and filters before reading rows. A request for unpaid invoices from branch 47 should identify invoice status, branch ID and billing date; an embedding over column descriptions may help discover candidates but cannot define the final join. Store approved schema descriptions, key relationships and field meanings. A column named amount may be gross, net or settled. Intent routing should distinguish a row lookup from a policy explanation or a calculation.
Keep query generation bounded
Treat a proposed SQL query as untrusted input. Constrain it to an allowlisted read-only view or a small set of approved query templates. Bind values as parameters, cap rows and time, and reject mutations or cross-tenant joins. Parsing a generated string for the word SELECT alone is not a security boundary; database permissions and row-level security must enforce scope. Access control belongs at the data source as well as in the retrieval layer.
Carry row provenance into the answer
Return primary keys, source table or view, query template version, data snapshot and effective filters with each result. An aggregate such as '47 unpaid invoices' needs a traceable query and the population definition, not merely a plausible sentence. If a join multiplies rows, count distinct invoice IDs or fix the join before answering. For a cell-level claim, identify both the row and column. Table evidence requires the unit and row context that make a number meaningful.
Separate retrieval from computation
A row set may require arithmetic after retrieval, but that computation should be deterministic and reviewable. Currency conversion needs an explicit rate and as-of date; a missing rate should cause a partial answer or abstention. A result that combines transactional rows with a document policy needs separate citations to each source. Evidence chains should show which source supplies the rule and which supplies the transaction facts.
Evaluate query and result failures
Judge schema linking, authorized row recall, predicate accuracy, join cardinality and final answer support separately. Include duplicate line items, soft-deleted records, null status, renamed columns and time-zone boundaries. A syntactically valid query can be semantically wrong: selecting posted_at instead of due_at may produce credible but incorrect overdue counts. Compare the executed query and returned row IDs against a reviewed reference set; do not grade only the final prose.
Worked contract
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE invoices (invoice_id TEXT PRIMARY KEY, tenant TEXT, branch INTEGER, status TEXT, amount_cents INTEGER)")
connection.executemany("INSERT INTO invoices VALUES (?, ?, ?, ?, ?)", [
("INV-47", "north", 47, "unpaid", 8300),
("INV-48", "north", 47, "paid", 4700),
("INV-49", "south", 47, "unpaid", 9900),
])
def unpaid_invoices(tenant: str, branch: int) -> list[tuple[str, int]]:
return connection.execute(
"SELECT invoice_id, amount_cents FROM invoices "
"WHERE tenant = ? AND branch = ? AND status = ? ORDER BY invoice_id LIMIT 83",
(tenant, branch, "unpaid"),
).fetchall()
assert unpaid_invoices("north", 47) == [("INV-47", 8300)]
connection.close()Performance and operating cost
With an index on tenant, branch and status, a selective lookup can avoid scanning every invoice; the exact cost depends on the planner and row count. The in-memory example is tiny, but a production read needs a row cap, execution timeout and query plan check. Materializing R result rows costs O(R) memory; stream large exports rather than placing them in an answer context.
Common Mistakes
- Executing free-form generated SQL with broad database privileges.
- Using a similarly named amount column without checking its business definition.
- Counting joined line items as distinct invoices.
- Omitting row IDs and filter values from an aggregate's audit trace.
Validation drill
Create 43 questions against invoices, payments and branch tables. Include duplicate line items, nulls and two tenants. Require matching row IDs, approved schema paths, correct aggregate populations and no cross-tenant disclosure.
