Tutorials

AI-generated illustration of a teal stream entering a faceted gold prism, with a thin red filament leaving the far side. Demo only, not a production security boundary.
Tutorial

How I built parser and EXPLAIN guardrails for a text-to-SQL demo

A portfolio walkthrough of text-to-sql-guardrails: a deterministic offline stub that turns a question into one PostgreSQL SELECT, then a sqlglot allow-list, EXPLAIN cost and row limits, and a read-only role. How to build it, run the tests, and what the GitHub Pages demo actually shows, including the honest gaps. Demo only, not a production security boundary.

Arpan Bom10 min read
ShareXLinkedIn

This is a simulation only

This is a portfolio demo with a deterministic offline model. It is not a production security boundary, and it is not a complete PostgreSQL security control. The default model is five regex templates, not a language model. The optional OpenAI-compatible adapter is untested in CI and makes no accuracy claim. I built a path that turns a natural-language question into one PostgreSQL SELECT over a small shop demo schema, then runs that SQL through a parser allow-list, an EXPLAIN cost and row bound, and a read-only role. I did not invent query allow-listing, EXPLAIN-cost gating, or execution-accuracy evaluation.

Try the live demo

The fastest way to see it working is the static demo on GitHub Pages: https://applycoding.github.io/text-to-sql-guardrails/

The page title is "demo, deterministic offline model, not a production security boundary," and the header repeats that sentence. A line under the header says "AST checks ran in your browser; database checks ran in CI." The page is a self-hosted Pyodide site, not a live database in the browser. The same Python guard and stub model run locally in Pyodide. Row payloads are precomputed in CI and looked up after the AST check. The demo does not open a network connection to PostgreSQL from your browser, and it does not call an external LLM.

Three example buttons are on the page: top 3 products by revenue, SELECT pg_sleep(9), and an unsupported question (how many customers in atlantis). The first should return code OK and the gold revenue rows below. The second should return FUNCTION_NOT_ALLOWED. The third should return NO_TEMPLATE.

The live GitHub Pages demo of text-to-sql-guardrails, with the honesty title, the question top 3 products by revenue, and gold rows for Product 84, Product 80, and Product 76. Demo only, not a production security boundary.

Image: the live GitHub Pages demo after running top 3 products by revenue. Demo only, not a production security boundary. applycoding.com.

What the project is

text-to-sql-guardrails (repo: applycoding/text-to-sql-guardrails, commit fe8629b) turns a question into one guarded PostgreSQL SELECT over a seeded shop schema. The stack is:

Layer Role
t2sql.model.StubModel Five deterministic regex templates. Default via T2SQL_MODEL=stub.
t2sql.guard Parser allow-list on a sqlglot AST: statement type, tables, columns, functions, casts, and LIMIT.
t2sql.explain and t2sql.executor EXPLAIN (FORMAT JSON) cost and row bounds, then read-only execution as t2s_reader.
t2sql CLI (ask, check, run) JSON on stdout. check is AST only. ask runs the model, then the guard, then the executor.
site/ plus tools/build_site.py Static Pyodide demo with pinned vendor archives.

This is an original implementation, inspired by well-known methods: query allow-listing, EXPLAIN-cost gating, least-privilege database accounts, and scoring a generated query by comparing its result rows with a gold query. Those ideas, and the projects behind them, are credited in REFERENCES.md and NOTICE: the Spider and BIRD execution-accuracy idea (the datasets are not used), sqlglot's typed AST and optimizer.qualify, PostgreSQL EXPLAIN, privileges, and client settings, the OWASP SQL Injection Prevention Cheat Sheet (idea only), the general shape of a question-to-SQL-to-rows pipeline (Vanna is an idea reference only; I did not use it and did not read its code for the implementation), and Pyodide as the browser runtime. I did not copy those sources.

The seeded schema, from sql/schema.sql, is 1000 customers, 120 products, 8000 orders (all in 2025), 24000 order items (three per order), and 50 rows in staff_salaries. The allow-list and the t2s_reader grants cover customers, products, orders, and order_items only. staff_salaries is in the seed and is not granted. customers.email exists on the table and is not in ALLOWED_COLUMNS and not in the column grant.

The five stub templates, in src/t2sql/model.py, are:

  • how many customers in <city> for the eight seeded cities
  • how many orders are or were <status> for placed, shipped, delivered, and returned
  • top N products by revenue for a one or two digit N
  • revenue by category
  • orders per month in 20xx, on a strict pattern

Anything else, including a city that is not in the seed, returns NO_TEMPLATE. CI sets no API key and blocks outbound network access except Postgres, so it measures nothing about LLM accuracy.

The guard, the cost bound, and the eval

t2sql.guard.check is a pure function. It parses with sqlglot, then refuses at the first failing stage. The policy caps in t2sql.policy are MAX_SQL_LENGTH 4000, MAX_AST_NODES 400, MAX_LIMIT 100, MAX_OFFSET 1000, MAX_PLAN_COST 50000, MAX_PLAN_ROWS 1000000, STATEMENT_TIMEOUT_MS 2000, and MAX_RESULT_BYTES 1048576. Allowed roots are SELECT, UNION, INTERSECT, and EXCEPT. Missing or oversized LIMIT values are clamped to 100 when the limit stage is on. The executor then opens a read-only transaction as t2s_reader, sets statement_timeout again, runs EXPLAIN (FORMAT JSON) when dry run is on, and only then executes.

The live pipeline cases in tests/test_explain.py are bounds that the planner must meet or exceed, and CI also printed the measured values. On commit fe8629b, GitHub Actions run 42945779388 reported:

Case SQL Code Measured plan value
orders_x_items SELECT o.id FROM orders o, order_items i DRYRUN_ROWS max rows 192000000.0
orders_x_customers SELECT o.id FROM orders o, customers c DRYRUN_ROWS max rows 8000000.0
items_self_join SELECT a.order_id FROM order_items a JOIN order_items b ON a.product_id = b.product_id DRYRUN_ROWS max rows 4800002.0
orders_x_items_count SELECT count(*) FROM orders o, order_items i DRYRUN_COST total cost 2880651.01

The same run printed eval_max_cost=752.74 eval_max_rows=24000.0 for the ten executable eval questions. Those figures sit well under the policy caps of 50000 and 1000000. EXPLAIN estimates can still be wrong, and they can change with the planner version and settings.

The eval harness in tests/test_eval.py is a fixed regression check, not an LLM benchmark. It runs the stub on ten executable questions and compares the rows with both a frozen fixture and the result of a gold SQL statement run as admin. It also checks five refusals, which must return NO_TEMPLATE. One executable question is top 3 products by revenue. The gold rows, in tests/fixtures/eval_expected.json and in the Playwright e2e test, are:

  • Product 84, 6454206
  • Product 80, 6171652
  • Product 76, 5852142

The five refusal prompts are a stacked DROP TABLE attempt, a request for staff salaries, a pg_sleep attempt, the unseeded city atlantis, and top 1000 products by revenue (the stub only accepts a one or two digit N).

Build and run locally

CI pins Python 3.13.18 on ubuntu-24.04 and a digest-pinned postgres:17.11 image. Locally you need Python 3.13 and PostgreSQL 17.x:

# Python 3.13 recommended (CI pin is 3.13.18)
pip install -r requirements-dev.txt
pip install -e .
export T2SQL_DSN_ADMIN_PASSWORD=...
export T2SQL_READER_PASSWORD=ci_reader
python -m t2sql.seed
python -m t2sql ask "how many customers in Denver?"
python -m t2sql check --sql "SELECT id FROM orders"
python -m t2sql ask "top 3 products by revenue"

t2sql check never opens the database. t2sql run defaults to dry run (T2SQL_DRY_RUN is 1 unless you set it to 0), so a costly statement is refused at EXPLAIN before it executes. The CLI EXEC_TIMEOUT test (tests/test_cli.py::test_cli_run_exec_timeout) needs T2SQL_DRY_RUN=0 so the statement actually reaches the two-second timeout.

The lint job also runs ruff check, ruff format --check, mypy --strict src, python tools/check_notice.py, SPDX headers, a LICENSE sha256 comparison with the official Apache-2.0 text, action pin checks, a grep that forbids assert True, pytest.skip, and xfail in tests/, a check that T2SQL_LLM_API_KEY does not appear in the workflows, and required README sections.

Results from the tests

On commit fe8629b, GitHub Actions run 42945779388 completed every job in ci.yml. The lint job printed All checks passed! from ruff, Success: no issues found in 12 source files from mypy, and NOTICE ok (28 pip packages, 7 actions checked). The test job reported 229 passed in 13.47s (pytest 9.2.0 on Python 3.13.18). The mutants job printed killed 12/12 after each of the twelve source mutants failed its own target test in tests/test_mutant_targets.py. The site job printed site pins ok and reported 7 passed in 20.09s from e2e/test_site.py, including the title, the top-3 gold rows, the pg_sleep refusal, the NO_TEMPLATE case, corpus parity with CPython, and the pinned Pyodide and sqlglot checksums.

The committed Pyodide core archive pin in site/vendor.json is sha256 2abdcc2e35208af406e07724cffa85bc582ced97e9028383ecf5462541393f95 (Pyodide 314.0.7).

Pages deploy 42946081631 on this SHA returned HTTP 200 for the live demo, whose title is "demo, deterministic offline model, not a production security boundary."

License and references

Apache-2.0. Copyright 2026 Arpan Bom. See LICENSE and NOTICE.

NOTICE lists the pinned dependencies with licenses, including sqlglot 30.31.0 (MIT), pg8000 1.31.6 (BSD-3-Clause) and its runtime stack, pytest 9.2.0, pytest-timeout 2.4.0, ruff 0.17.4, mypy 2.4.1, pip-tools 7.6.2, playwright 1.65.0, Pyodide 314.0.7 (MPL-2.0, which includes CPython PSF-2.0 and Emscripten MIT runtime code), Chromium revision 1254 as shipped with Playwright, PostgreSQL 17.11 (PostgreSQL License), and the GitHub Actions pins in .github/workflows/. It points at REFERENCES.md for idea-only references and their licences. No third-party text-to-SQL library is vendored.

How this was verified

I ran the standard portfolio-tutorial checks against commit fe8629b418968101a59dcb8a94cf605d9c719498 on main.

  • The GitHub repo is not a fork. gh api repos/applycoding/text-to-sql-guardrails reports "fork": false.
  • main has two commits, both with author and committer Arpan Bom (applycoding@gmail.com): the planning commit e32265a, and the product commit fe8629b, which is a single squashed commit. git log --format=%B main has no Co-authored-by trailers. The only remote branch at this SHA is main.
  • A search of the tree found no third_party, vendor, or external directories, and no "ported from", "adapted from", or "copied from" markers in the authored source. Pyodide and the sqlglot wheel are fetched at site-build time and pinned in site/vendor.json. They are credited in NOTICE.
  • This is an original implementation of well-known query allow-listing, EXPLAIN-cost gating, least-privilege, and execution-accuracy methods, inspired by the projects and references credited above. I did not invent those methods, and I did not copy those sources.
  • At fe8629b, NOTICE names the direct pip, toolchain, and Actions pins with licenses, and it points at REFERENCES.md for idea-only references. The repo license is Apache-2.0. The LICENSE file is byte-identical to the official Apache-2.0 text from apache.org (sha256 cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30).
  • Commands, paths, APIs, and the numbers in this tutorial were checked against the repo at fe8629b and against the live demo. The 229 pytest passes, the ruff and mypy lines, NOTICE ok, killed 12/12, site pins ok, and the 7 Playwright passes are from GitHub Actions run 42945779388 on that commit. Pages deploy 42946081631 on this SHA returned HTTP 200 for the live demo. The same test job printed the plan values and eval caps quoted above. Both runs have actor and triggering_actor applycoding.
  • Independent checks at this SHA: the twelve source mutants in tools/mutants.py each fail their own test_m* target; tests/test_forbid_skip.py writes a skipped probe and requires pytest to exit non-zero with 1 failed; lint forbids pytest.skip and xfail in tests/, and none are present; the live Pages title matches the honesty label; and authorship as above.
  • This project is a demo with a deterministic offline model. It is not a production security boundary.

Limits

This is a portfolio demo with a deterministic offline model. It is not a production security boundary. The stub is five regex templates, not a language model, and CI measures nothing about LLM accuracy. The optional OpenAI-compatible adapter (T2SQL_MODEL=openai-compatible) is untested in CI and makes no accuracy claim. The policy is a deliberately small SQL subset for one demo schema. EXPLAIN estimates can be wrong and can vary by version and settings. Role defaults are reinforced per transaction in the executor; catalog reads are blocked in the AST, not by grants. The browser demo runs AST checks only; row payloads are precomputed in CI.

tools/check_notice.py checks locked pip versions and action SHAs against NOTICE. It does not validate GitHub Action version tags. The built Pages tree includes a vendored pyodide/python_cli_entry.mjs file that contains an em dash that is not ours; it comes from the pinned Pyodide 314.0.7 archive. An xfail-marked test could still report FAILED with exit 0. Lint forbids xfail, and none exist in tests/. The CLI EXEC_TIMEOUT test needs T2SQL_DRY_RUN=0.