LLM and the database
A read-only AI
Say this
Read-only is enforced by the infrastructure, never by the prompt, because prompts can be bypassed. The database connection itself is read-only, every query has a timeout, the AI only gets read tools, and everything is logged.
Example project
In an analytics assistant, the Postgres connection runs with default_transaction_read_only=on and a 10-second statement_timeout. The model can't write SQL at all; it can only call predefined tools. Every SQL statement is recorded and shown to the user. Even a perfect prompt injection can't change data, because the connection can't write.
If they push
- Add a dedicated DB role with SELECT on views only, a read replica, and row-level security per user.
- If free SQL is ever allowed: parse it (sqlglot), allow one SELECT on allowed tables, add a LIMIT.
Full system: question → AI model → database, in a RAG structure
Say this
A real assistant has two kinds of knowledge: documents (policies, articles, manuals) and structured data (orders, prices, balances). Documents go through RAG: chunked, embedded, searched by meaning. Structured data goes through tools: fixed, parameterized queries on a least-privilege database account. In front of both sits a router. It decides whether a question needs documents, data, or both, often by letting the LLM choose tools, where "search documents" is just one more tool. The LLM never holds a database connection; my backend does. It retrieves or queries, gives the LLM only the evidence, the LLM writes the answer with citations or numbers from the results, the backend verifies it, and everything is logged. So: understand → route → retrieve or query → generate → verify → answer.
- User → APIauth, rate limit, user id + permissions
- 1Understandnormalize, rewrite follow-ups with the chat history, detect the language
- 2Routerrules, a classifier, or the LLM choosing tools3a · Documents? → RAGembed → hybrid search (pgvector + keyword) → RRF → rerank → threshold → chunks [E1..E6]3b · Data? → Toolsthe LLM returns toolCall JSON → validate → fixed SQL on a least-privilege role → rows as JSON (numbers computed by the DB)
- 4LLMsystem rules + evidence + tool results + question → answer
- 5Verifycitations exist, numbers appear in the tool results, refuse if empty
- 6Answer + sources or SQL showntrace logged: question, route, chunks, SQL, latency
An example that uses both paths
"What is our refund policy, and how many refunds did we have last month?"
- Router → both. RAG finds the policy chunk [E1].
- The LLM calls
count_refunds(month="2026-10"); the backend runs a fixed SQL on a read-only role →{"count": 37}. - The answer: "Refunds are allowed within 14 days with a receipt [E1]. Last month there were 37 refunds (from the orders database)."
- Verify: [E1] exists, and 37 appears in the tool result.
| Part | Job | Rule |
|---|---|---|
| API layer | who is asking, what they may see | permissions filter both search and SQL |
| Router | pick documents, data, or both | when unsure, ask a clarifying question |
| RAG path | find evidence in text | threshold; no evidence → refuse |
| Tool path | get exact facts from data | least privilege; parameterized; timeout; row limit |
| LLM | combine and phrase | never invent numbers; cite sources |
| Verifier | check before showing | code checks; failing → refuse or retry |
| Traces | debug and evaluate | log route, chunks, SQL, latency |
My three systems, each a piece of this
- RAG app: the documents path: hybrid search, threshold, citation check, traces.
- ZargarShop: the data path by phone: read tools for the catalog plus one insert-only
create_order, with a human checking new orders.
Questions they ask next
- Why not put the database rows into the vector store too? Embeddings are bad at exact numbers, filters and totals ("how many", "sum", "last month"). SQL does that exactly. Text goes to RAG, numbers to SQL.
- How does the router decide? Simplest: give the LLM both "search_documents" and the data tools and let it choose, with tool descriptions saying when to use each. Cheaper: a small classifier. Measure routing accuracy on labelled questions.
- What if the tool returns nothing? Say so honestly ("no orders found for that period"); never fill the gap from memory.
- Free text-to-SQL or fixed tools? Fixed tools for production: safe and testable. Text-to-SQL only with a parser, a table allowlist, a read-only role, limits and a timeout (chapter 11).
How an LLM connects to a database
Say this
It never connects directly; an LLM only reads and writes text. My application holds the connection, with credentials in environment variables, a connection pool and a least-privilege database role. There are three patterns. One, RAG: the database is a vector store my code searches, and the LLM only sees the chunks. Two, tool calling: I write functions with fixed, parameterized queries and describe them to the LLM; the LLM returns a JSON call, my code validates and runs it, and the LLM sees only the result. Three, text-to-SQL: the LLM writes SQL from a schema, and my code parses it, allows only SELECT on allowed tables, adds limits and runs it on a read-only role. MCP is not a fourth pattern: it is a standard protocol that packages those tools so any AI client can use them. For production I prefer tool calling, because it's safe and testable.
| Pattern | What the LLM sees | Flexibility | Safety | My example |
|---|---|---|---|---|
| RAG (vector store) | retrieved chunks | documents only | high | RAG app: pgvector |
| Tool calling | tool descriptions + results | what I built | highest | ZargarShop, railway bot |
| Text-to-SQL | schema + query results | any question | needs strong guards | Tez uses a JSON plan instead of SQL |
| MCP server (a protocol, not a separate pattern) | tools from a standard server | reusable across clients | as safe as its tools | an analytics assistant |
Text-to-SQL done safely (if they ask)
- Give the LLM only the relevant tables: schema retrieval with column descriptions and a few example question → SQL pairs.
- The LLM writes SQL.
- Parse it (for example with sqlglot): exactly one statement, SELECT only, allowed tables and columns only.
- Add or check
LIMIT; optionallyEXPLAINto reject very expensive plans. - Run on a read-only role or a replica, with
statement_timeout. - On an error, send the error to the LLM once to fix it; cap the retries.
- Show the SQL to the user, and check numbers in the answer against the rows.
Connection details interviewers like
- Credentials in environment variables or a secret manager, never in the prompt or the code.
- A connection pool, because opening a connection per request is slow; close connections reliably.
- Parameterized queries only (
$1,%s), never string-built SQL, to prevent injection. - Large results: aggregate in SQL or return the first N rows plus a count. Never paste thousands of rows into the context.
- Per-user permissions: the backend filters by the real user (row-level security), not by what the LLM asks.
My examples
- ZargarShop: two read tools + one insert-only
create_order; staff review new orders. - Tez: the model writes a JSON plan from a fixed set of 19 tools, never SQL; DuckDB executes it; a grammar forces valid JSON.
Questions about this chapter?
The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.