ONE SMALL SERVICE, TWO PRODUCTS • READ-ONLY BY DESIGN

Ask in Plain English. Get Real Numbers.

For about a year, I thought natural-language-to-SQL was reckless — letting an AI near a live database, and trusting numbers it made up. This microservice is how I changed my mind without lowering the guardrails: the AI only translates a question into one read-only query, two safety checks run before the database sees it, the database does all the math, and the answer comes back as a live chart with the SQL shown. It was built for 3PM Daily's 45 tables of market data, and it now also powers the chat on this portfolio.

Problem

Chatbots that “analyze data” fail two ways: they guess numbers instead of querying them, or they dump 50 rows of raw table text into the chat. Users don't trust the first and can't read the second.

Solution

Split the pipe. The AI translates a question into one read-only query and sees only a 25-row sample to write a two-sentence summary. The full result bypasses the AI entirely and arrives as an interactive chart, table, and SQL inspector.

Outcome

Non-technical users interrogate 45 tables in plain English; every number is computed by the database; every query can be inspected. In testing, every attempt to change data was blocked before it reached the database.

01 / DISCOVERY — THE SKEPTIC'S STARTING POINT

I Dismissed This Idea for a Year. The Status Quo Is Why.

Conversational AI over real data usually fails in one of two ways. The guesswork bot: the model approximates numbers from its training instead of querying the live data, and sounds certain doing it. Or the text-dump: the model runs a query and pastes 50 rows of raw table text into the chat, burying the conversation under data nobody can read.

Watching people use interfaces like that, the friction wasn't subtle. Users don't want a wall of tabular text, and they don't trust an AI's arithmetic. If a tool claims to analyze real data, they demand proof they can check: What exact query was run? How long did it take? Can I inspect the numbers, sort them, export them?

My own first answer was to avoid NL-to-SQL entirely: hard-coded, fixed APIs — one for a single stock quote, one for a 10-year valuation, one for moving averages — with the AI acting purely as a router between them. Safe, but every new question needed a new endpoint. The pivot wasn't removing the gate. It was moving where the gate lives.

The Epiphany

“Math must do math, databases must store state, and the AI must only translate intent.”

Failure Mode 1
Arithmetic Hallucination

Asked for rankings or margins, the model synthesizes plausible numbers from its training instead of reading the live data — delivered with total confidence and no way to check them.

Failure Mode 2
Security & Corruption Risk

A poorly guarded SQL generator — or a cleverly jailbroken prompt — risks accidental writes, locked tables, and corrupted schemas. The database is the business; you don't hand a language model the keys.

Failure Mode 3
Context Window Poisoning

The naive fix — stream the raw rows back as text — burns 10,000+ tokens per query and leaves those rows sitting in the conversation's memory, throttling every turn that follows. A correct query with an unusable delivery is still a failed product.

What Users Actually Asked For

Verifiable provenance. The exact query, the execution time, and the numbers in a form they can inspect, sort, and export to CSV. Trust doesn't come from the AI sounding sure. It comes from being able to check its work.

02 / RESEARCH — TWO READERS, OPPOSITE NEEDS

One Answer, Three Audiences

I designed against two modeled archetypes (design models, not interviewed users — the same way I pressure-test most of my product decisions before real usage data exists).

The core finding: an AI's answer can't just be text. The same result has to arrive as a chart for the person who needs the headline, a searchable table for the person who needs the details, and the raw query plus timing for the person who needs to audit it. One response, three surfaces.

Archetype 1 — The Executive
Elena Vance, VP of Commercial Strategy

Needs ad-hoc answers on the fly during executive reviews — market-cap comparisons, revenue rankings, sector trends, “Top 5 market caps vs. the whole market” — with zero SQL familiarity. Her contract: dynamic part-to-whole charts with honest remainder buckets, no raw code jargon, instant visual hierarchy, and a one-click CSV export for leadership.

Archetype 2 — The Auditor
David Kross, Principal Infrastructure Auditor

Distrusts black-box AI systems on principle. His contract: strict database isolation and immutable production schemas; a transparent viewer showing the exact SQL that ran; real-time execution latency in milliseconds; zero write privileges, with every mutation attempt intercepted before execution. For him, the audit trail isn't a detail — it's the product.

The Design Contract

Every answer must serve both at once: a chart Elena can read in five seconds, a table an analyst can search and sort, and an inspector David can use to see exactly what ran and how long it took — without any of them seeing the others' clutter.

03 / SYSTEMS — TWO PIPES, TWO LAYERS OF DEFENSE

The Thinking and the Data Never Share a Pipe

The architecture splits into a control plane and a data plane. The control plane is small and smart: the question, the drafted query, and a 25-row sample the model may look at to write a two-sentence summary. The data plane is dumb and heavy: the full result set travels directly from the database to the screen, never passing through the model.

That split solves the token problem and the trust problem with the same move. Hundreds of rows never enter the conversation, so the chat stays lean and cheap — and since the model never holds the numbers, it can't misquote them.

Defense Layer 1 — The Query Is Inspected (Application)

Every generated query is parsed with sqlglot into its syntax tree before it runs. Statement chaining — a second query smuggled in after a semicolon — is rejected, and any write operation (INSERT, UPDATE, DELETE, DROP, ALTER) is blocked at the parser, before a packet ever leaves for the database.

Defense Layer 2 — The Account Can Only Read (Database)

Queries execute as a dedicated MySQL user, nl_sql_reader, holding strictly SELECT permissions. If a mutation somehow reached the database, it would fail there instead (MySQL Error 1142). The first layer doesn't have to be perfect for the system to be safe.

The Sandbox — Saved Views Live Elsewhere

When a user saves a custom screener (POST /create-view), the AST check itself forces the new view into a physically separate schema (financebot_views). Core exchange tables stay untouched — and stay free of the lock contention a stray view could cause.

The Shape of It — Two Planes, One Read-Only Door
User question, in plain English
Control Plane → The Model
  • Semantic schema catalog (45 tables)
  • AST guardrail (sqlglot) on every query
  • 1-turn self-healing loop
  • Capped sample: top 25 rows
  • Summary stored: ~40 tokens (Firestore)
Data Plane → The Screen
  • Out-of-band JSON transport
  • Charts built by viz_service.py (<2ms)
  • All rows bypass the model (0 tokens)
  • Live table + CSV, rendered on the page
MySQL 8.4 — nl_sql_reader: SELECT ONLY
financebot (core 45 tables, immutable) • financebot_views (sandbox for saved views)

Everything the diagrams tried to say, in the page's own language: the model holds the question and a sample; the screen holds the data; and the only door between them opens one way — read.

04 / CRAFT — THE ENGINE, THE REPAIR LOOP, THE CHART

A Standalone Service, Not a Hack in a Component

The engine (nl_sql_engine, a FastAPI microservice) was built standalone, with its own test playground, and then plugged into two products. It generates SQL with Gemini 2.5 Flash at temperature 0.0 — the same question should produce the same query — guided by a schema catalog of all 45 tables, proven example patterns, and market-calendar rules, like using LAG() window functions over trading sessions instead of naive calendar-day subtraction.

And when a query fails, it mostly fixes itself — once.

Self-Healing — One Turn, Then It Stops

The router catches MySQL execution errors in real time and re-prompts the model with the failing SQL and the exact error message. The repaired query typically executes in under 350ms. One repair attempt is the limit — if it fails again, the user hears about it instead of watching the system loop.

Charts Without the Model

A small Python service (viz_service.py) reads the shape of the returned data and picks the chart — no model tokens spent on charting at all. Its best trick: when a question asks for part of a whole (“Top 5 market caps”), it queries the total and adds a “Rest of Tracked Universe” bucket, so the donut chart honestly adds up to 100% instead of implying the top 5 are everything.

The Component — Three Views, One Answer

Results render as a live React component (<NlSqlIntelligence />, Next.js 16 + Recharts) with three synchronized modes: the chart for Elena; a paginated, searchable table for the analyst — values formatted the way finance readers expect ($3.45T, 18.2× P/E) with text filtering across every column; and a SQL & telemetry tab for David — the executed query, row count, and timing, with CSV export.

Questions It Answers (From the Design)
  • “Top 5 market caps vs. the whole market.” → donut chart, with the “Rest of Tracked Universe” bucket
  • “Show me 6 months of prices for these 3 stocks.” → 378 rows, drawn as a multi-line chart; the model saw 25 of them
  • The briefing it wrote from that sample: “Over the last 6 months, Netflix gained +24% while Apple and Google traded in range…”
05 / TELEMETRY — MEASURED, NOT ADJECTIVED

What the Tests and the Timers Say

These numbers come from the engine's local test suite and from live runs against the real database. They're ranges and test results, not guarantees — but they're measured, which is more than most “AI analytics” can say.

Security — Mutation & Injection Stress Tests
Write attempts (DROP / UPDATE / INSERT)100% blocked at the parser, before the database
Semicolon chaining attempts100% blocked
BackstopRead-only account refuses anything that gets through
Token Economics — One Real Query, Two Ways
The query6 months of prices, 3 tickers — 378 rows
Naive: rows streamed through the model~9,500 tokens, plus ~1,200 more for a chart
Naive total per turn~10,700 tokens — and 4.5–7.0s end to end
This service: SQL generation~85 tokens
This service: total per turn~475 tokens — 95.5% fewer
Chart specificationBuilt locally in under 2ms, 0 model tokens
Latency — Where the Time Goes
Query generation + safety check~600–900ms
Database execution~12–45ms
Self-healing retry (when needed)Under 350ms
End to end, question to chart~1.2–1.8s
06 / OUTCOME — IMPACT & WHAT I LEARNED

The Black Box Is Gone

Non-technical stakeholders can now interrogate 45 tables of market data in plain English — no SQL, no data engineer in the middle, and no risk to the database. Elena gets her chart; David gets the executed SQL and the export. The same engine then dropped into this portfolio's chat, unchanged in its safety design.

The honest limit stays: a vague question can still produce a valid query that answers a slightly different question than the one you meant. That's precisely why the SQL inspector exists — the mitigation isn't a smarter promise, it's showing the work.

The Retrospective in One Line

“Dismissing NL-to-SQL as an uncontrollable hazard was a failure of boundary definition, not of model capability.”

Production Client 01 — This Portfolio
The Chat, Ungated

The same engine hydrates live result cards in this site's chat — an open demo where recruiters and architects can watch the tool-calling and the guardrails work, no account needed.

Production Client 02 — 3PM Daily
The Market Terminal

In the trading product, the engine turns complex cross-table questions into validated data cards — the same safety design, pointed at live market data instead of a portfolio.

Two Lessons Worth More Than the Feature

1. Don't over-engineer. Elsewhere in my work I reach for graph databases — but a 45-table schema compiles down to roughly 3,000 tokens of catalog. Feeding that catalog straight to the model means it sees every table, with no graph database to sync, no extra latency, and no retrieval layer to debug. The boring solution was the right one.

2. Keep the control plane clean. Let large data payloads bleed into a chat's history and you poison every later turn — the model wades through old rows instead of thinking about the new question. The out-of-band data plane isn't an optimization; for multi-turn chat, it's the thing that makes the product viable at all.

Read-Only • Checked TwiceFastAPI • MySQL • sqlglotLive in Two Products