# Databases and NL-to-SQL

Connect read-only to nine SQL engines, inspect and profile schemas, turn plain-language questions into validated SQL, and give agents a safe SQL tool.

Source: https://glamorous-boar.cloudvent.net/databases/

---

<Figure source="/src/assets/images/screens/sql.jpg" alt="Asking a database a question in plain language" caption="Ask your database: a plain-language question becomes read-only SQL grounded in the schema, and Chat shows the query and rows."/>

## Try it in two minutes

1. **New** → *Ask your database (NL-to-SQL)*.
2. Select the *Sales database* node, click **Upload files**, choose `examples/data/sales.sqlite` (a fictional sales database: customers, products, orders, order items) and select it.
3. Ask in **Chat**: *Which product category had the most revenue in 2025?* The answer shows its SQL and the rows.
4. Try something it must refuse: *Delete all cancelled orders*. The write is blocked by policy, and the model refuses instead of substituting another query.

## The nodes

| Node | Does |
|---|---|
| **Database Connector** | A read-only connection, as a `Database` handle. Bounds every query with `max_rows` (500) and `timeout_seconds` (15); `schemas` limits what may be queried. |
| **Schema Inspector** | Tables, columns, primary and foreign keys, optional row counts and sample rows, plus a compact text form for prompts. |
| **Table Profiler** | Null rate, distinct values, min/max/mean or text lengths, top values, over a bounded scan. |
| **SQL Validator / Executor** | Checks SQL against the read-only policy (`validate`), and runs it (`execute`). |
| **NL-to-SQL** | Question → SQL grounded in the schema and optional business `context`, via a forced `submit_sql` call; validated; executed; on errors the error goes back to the model for up to `attempts` (3) tries. May return `answerable=false`. |
| **SQL Tool** | Gives an Agent a `query_database` tool with the schema in its description. |

## Supported engines

| Engine | Covers | Read-only and bounded by |
|---|---|---|
| `sqlite` | Uploaded `.sqlite` / `.db` files | Opened `mode=ro` with `query_only`; a content-addressed copy; progress-handler timeout |
| `duckdb` | Uploaded `.duckdb` files, MotherDuck | `read_only`, no external file access; interrupt on timeout |
| `postgresql` | PostgreSQL, Supabase, Neon, RDS/Aurora, CockroachDB, Redshift | Read-only session + `statement_timeout` |
| `mysql` | MySQL, MariaDB, PlanetScale, TiDB | `SET SESSION TRANSACTION READ ONLY`, execution time limit, rollback |
| `sqlserver` | SQL Server, Azure SQL | Policy + rollback after each query; driver timeout |
| `snowflake` | Snowflake (password, PAT or key pair) | Policy + `STATEMENT_TIMEOUT_IN_SECONDS` |
| `databricks` | SQL warehouses (Unity Catalog) | Policy + polling; cancelled on timeout |
| `clickhouse` | ClickHouse, ClickHouse Cloud | `readonly=1`, `max_execution_time`, server-side row cap |
| `bigquery` | BigQuery | Policy + `jobTimeoutMs`; read-only OAuth scope; cancelled on timeout |

### Connecting with credentials

Use either a `dsn` secret (e.g. `ANALYTICS_DB_DSN=postgresql://reader:…@host:5432/db`) or structured fields: `host`, `port`, `database`, `user`, plus secret references for `password`, `token`, `private_key` or `service_account`, and engine fields (Snowflake `account`/`warehouse`/`role`; Databricks `warehouse`/`catalog`; BigQuery `project`/`location`). The form shows only the fields for the chosen engine.

**Supabase:** Project → Connect → *Session pooler* connection string as the `dsn`, engine `postgresql`.

Engines without a read-only session (SQL Server, Snowflake, Databricks, BigQuery) rely on the policy, so **always use a read-only login, role or grant**.

## The read-only policy

Every query, from NL-to-SQL, the SQL tool or the executor, must pass a policy built on `sqlglot` in the engine's own dialect:

- exactly **one statement**, a SELECT or set operation (CTEs and UNION allowed);
- **no writes anywhere**, including `SELECT … INTO` and data-modifying CTEs;
- no **denied functions**: file access, sleeps, admin functions, and per engine MySQL `SLEEP`/`BENCHMARK`/`LOAD_FILE`, SQL Server `OPENROWSET`/`xp_cmdshell`, DuckDB `read_*`/`glob`, ClickHouse `url`/`s3`/`file`/`remote`, Snowflake `SYSTEM$WAIT`, BigQuery `EXTERNAL_QUERY`;
- only **tables that exist** and are **allowed** (`schemas` on the connector, `allowed_tables` on the executor);
- a **row cap**: LIMIT is added or lowered (TOP on SQL Server).

Independently, the connection itself is read-only where the engine supports it, so a gap in the policy still cannot change data. A test sends a DELETE straight to the connection, bypassing the policy, and it fails.

<Alert variant="warning" title="A guard, not a firewall" text="The policy protects against mistakes and prompt injection. Least privilege still belongs in the database: connect with a role that can only read the tables it needs."/>

## Building blocks for analytics graphs

- **Grounding with business context:** pass definitions (*revenue excludes cancelled orders*) to NL-to-SQL's `context` input, or use [Auto Ontology](/auto-ontology/)'s Ontology Context.
- **Agents with SQL:** connect a SQL Tool to an Agent; combine with Calculator or Code Interpreter for follow-up analysis.
- **Data quality reports:** Database Connector → Table Profiler → LLM to describe anomalies.

## Error codes

`SQL_EMPTY`, `SQL_PARSE_ERROR`, `SQL_MULTIPLE_STATEMENTS`, `SQL_NOT_READ_ONLY`, `SQL_FUNCTION_DENIED`, `SQL_UNKNOWN_TABLE`, `SQL_TABLE_NOT_ALLOWED`, `SQL_TIMEOUT`, `SQL_EXECUTION_ERROR`, `DATABASE_NOT_CONFIGURED`, `DATABASE_INVALID_FILE`, `DATABASE_UNAVAILABLE`, `DATABASE_DRIVER_MISSING`, `TABLE_NOT_FOUND`, `NL_TO_SQL_FAILED`, `QUESTION_EMPTY`. See [Error codes](/error-codes/).

## Limits

Only SQLite and DuckDB are exercised live in CI; other engines are tested against mocked drivers and APIs. No Oracle yet, no PII masking or column-level permissions.
