AskDB 1.0.0-rc.3: context for NL-to-SQL, without giving the model your rows

AskDB 1.0 release candidate. The question "How much did we make in sales, in dollars?" and the SQL AskDB returned for it.

People want to use AI to run reports on their databases. Giving an AI access to the data is where it stops: some teams don't trust it, and some won't allow it at all.

AskDB is an open-source TypeScript toolkit for that situation. It uses your LLM to write SQL from a description of your schema, checks the SQL, and hands it back to your application to review and run. The model sees the schema and the question. It never sees your rows.

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) and LUNAR (1971). Studies of large language models such as OpenAI's Codex writing SQL began in early 2022. Today, pasting a few CREATE TABLE statements into a chat window gets you plausible SQL.

It goes wrong on what the schema doesn't say. A model that sees orders.total_amount integer doesn't know the amount is stored in cents. It doesn't know that when your finance team says "sales" they mean paid orders and nothing else. Those facts live in people's heads, or in a prompt someone wrote for one project and has to write again for the next.

So the context has to be written down once and reach the model the same way on every question. AskDB keeps it in files next to your code and puts the right parts into each prompt.

What that looks like

Here's 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#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, exactly as sent:

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?

Everything the model needs is in that text: "sales" means paid, and amounts are in cents. The Revenue concept at the bottom comes from a second file, concepts.md, and the foreign key from orders to users comes from the database. The email column carries a (sensitive) tag, which the sensitive check uses later.

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",
  parameterize: false, // skip the extra parameterized copy of the SQL; this example doesn't use it
  model: openai("gpt-4o-mini"), // any Vercel AI SDK model object
});

With @askdb/core 1.0.0-rc.1 and OpenAI's gpt-4o-mini, it resolved to this:

{
  "sql": "SELECT SUM(\"orders\".\"total_amount\") / 100.0 AS total_sales\nFROM \"public\".\"orders\"\nWHERE \"orders\".\"status\" = 'paid';",
  "verdict": {
    "outcome": "allow",
    "findings": []
  },
  "sensitiveGuardrail": {
    "passed": true,
    "references": []
  },
  "usage": {
    "promptTokens": 687,
    "completionTokens": 38,
    "totalTokens": 725
  }
}

The model divided by 100 and filtered on paid because the notes told it to.

Two notes in the schema and the SQL they produced: the note "Stored in cents. Use / 100.0" points to the / 100.0 in the SELECT, and "sales usually means paid orders" points to WHERE status = 'paid'.

The verdict comes from AskDB's checks, which run on every SQL string before your code sees it.

The schema artifact

AskDB calls this directory the schema artifact. It has two layers.

schema.json is the physical layer: 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 Markdown is the enrichment layer, one file per table you choose to describe, written by people. You can write it by hand. Studio, AskDB's local web UI, can 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. 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.

By default the prompt carries the whole artifact, as in the example above. Two things are held back: example questions, which only retrieval uses, and the notes on any sensitive table or column.

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 to read the catalogs, and 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. Three 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 with retrieval, a second provider, your embedding model, receives every schema chunk when you build the index and the question on each call.

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 the docs, 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.

Bar charts of retrieval similarity scores, before and after. Before, the top 8 chunks are all subscription and usage tables, no plans table, and the model answered $20. After adding plans.md and an MRR concept, concept:mrr (0.593) and plans#biz (0.576) rank first, plans is in the prompt, and the answer is $38.

The fix was two files. tables/plans.md gave the table a description, aliases such as "subscription plans" and a business-context line saying MRR is built from plans.monthly_price. concepts.md got a monthly recurring revenue concept that links subscriptions and plans; when retrieval returns a concept, AskDB puts every table it links into the prompt. After re-indexing, the concept and the plans notes ranked first, and three runs out of three joined plans and 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.

A sequence diagram of one question: your app sends the question to AskDB, AskDB sends the question and schema text to your model, the model returns SQL, AskDB checks it and returns it to your app, and your app runs it read-only against your database and gets the rows. Rows, credentials and results never go to the model.

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().

The three checks

There are three: the read-only check (on for every built-in dialect), the tenant check (on when the schema has a tenant-policy.md and the caller's scope isn't global) and 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.

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.

Three gates between a model's SQL and your data: AskDB's checks (pattern matching, which can miss), your app's review, and your database role (read-only, row-level security, timeouts, row cap), which is the boundary.

Known limits

  • Little system-schema filtering. With a tenant policy, rc.3's tenant check refuses Postgres's planner-statistics relations (pg_stats and its relatives). Other queries against pg_catalog, information_schema or SQL Server's sys aren'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_QUOTES mode 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.

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.

What the release candidate means

The public API is frozen for 1.0, and later release candidates fix bugs. The exception is the schema artifact format (Schema v2), which may still change before 1.0.0. After 1.0.0, removing an export needs a major version. Twelve packages are at 1.0.0-rc.3 together, including askdb, @askdb/core, @askdb/client, @askdb/ai and the engine packages. Studio, @askdb/enrich and @askdb/rag are at 0.2.0-rc.3. Seven of the twelve jumped from a 0.x version, and a 0.x range in your package.json won't match 1.0.0-rc.3.

Between now and 1.0.0 I'm working on gaps in the checks, reference-doc accuracy and user-visible bugs. There's no date for 1.0.0. The RC is on npm's latest tag, so a plain npm install askdb gets it.

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 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.

What I'd like to hear about:

  • A break anywhere on the Quickstart path, a user-visible bug, or a reference page that 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.