AskDB: AI-written SQL and charts, without AI seeing your data

People want to use AI to run reports on their databases. They also don't want to give AI access to their database. It's a Catch-22.
AskDB is an open-source TypeScript text-to-SQL toolkit: it turns a question into checked SQL for your app to run. The model sees your schema and the notes you write, never your data.
Today I'm announcing the release candidate for AskDB 1.0. The current build is 1.0.0-rc.3.
Here is the whole flow in 41 seconds:
Where NL-to-SQL goes wrong
NL-to-SQL is an old problem. Systems that answer English questions from a database go back to BASEBALL (1961)1 and LUNAR (1971)2. Studies of large language models such as OpenAI's Codex writing SQL go back to early 20223. So the problem is not new.
The problem now isn't generating plausible SQL. It's conveying all the business context, terms and lingo consistently, so the AI generates SQL that's correct, not just plausible. It's in what the schema doesn't say, and in what the LLM assumes or hallucinates.
For example: a model that sees
orders.total_amount integerdoesn't know the amount is stored in cents. It doesn't know that when your finance team says "sales" they mean paid orders, not every order. Those facts live in people's heads, or have to be explained to the model every time someone asks a question.
What you want is to write those nuances down once, as notes on the schema, keep them in version control where you can keep improving them, and have them reach the model the same way on every question. That's what AskDB does.
What that looks like
Here's a snippet of a schema from the repo's test fixtures. The orders table has no sales column. "Sales" is a business word, defined in the schema's Markdown. Here's part of tables/orders.md:
---
id: table:public.orders
name: orders
...
columns:
- id: table:public.orders#total_amount
aliases: [revenue, sale_amount]
description: Stored in cents. Use `total_amount / 100.0` for dollar values.
...
---
## Common query language
- "sales" usually means paid orders (`status = 'paid'`)
- "revenue" usually means `sum(total_amount)` where `status = 'paid'`
The question is "How much did we make in sales, in dollars?" This is the schema part of the prompt AskDB built for it:

The prompt as text
Database schema:
TABLE public.users -- aliases: accounts, members
-- Registered user accounts. One row per signed-up user.
- id uuid (PK NOT NULL) -- aliases: user_id
- email text (NOT NULL) (sensitive)
- created_at timestamptz (NOT NULL) -- aliases: signup_date, registered_at; When the user account was created.
-- common query language --
-- - "users" and "members" refer to this table
-- - "new users" usually means accounts created in the selected date range
-- - "active users" typically means users who placed at least one order
-- business context --
-- Each user has a unique email address used for login. The `email` column is sensitive — filter on it only when necessary and never display it in group-by reports.
TABLE public.orders -- aliases: purchases, sales, transactions
-- Customer purchase orders. One row per submitted order.
- id uuid (PK NOT NULL) -- aliases: order_id
- user_id uuid (NOT NULL)
- status text (NOT NULL) -- aliases: order_status; values: pending|paid|shipped|cancelled; Order lifecycle state. Most reporting filters on `paid`.
- total_amount integer (NOT NULL) -- aliases: revenue, sale_amount; Stored in cents. Use `total_amount / 100.0` for dollar values.
FK (user_id) -> public.users (id)
-- common query language --
-- - "sales" usually means paid orders (`status = 'paid'`)
-- - "revenue" usually means `sum(total_amount)` where `status = 'paid'`
-- - "new orders" usually means orders created in the selected date range
-- business context --
-- Orders move through `pending → paid → shipped` and may end in `cancelled`. The `total_amount` column is stored in cents.
-- concepts --
-- Customer; synonyms: user, client, buyer, account holder; links: public.users; A person who has signed up and placed at least one order.
-- Revenue; synonyms: sales, gross sales, top line; links: public.orders.total_amount; Sum of `orders.total_amount` where `status = 'paid'`, expressed in cents.
Question: How much did we make in sales, in dollars?
It isn't DDL or SQL. It's a condensed format of the tables and the notes written about them.
Everything the model needs is in that text: "sales" means paid, and amounts are in cents. Concepts that span more than one table, like the Revenue concept at the bottom, come from a second file, concepts.md.
The call is one function in @askdb/core:
import { ask, loadSchema } from "@askdb/core";
import { openai } from "@ai-sdk/openai";
const result = await ask({
question: "How much did we make in sales, in dollars?",
schema: loadSchema("./schema"), // the schema artifact directory
dialect: "postgres",
model: openai("gpt-4o-mini"), // any Vercel AI SDK model object
});
With @askdb/core 1.0.0-rc.3 and OpenAI's gpt-4o-mini, it returned this (trimmed):
{
"sql": "SELECT SUM(total_amount) / 100.0 AS sales_in_dollars\nFROM public.orders\nWHERE status = 'paid';",
"verdict": {
"outcome": "allow",
"findings": []
},
"sensitiveGuardrail": {
"passed": true,
"references": []
},
"unboundSql": "SELECT SUM(total_amount) / 100.0 AS sales_in_dollars\nFROM public.orders\nWHERE status = $1;",
"params": ["paid"]
}
The model divided by 100 and filtered on paid because the notes told it to. unboundSql and params are the same query with its values pulled out, ready for your driver to bind.

The verdict comes from AskDB's checks, which run on every SQL string before your code sees it.
The schema artifact
AskDB keeps what it knows about your database in one directory, the schema artifact. It has two layers.

The physical layer (schema.json): the tables, columns, types, keys and relationships. askdb introspect writes it by reading the database catalogs (information_schema, pg_catalog, sys.*, sqlite_master). Introspection collects no sample values.
The enrichment layer (the Markdown files): one file per table or concept you choose to describe, written by people. You can write those files by hand or in Studio (more on that below). Because it's all files, your data team reviews a change to "what sales means" in a pull request, and you can see line by line what the model will receive.
The physical layer is enough for SQL that runs. The enrichment layer is what makes it right for the business. Without the two notes above, the model could just as well have summed every order and reported cents as dollars: valid SQL, wrong answer.
When you ask a question, AskDB folds the two layers into the compact text you saw above and sends it to the model with your question. It holds back the notes on any sensitive table or column, and the example questions, which are there for retrieval.
A large schema is too big to send whole on every question. Past about 22 tables, or when the rendered schema routinely passes 8K tokens, turn on retrieval with @askdb/rag. It indexes the same artifact in a vector store and puts only the relevant slice into each prompt. @askdb/rag stays on 0.x at 1.0, so its API may still move.
ask() takes no database connection, so it never sees your rows or query results and can't send them. Introspection connects only at build time to read the catalogs. It sends nothing to a model. A value reaches the prompt only as text you wrote into the artifact, such as an enum list, or text the user typed in the question. Two caveats. Anything you write in the Markdown goes to the model verbatim. A label you pass in tenantScope.context, such as a customer's name, goes into the prompt as written too. And as you'd expect, retrieval adds a second provider: your embedding model receives every schema chunk when you build the index, and the question on each call.
Studio: enrich and test before you ship
You don't have to write the Markdown by hand. npx askdb studio opens AskDB Studio, a local web app on your machine that reads and writes the schema artifact directly. It's where I'd start: describe a table, add its aliases and common query language, then ask a question in the Playground and read the SQL and its check results. If the SQL isn't what you expected, tighten the notes and ask again, without leaving the tab. That loop (enrich, ask, re-enrich) is how you get reliable SQL for the words your team uses, before any of it touches your application.

Studio can also draft descriptions and aliases with your model for you to confirm. For a draft, it sends the model the table's column definitions and the names of up to four linked tables. Running the Playground's SQL against your database is off by default; turning it on means giving Studio a read-only role. Studio is still on 0.x at 1.0, so its UI may change. The Studio tour walks through every view.
When retrieval leaves out a table
Retrieval puts a table in the prompt only when one of the chunks it returns points to that table. Writing this blog, I hit the failure that follows from that.
On a made-up 63-table SaaS schema, I asked "What's our monthly recurring revenue from active subscriptions?" Only subscriptions was described, with the rule for an active subscription. Retrieval returned chunks from subscriptions, usage_records and subscription_events. It didn't return plans, where the prices live. The model never saw a price, so it counted the active subscriptions and multiplied by 10. The answer was $20. The right answer was $38. The SQL was a valid read-only query, so every check passed.

The fix was two files:
tables/plans.mdgave the table a description, aliases such as "subscription plans" and a business-context line saying MRR is built fromplans.monthly_price.concepts.mdgot a monthly recurring revenue concept that linkssubscriptionsandplans; when retrieval returns a concept, AskDB puts every table it links into the prompt. After re-indexing, the concept and theplansnotes ranked first, and three runs out of three joinedplansand returned 38.
The lesson is the same one the checks teach: they test the query's shape, not its numbers. Test the questions your users ask. The tutorial Find the right tables in a large schema walks through this case with the real output.
Your app runs the SQL
The library, the CLI and the HTTP API return SQL and never execute it. Your application runs it under its own database role. The one exception is Studio's Playground Execute button, a local development tool that's off by default.

I made this choice because the database role you already trust to run queries should be what bounds generated SQL. AskDB doesn't host inference either: you bring the model and the key, and it doesn't proxy, log or cache the requests. Use one of @askdb/ai's built-in providers (OpenAI, Anthropic, Google, Azure, Vercel AI Gateway) or pass any Vercel AI SDK model object to ask(). @askdb/ai uses the Vercel AI SDK under the hood, so the choice is between passing in the model your app already uses and letting @askdb/ai build one from your AskDB config.
The three checks
AskDB runs three checks on the returned SQL before passing it back to you:
- The read-only check, on for every built-in dialect. It makes sure no data-changing statement (
UPDATE,INSERT,DELETEand the like) comes back. - The tenant check, on when the schema has a
tenant-policy.mdand the caller's scope isn't global. - The sensitive check, on when something is marked sensitive.
To show refusals, I stubbed the model to return SQL I wrote. The errors below are AskDB's real output on rc.3.
DELETE FROM orders WHERE status = 'cancelled';:
{
"name": "SqlValidationError",
"message": "SQL must start with SELECT or WITH (got 'delete').",
"verdict": {
"outcome": "deny",
"findings": [
{
"check": "read-only",
"form": "sql",
"rule": "SQL_NOT_SELECT_OR_WITH",
"message": "SQL must start with SELECT or WITH (got 'delete').",
"hint": "Regenerate as a read-only SELECT (optionally with WITH). INSERT/UPDATE/DELETE and procedural calls are blocked in dev guardrails."
}
]
}
}
SELECT COUNT(*) FROM orders; DROP TABLE users; is refused with rule SQL_MULTI_STATEMENT.
With a tenant policy that scopes orders by agency_id, SELECT COUNT(*) FROM orders; throws TenantGuardrailError with rule MISSING_TENANT_PREDICATE: "Tenant-scoped table 'orders' is missing required tenant predicate. Expected one of: agency_id, …" Adding OR 1 = 1 next to a correct predicate gets the same refusal. When the predicate is there, AskDB binds the tenant ID as a driver parameter ($1) and returns it in tenantParams for your driver.
SELECT id, email FROM users; comes back with "outcome": "warn" and a SENSITIVE_COLUMN_REFERENCED finding. In strict mode it throws SensitiveReferenceError.
The database is the boundary
AskDB doesn't parse SQL. The checks are token- and pattern-based. They catch the common ways a model gets it wrong, and unusual or adversarial SQL can get past them. The database role your application uses is the boundary. The CLI's own --explain output says so:
"remediationNote": "Heuristic, lexer-based defense-in-depth checks only—not a SQL parser and not a security boundary. Execute generated SQL under a read-only database role, and review it before trusted execution."
Run generated SQL under a read-only, least-privilege role. Enforce tenant isolation in the database, for example with Postgres row-level security. Set statement timeouts and cap the rows you read. AskDB never adds a tenant filter, a row limit or a timeout to the SQL.

An experimental chart planner
@askdb/client/charts asks your model to plan a chart from the question, the query with its literal values masked, and the result's column names, column kinds (date, currency, category, measure…), row count and truncated flag. The model never sees the rows. If you keep sensitive columns out of prompts, pass that setting and the schema artifact to planChart(), and the model gets no SQL or column name that touches a sensitive column. It returns a chart spec, and your app draws the chart from its own data. A minor release of @askdb/client may change it; it's outside the 1.0 API freeze. The tutorial Chart your first answer adds a chart to the Quickstart's project.
Known limits
- Little system-schema filtering. With a tenant policy, rc.3's tenant check refuses Postgres's planner-statistics relations (
pg_statsand its relatives). Other queries againstpg_catalog,information_schemaor SQL Server'ssysaren't rejected. - A call to one of your own functions that writes passes the checks, and so does an expensive join. - No protection from prompt injection. Anyone who can write the question or the schema Markdown can influence the SQL.
- No protection from untrusted schema files. Whoever can write the schema directory changes what AskDB loads and what the model sees. Load schema files only from sources you trust.
- MySQL's
ANSI_QUOTESmode isn't supported. MySQL and MariaDB have no row-level security policies, and SQLite has no users or grants, so use a database per tenant there.
The 1.0 support claim covers five engine families: PostgreSQL, MySQL, MariaDB, SQLite and SQL Server. CockroachDB has a built-in dialect that reuses the Postgres spec, but it's outside the 1.0 claim: the end-to-end tests don't cover it.
AskDB is for engineers who embed it in a Node app, a CLI workflow or an HTTP service and own the schema, the keys and execution. Analysts use it through an app someone built on it. It doesn't guarantee business correctness: a person still reviews critical queries.
At 1.0, AskDB stops at the SQL behind a report. Reports and a first-party MCP server are planned for after 1.0. Until then, agents use the CLI and the HTTP API.
Try it
You need Node.js 22.23.4 or newer.
npm install --save-dev askdb
npx askdb init --yes --database sqlite --sqlite-file ./shop.db
The RC is on npm's latest tag, so a plain install gets it. If you're coming from a 0.x version, update the range in your package.json: a 0.x range won't match 1.0.0-rc.3.
The Quickstart goes from install to running the returned SQL on a small SQLite shop database. The code is at github.com/Ygilany/AskDB, Apache-2.0.
This is a release candidate, and I need people to try it before 1.0.0. Point it at your own schema, ask it the questions your team asks, and tell me what breaks. Issues, ideas and pull requests are all welcome; CONTRIBUTING.md has the setup.
- Something broke, the Quickstart tripped you up, or a docs page doesn't match the code: open an issue.
- A business term you couldn't express in the schema artifact: start a thread in Discussions → Ideas.
- SQL that gets past a check it should fail: report it privately at github.com/Ygilany/AskDB/security/advisories/new (see the security policy); when the policy treats it as a vulnerability, I publish an advisory for it.
Notes
-
Bert F. Green, Alice K. Wolf, Carol Chomsky and Kenneth Laughery, "Baseball: an automatic question-answerer," Western Joint IRE-AIEE-ACM Computer Conference, 1961. ↩︎
-
William A. Woods, "Progress in natural language understanding: an application to lunar geology," AFIPS National Computer Conference, 1973. LUNAR was first shown at the Second Lunar Science Conference in 1971. ↩︎
-
Nitarshan Rajkumar, Raymond Li and Dzmitry Bahdanau, "Evaluating the Text-to-SQL Capabilities of Large Language Models," arXiv, March 2022. ↩︎

AskDB is an open-source TypeScript text-to-SQL toolkit: it turns a question into checked SQL for your app to run. The model sees your schema and the notes you write, never your data.