Skip to content

LLM and the database

Chapter 11 0 code blocks 1279 words

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.

  1. User → API
    auth, rate limit, user id + permissions
  2. 1
    Understand
    normalize, rewrite follow-ups with the chat history, detect the language
  3. 2
    Router
    rules, a classifier, or the LLM choosing tools
    3a · Documents? → RAG
    embed → hybrid search (pgvector + keyword) → RRF → rerank → threshold → chunks [E1..E6]
    3b · Data? → Tools
    the LLM returns toolCall JSON → validate → fixed SQL on a least-privilege role → rows as JSON (numbers computed by the DB)
  4. 4
    LLM
    system rules + evidence + tool results + question → answer
  5. 5
    Verify
    citations exist, numbers appear in the tool results, refuse if empty
  6. 6
    Answer + sources or SQL shown
    trace 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.
PartJobRule
API layerwho is asking, what they may seepermissions filter both search and SQL
Routerpick documents, data, or bothwhen unsure, ask a clarifying question
RAG pathfind evidence in textthreshold; no evidence → refuse
Tool pathget exact facts from dataleast privilege; parameterized; timeout; row limit
LLMcombine and phrasenever invent numbers; cite sources
Verifiercheck before showingcode checks; failing → refuse or retry
Tracesdebug and evaluatelog 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.

PatternWhat the LLM seesFlexibilitySafetyMy example
RAG (vector store)retrieved chunksdocuments onlyhighRAG app: pgvector
Tool callingtool descriptions + resultswhat I builthighestZargarShop, railway bot
Text-to-SQLschema + query resultsany questionneeds strong guardsTez uses a JSON plan instead of SQL
MCP server (a protocol, not a separate pattern)tools from a standard serverreusable across clientsas safe as its toolsan analytics assistant
LLM
sees only the tool list
My backend
holds DATABASE_URL (env), the pool and a least-privilege role
Database
  1. LLM → My backend
    toolCall JSON
    {"name": "get_order", "args": {"id": 4512}}
  2. 1–3
    My backend
    Check before anything runs
    is the name in the allowlist? are the args valid (type, range)? is THIS user authorized?
  3. 4
    My backend → Database
    Fixed parameterized query
    timeout, LIMIT
    SELECT ... WHERE id = $1
  4. Database → My backend
    Rows
  5. 5
    My backend → LLM
    toolResponse JSON
    only the needed fields, summarized
  6. 6
    My backend
    Log
    tool, args, SQL, ms
  7. LLM
    Writes the answer

Text-to-SQL done safely (if they ask)

  1. Give the LLM only the relevant tables: schema retrieval with column descriptions and a few example question → SQL pairs.
  2. The LLM writes SQL.
  3. Parse it (for example with sqlglot): exactly one statement, SELECT only, allowed tables and columns only.
  4. Add or check LIMIT; optionally EXPLAIN to reject very expensive plans.
  5. Run on a read-only role or a replica, with statement_timeout.
  6. On an error, send the error to the LLM once to fix it; cap the retries.
  7. 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.

Write on Telegram Contents