Text-to-SQL fails quietly. A model that writes plausible SQL against a raw schema will, sooner or later, join sales lines to returns and double count, redefine "net revenue" between two askings, show a branch manager another branch's rows or scan a whole fact table to answer a one-line question. None of these raise an error. They return a confident number.
Our position is simple: the model proposes, the guard disposes. The model never decides what a metric means, which rows a user may see or how much the warehouse may spend. Those decisions live in a governed semantic layer and in code that parses every statement into a syntax tree and judges the tree, backed by a database connection that could not write even if the guard were wrong.
Below is that design as we built it in our Text-to-SQL Copilot prototype (DuckDB, SQLGlot, a synthetic retail warehouse): the layering, a working guard, the budgets that keep a query cheap, how to show your work and how to measure it.
The model proposes, the guard disposes
The failure modes of free-written SQL fall into four groups, and each needs a different control:
| Failure | Example | Control that stops it |
|---|---|---|
| Wrong meaning | "Sales" summed as gross one day, net the next | Governed metric definitions with an owner |
| Wrong shape | Joining two facts before aggregating, so each sale counts once per return | Compiling from the layer; many-to-one joins only |
| Wrong reach | A hidden column, another branch's rows, a file on disk | Syntax-tree checks, an access rewrite, a locked connection |
| Wrong cost | A fan-out join or an unbounded scan | Row cap, cost estimate, hard timeout |
Prompting fixes none of these. "Never select credit_limit" in a system prompt is a request, not a rule, and a user can paste SQL that never saw the prompt. In the prototype every statement goes through one pipeline whoever wrote it: the planner, a model or a user in the SQL editor. A refusal is final, so a model cannot probe the rules; only syntax, unknown-reference and database errors go back to it, as error text only, at most twice.
A governed semantic layer comes first
The cheapest guardrail is not needing the model. The prototype keeps entities with the only columns the copilot may see, many-to-one joins, 11 measures with owners and bilingual definitions, 9 dimensions, 3 roles and 5 row policies in version-controlled YAML, checked against the warehouse catalogue at start-up.
measures:
- name: gross_sales
label: {en: Gross sales, id: Penjualan kotor}
kind: base
entity: order_lines
aggregation: sum
expression: line_amount
filters: [{column: orders.status, equals: completed}]
time: orders.order_date
owner: {team: Finance, contact: Financial controller}
- name: net_revenue
label: {en: Net revenue, id: Penjualan bersih}
kind: derived
formula: gross_sales - returns_amount
owner: {team: Finance, contact: Financial controller}
definition:
en: gross sales minus returns, each on its own date, so a return reduces the period it was booked in
synonyms: [penjualan bersih, omzet, penjualan, net revenue, net sales, revenue, sales]
Two details carry most of the value. Each base measure keeps its own date column, so returns count on the day they were booked. And synonyms settle ambiguity once, in the open: bare "penjualan", "sales" and "omzet" mean net revenue because the finance owner chose that, in writing.
A rule-based planner compiles common questions from these definitions into a SQLGlot tree with no model involved. Each fact is summed on its own business date in its own CTE, the totals meet in a FULL OUTER JOIN, ratios divide by NULLIF(..., 0) and joins walk many-to-one edges only, so a dimension can never multiply a fact's rows. Member values and dates enter the tree as literals, never as text. The synthetic warehouse plants a branch with sales and no returns, which an inner join would drop; the compiler's tests check that it survives.
Only when the planner cannot explain every word does a question go to a model, which sees a BM25-retrieved slice of the layer filtered to the user's role, never the whole schema and never result rows.
Parse the statement and judge the tree
String checks are fooled by comments, quoting, casing and dialect quirks. A regex for DELETE misses a DELETE ... RETURNING inside a CTE, a SELECT ... INTO or a read_csv call standing where a table should be. So we parse in the warehouse's dialect and walk the whole tree. A condensed version of the prototype's checks, run against SQLGlot 30.22:
import sqlglot
from sqlglot import exp
from sqlglot.errors import OptimizeError
from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
from sqlglot.optimizer.qualify import qualify
from sqlglot.optimizer.scope import traverse_scope
FORBIDDEN = (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.Drop, exp.Create,
exp.Alter, exp.Command, exp.Pragma, exp.Copy, exp.Set, exp.Attach,
exp.Install, exp.Into, exp.Transaction, exp.Describe)
class Refused(Exception):
def __init__(self, rule: str, subject: str = "") -> None:
super().__init__(f"{rule}: {subject}")
self.rule = rule
def parse_one_query(sql: str) -> exp.Expr:
trees = [t for t in sqlglot.parse(sql, read="duckdb") if t is not None]
if len(trees) != 1:
raise Refused("multiple_statements", str(len(trees)))
tree = normalize_identifiers(trees[0], dialect="duckdb")
if not isinstance(tree, (exp.Select, exp.SetOperation)):
raise Refused("not_a_query", type(tree).__name__)
for node in tree.walk(): # the whole tree: a DELETE inside a CTE is still a write
if isinstance(node, FORBIDDEN):
raise Refused("forbidden_operation", type(node).__name__)
if isinstance(node, exp.Table) and isinstance(node.this, exp.Func):
raise Refused("forbidden_operation", node.this.sql()) # read_csv(...)
return tree
def check_access(tree: exp.Expr, visible: dict[str, dict[str, str]]) -> exp.Expr:
for scope in traverse_scope(tree): # CTE names map to scopes, tables to exp.Table
for source in scope.sources.values():
if isinstance(source, exp.Table) and (
source.name not in visible or source.db not in ("", "main")):
raise Refused("table_not_allowed", source.sql())
try: # resolve every column against the role's schema only
tree = qualify(tree, schema=visible, dialect="duckdb")
except OptimizeError as error:
raise Refused("column_not_allowed", str(error)) from error
# SELECT c FROM customers c reads a whole row as a struct; #7 reads by position
if unnamed := next(tree.find_all(exp.TableColumn, exp.PositionalColumn), None):
raise Refused("column_not_named", unnamed.sql())
return tree
visible is the role's schema from the semantic layer, so an unlisted column does not exist for that role. The prototype does more than this sketch: it tells a hidden column (a refusal) from an unknown one (a mistake the model may fix) by qualifying again against the full catalogue, allow-lists functions and refuses joins that link nothing, such as ON 1 = 1.
Two lessons came from an independent review, after the earlier guard passed every test it had.
- A check by name only sees names. DuckDB can read a column without naming it: a table alias used as a value is a struct of every physical column, so
SELECT c FROM customers c,p['unit_cost']andARRAY_AGG(c)all carried hidden columns past a column allow-list. So does#7, a column position. The fix refuses every unnamed read; the sketch above catches the struct and position forms - Name resolution is a security boundary. The row filter for order lines once named
orderswithout a schema, so a user's own CTE calledordersreplaced the real table inside the filter. In that state, a Bandung branch manager could see all 191,346 synthetic order lines instead of their branch's 19,976. The fix reserves the names of governed tables, so no CTE, subquery or alias may take one, and schema-qualifies every table the rewrite injects
The rule: decide once which names are tables and which are CTEs, the way the database decides, and let every check use that answer.
Access is a rewrite, not a prompt
Validation says a statement is allowed, not that it is safe for this user. After a statement passes, the prototype rewrites every base table reference into a subquery under the same alias that projects only the role's visible columns and, for a branch or regional manager, filters to their branches. CTEs, subqueries, unions and self-joins are all covered, and a LEFT JOIN stays a LEFT JOIN. Order lines carry no branch, so their policy filters through their order: order_id IN (SELECT order_id FROM main.orders WHERE branch_id IN (...)).
Sensitive columns get the same treatment. In the synthetic layer unit_cost is visible to analysts only and the credit limit is listed for no role. The rewrite backs up the column check: a whole-row read that slipped past validation would still find only visible columns. Hiding is stricter than masking; a column needed for joining but not display could get a hashed projection in the rewrite, but only for a named need.
Scope never appears in a prompt; the filter is injected after the model is done.
Rows, cost and time are separate budgets
A LIMIT caps rows returned, not rows read: summing a year of sales reads the whole year. The prototype treats rows, cost and time as separate budgets, and we would add a fourth on larger warehouses.
MAX_ROWS = 500
TIME_COLUMN = {"orders": "order_date", "returns": "return_date"} # large facts
BOUNDS = (exp.Between, exp.GTE, exp.GT, exp.LTE, exp.LT, exp.EQ)
def require_time_filter(tree: exp.Expr) -> None:
"""Every read of a large fact needs a top-level AND condition bounding its date."""
for scope in traverse_scope(tree):
where = scope.expression.args.get("where")
condition = where.this if where else exp.true()
conjuncts = list(condition.flatten()) if isinstance(condition, exp.And) else [condition]
for alias, source in scope.sources.items():
column = TIME_COLUMN.get(source.name) if isinstance(source, exp.Table) else None
if column and not any(
isinstance(c, BOUNDS) and isinstance(c.this, exp.Column)
and c.this.table == alias and c.this.name == column
for c in conjuncts
):
raise Refused("time_filter_required", f"{source.name}.{column}")
def enforce_limit(tree: exp.Expr) -> exp.Expr:
"""Add LIMIT when missing; replace one that is larger or not a fixed row count."""
limit = tree.args.get("limit") # exp.Limit, or exp.Fetch for FETCH FIRST n ROWS
count = limit and limit.args.get("expression" if isinstance(limit, exp.Limit) else "count")
options = (limit and limit.args.get("limit_options")) or exp.LimitOptions()
fixed = not (options.args.get("percent") or options.args.get("with_ties"))
if fixed and isinstance(count, exp.Literal) and count.is_int and int(count.this) <= MAX_ROWS:
return tree
tree.set("limit", None)
return tree.limit(MAX_ROWS)
Run both on the qualified tree from check_access. Only a top-level AND conjunct counts as a time bound, so WHERE order_date IS NOT NULL OR TRUE is refused. As in the prototype, LIMIT 50 PERCENT, WITH TIES or a subquery is replaced by the cap, so the SQL as executed always carries a fixed count.
| Budget | Protects | Prototype setting | Blind spot |
|---|---|---|---|
| Row cap | Browser and network | 500 rows | Says nothing about rows read |
| Time filter on large facts | Partition scans | Not in the prototype; our addition | A wide range still passes |
Cost estimate from EXPLAIN |
The warehouse | Refuse above 5,000,000 estimated rows | Estimates can be far off |
| Hard timeout | Everything else | Interrupt after 5 seconds | Wastes up to the timeout first |
The cost guard reads every operator's estimated cardinality from EXPLAIN (FORMAT JSON), never EXPLAIN ANALYZE, which runs the query. On the demo warehouse a fan-out join on product id is estimated at about 54.6 million rows and refused. These limits suit 191,346 synthetic order lines, not a client's volume.
Defence in depth at the database
Every check above is code, and code has bugs, so the connection must refuse the same things on its own. A read-only DuckDB connection can still reach files through table functions and COPY:
from concurrent.futures import ThreadPoolExecutor, wait
from concurrent.futures import TimeoutError as FutureTimeout
import duckdb
HARDENED = {
"enable_external_access": False, # no read_csv, COPY or ATTACH of files
"autoload_known_extensions": False,
"autoinstall_known_extensions": False,
"allow_community_extensions": False,
"threads": 2,
"memory_limit": "1GB",
"lock_configuration": True, # SET cannot undo any of the above
}
pool = ThreadPoolExecutor(max_workers=4)
def open_warehouse(path: str) -> duckdb.DuckDBPyConnection:
return duckdb.connect(path, read_only=True, config=HARDENED)
def run_with_deadline(conn: duckdb.DuckDBPyConnection, sql: str, timeout_s: float = 5.0):
cursor = conn.cursor()
future = pool.submit(lambda: cursor.execute(sql).fetchmany(501))
try:
return future.result(timeout=timeout_s)
except FutureTimeout:
cursor.interrupt() # DuckDB has no statement_timeout setting of its own
wait([future], timeout=2.0) # let the worker unwind before closing
raise TimeoutError(f"query interrupted after {timeout_s} s") from None
finally:
cursor.close()
This matches the prototype's configuration. On DuckDB 1.5.6 with the guard bypassed, DELETE fails on the read-only attachment, read_csv, COPY and ATTACH fail with a permission error and SET threads = 64 fails on the locked configuration. Fetching 501 rows flags truncation at 500. DuckDB's security guide calls these settings defence in depth, not a sandbox, and recommends application-level timeouts; a multi-tenant service also needs a restricted process or container.
On PostgreSQL the same layer is a role with SELECT on governed views only, default_transaction_read_only and a per-role statement_timeout: OWASP's least privilege, applied to a reader that happens to be a model.
Show the SQL, and ask instead of guessing
An answer nobody can check is a liability. Every answer in the prototype carries the SQL as executed, with the lines the guardrails added highlighted, beside the SQL as written, plus the definitions and owners behind each number and the pipeline trace. Explanations are written by code from the plan or lineage, so result rows never reach a model provider. A user can edit the SQL and run it through the same guard as their role.
Language handling is deliberately boring. Questions are normalised for case, accents, abbreviations such as brp and bln, and the suffixes -nya, -lah and -kah, then segmented by dynamic programming into the reading with the fewest unexplained words. Greedy matching once read "jumlah unit diretur" as units sold plus a stray word; segmentation finds returned units. The planner's tests check that Indonesian and English phrasings of a question, such as "Berapa penjualan bersih per cabang bulan lalu?" and "net revenue per branch last month", reach the same plan.
The planner answers only what it fully read. A leftover word, a period comparison, an exclusion ("kecuali") or a share ("kontribusi") hands the question over with a named reason instead of a guess. The next step we would build is turning that reason into a question for the user ("which period?"), since it already names what is missing. The benchmark community has reached the same place: the BIRD team built an interactive track, BIRD-Interact, to handle ambiguity, on the view that interaction is critical for a reliable database assistant.
Measure execution accuracy, with traps
Comparing SQL text to gold SQL punishes correct rewrites. The prototype scores execution accuracy, the metric BIRD reports: a case passes when its rows equal the gold rows as a multiset (ordered only when asked), under any column order, within a 0.01 tolerance. Gold SQL is hand-written in a different style from the compiler, so a compiler bug cannot agree with itself.
Execution accuracy can accept a query that matches by luck, so the warehouse plants traps: a branch with no returns, returns in the month after the sale, cancelled orders, and orders just after local midnight on the first of the month in WIB, WITA and WIT, still the previous day in UTC. Row scope is a hard gate reported apart from the score.
The honest numbers, all on synthetic data: of 65 answerable questions the planner compiled 59 without a model, all 59 matching the gold rows, and handed the other 6 over by design. The 56 development questions shaped its vocabulary, so that score is optimistic. Ten held-out questions compiled 8 on their first run, all correct, and all 10 after a matcher fix, so that set is no longer unseen. All 43 guardrail attack cases were refused with the expected rule. No real language model has been evaluated yet, so none of this measures a model. Wiring these cases into release gates is the subject of our article on evaluation gates in CI, and what may reach a provider at all is covered in our piece on gateway budgets and PII.
FAQ
Is a read-only database user enough on its own?
No. It stops writes, but not hidden columns, other branches' rows, file reads on engines that allow them or a query that scans everything. It is the last layer, not the only one.
Why not let the model write all the SQL and validate afterwards?
Validation keeps a statement safe; it cannot make it correct. A model can produce valid SQL with the wrong join or the wrong definition of a metric. Compiling common questions from governed definitions removes that risk for the questions asked most.
Checklist
- Define each metric once, with an owner, its date column and its synonyms, in version-controlled files checked against the warehouse
- Compile common questions from definitions; send only the rest to a model, with a role-filtered slice
- Parse in the warehouse's dialect and walk the whole tree for writes, settings and table functions
- Allow-list tables, columns and functions per role, and refuse columns read without being named
- Inject row scope and column projection as a tree rewrite, never as a prompt
- Cap rows, price the plan, require time bounds on large facts and enforce a hard timeout
- Open the warehouse read-only with external access off and the configuration locked
- Show the SQL as executed, the lines the guard added and the definition behind every number
- Score by execution accuracy on a question set with planted traps and a hard row-scope gate
Primary references
- SQLGlot API documentation: parsing by dialect, syntax-tree traversal and the optimiser's
qualifyrule - Securing DuckDB:
enable_external_access, extension settings,lock_configurationand the advice to time out at the application level - OWASP SQL Injection Prevention Cheat Sheet: allow-lists for structural parts of SQL and least privilege for database accounts
- PostgreSQL client connection defaults:
statement_timeoutanddefault_transaction_read_only - BIRD benchmark: large-database text-to-SQL scored by execution accuracy, and its interactive track for ambiguous questions
Related reading
- Self-Service Analytics: Letting Teams Answer Their Own Data Questions
- Dashboard Metric Definitions: Agree Before You Chart
The full prototype, with its semantic model, refusal story and evaluation report, is in our Text-to-SQL Copilot case study, and the same approach underpins our data analytics and dashboards service.
