Metadata-Version: 2.5
Name: sql-ground
Version: 0.1.0
Summary: Check LLM-written SQL before it runs: value grounding, read-only enforcement and predicate-level lineage.
Project-URL: Homepage, https://github.com/basejump-ai/sql-ground
Project-URL: Issues, https://github.com/basejump-ai/sql-ground/issues
Author: Basejump AI
License-Expression: MIT
License-File: LICENSE
Keywords: guardrails,lineage,llm,sql,sqlglot,text-to-sql,validation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pyyaml>=6.0
Requires-Dist: sqlglot<31,>=30.35
Provides-Extra: dev
Requires-Dist: black>=24; extra == 'dev'
Requires-Dist: codespell>=2.3; extra == 'dev'
Requires-Dist: flake8>=7; extra == 'dev'
Requires-Dist: isort>=5.13; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pre-commit>=3.5; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: types-pyyaml; extra == 'dev'
Description-Content-Type: text/markdown

# sql-ground

[![CI](https://img.shields.io/github/actions/workflow/status/basejump-ai/sql-ground/coverage-badge.yml?branch=main&label=CI)](https://github.com/basejump-ai/sql-ground/actions/workflows/coverage-badge.yml)
[![coverage](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbasejump-ai%2Fsql-ground%2Fbadges%2Fcoverage.json)](https://github.com/basejump-ai/sql-ground/actions/workflows/coverage-badge.yml)
[![Python versions](https://img.shields.io/pypi/pyversions/sql-ground)](https://pypi.org/project/sql-ground/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/basejump-ai/sql-ground/blob/main/LICENSE)

Check the SQL an LLM writes before you run it.

If you are building a text-to-SQL agent, the model's SQL fails in predictable ways. It filters on values that
are not in the data (`region = 'California'` when the column holds `CA`), so the query runs, returns nothing,
and the agent reports "no results". It writes a `DELETE` inside a CTE, or two statements where you expected one.
It invents columns, mixes up tables and drops the quotes a case-sensitive identifier needs. `sql-ground`
catches these statically, from the SQL text and a description of your schema, and returns feedback worded so you
can hand it straight back to the model for another attempt.

What it does, most useful first:

- **Value grounding.** Every string literal compared with a column (`=`, `IN`, `LIKE`, through CTEs, subqueries
  and `LOWER()`) is checked against that column's known values, with suggestions: `'California'` → `'CA'`,
  `'calif'` → `'California'`, `'canceled'` → `'cancelled'`. Known values come from your schema file or from a
  callback that queries your own database.
- **Read-only enforcement.** Exactly one SELECT-style statement, with no write, DDL or session-changing operation
  anywhere in the tree (including data-modifying CTEs and `SELECT ... INTO`), no MySQL executable comments or
  other text MySQL runs but sqlglot reads as a comment, and no calls to a denylist of built-ins that run SQL or
  change server state. Anything that does not parse is rejected.
- **Predicate-level lineage.** For every column reference: the physical `schema.table.column` it comes from
  (through aliases, CTEs, subqueries, `UNION` branches and expression aliases), where it is used, and for
  comparisons the operator, literal values, casts and wrapping functions.
- **Existence checks.** Unknown tables and columns (with close-match suggestions), ambiguous columns, and
  identifier-case problems in dialects that care.
- **Auto-quoting (on by default).** Names the database only finds spelled exactly, such as a Postgres column
  created as `"CustomerID"`, are quoted for you in `result.corrected_sql`, changing nothing else in the text.
- **Optional `SELECT *` rejection**, with the table's columns listed so the model can name them.
- **Query comparison.** Whether two queries are identical, only reordered, share a table or are unrelated,
  ignoring alias names and, optionally, every `WHERE` clause: for spotting an agent that repeats itself and for
  matching a new query to a verified one that differs only in its filters.

It never connects to a database and has no LLM client. Runtime dependencies are
[sqlglot](https://github.com/tobymao/sqlglot) and PyYAML.

## Install

```bash
pip install sql-ground
```

Or from a checkout: `pip install .`

This package was first published as `sql-guardrails` (0.1.0, imported as `sql_guardrails`). The code is the same; only
the names changed.

Python 3.10 or newer. Tested with sqlglot 30.35.0 (the dependency is pinned to `>=30.35,<31`, because sqlglot's
optimizer internals change between major versions).

## Quick start

```python
from sql_ground import Schema, check

schema = Schema.from_dict(
    {
        "schemas": {
            "sales": {
                "tables": {
                    "orders": {
                        "columns": {
                            "id": "integer",
                            "region": {"type": "varchar(2)", "values": ["CA", "TX", "NY"]},
                            "status": {"type": "text", "values": ["open", "shipped", "cancelled"]},
                            "amount": "numeric",
                        }
                    }
                }
            }
        }
    }
)

sql = "SELECT SUM(amount) FROM sales.orders WHERE region = 'California' AND status = 'canceled'"
result = check(sql, dialect="postgres", schema=schema)
print(result.ok)
print(result.feedback())
```

```text
False
The SQL query has 2 problems. Fix every one and write the whole query again.
- In WHERE, `sales.orders.region` is compared with 'California', which is not one of its values, so the query will return no rows for it. For 'California' did you mean 'CA'? Its values are: 'CA', 'TX', 'NY'.
- In WHERE, `sales.orders.status` is compared with 'canceled', which is not one of its values, so the query will return no rows for it. For 'canceled' did you mean 'cancelled'? Its values are: 'open', 'shipped', 'cancelled'.
```

`check()` runs the security policies first and stops there if any fail; otherwise, when a schema is given, it
runs validation. `Guardrails(dialect, schema, ...)` holds the same settings for repeated use. Every result is a
`CheckResult` with `ok`, `issues`, `errors`, `warnings`, `lineage`, `feedback()` and `raise_for_issues()`, and,
from auto-quoting, `corrected_sql`, `fixes` and `correction_skipped`.

In an agent loop:

```python
from sql_ground import Guardrails, Schema

guard = Guardrails("postgres", Schema.from_dict({"tables": {"t": {"columns": {"x": "text", "Total": "numeric"}}}}))


def run_tool(sql: str) -> str:
    result = guard.check(sql)
    if not result.ok:
        return result.feedback()  # send this back to the model as the tool result
    sql_to_run = result.corrected_sql  # the query with any names that need quotes quoted
    return f"...run {sql_to_run} here, with a read-only database role..."


print(run_tool("SELECT y FROM t"))
print(run_tool("SELECT x, Total FROM t"))
```

```text
The SQL query has 1 problem. Fix every one and write the whole query again.
- Column `y` in the SELECT list does not exist in table `t`. Use only columns that exist.
...run SELECT x, "Total" FROM t here, with a read-only database role...
```

### Options

`check(sql, dialect, schema=None, **options)`, `Guardrails(dialect, schema=None, **options)` and
`validate_sql(sql, dialect, schema, **options)` take the same keyword options (`extra_denied_functions` and
`policies` only apply to the first two, which run the security check):

| Option | Default | What it does |
| --- | --- | --- |
| `auto_quote` | `True` | Quote names that must be spelled exactly, in `corrected_sql`, instead of reporting them. See [Auto-quoting](#auto-quoting). |
| `reject_star` | `False` | Report every `*` in a select list as a `select_star` error. See [Rejecting `SELECT *`](#rejecting-select-). |
| `check_values` | `True` | Ground string literals against known values. |
| `value_lookup` | `None` | `(column) -> values`: all distinct values of a column the schema lists none for. |
| `value_search` | `None` | `(column, predicate) -> values`: the values that could match a predicate's literals. Give this or `value_lookup`, not both. |
| `max_query_length` | `None` | Reject a query longer than this many characters with a `query_too_long` error, before it is parsed. Off by default. See [Limiting query length](#limiting-query-length). |
| `max_listed_values` | `50` | The most values (or star columns) quoted back in one message. |
| `extra_denied_functions` | `()` | Functions added to the read-only denylist. |
| `policies` | `[ReadOnlyPolicy()]` | Replace the security policies. |

The package exports `check`, `Guardrails`, `validate_sql` (the same function as
`sql_ground.validate.validate`), `analyze_lineage` (`sql_ground.lineage.analyze`), `check_security` and
`ensure_read_only`. `sql_ground.validate` and `sql_ground.lineage` are modules, so
`from sql_ground import validate` gives the module; import the function as
`from sql_ground.validate import validate`, or use `validate_sql`.

## `sql_ground.security`

Needs only the SQL and a dialect, no schema.

```python
from sql_ground import ReadOnlySQLError
from sql_ground.security import ensure_read_only

queries = [
    "SELECT id FROM sales.orders WHERE amount > 10",
    "WITH d AS (DELETE FROM sales.orders RETURNING *) SELECT * FROM d",
    "SELECT 1; DROP TABLE sales.orders",
    "SELECT pg_sleep(600)",
]
for sql in queries:
    try:
        ensure_read_only(sql, "postgres", extra_denied_functions=["pg_sleep"])
        print("allowed  ", sql)
    except ReadOnlySQLError as e:
        print("rejected ", sql, "->", e.code)

try:
    ensure_read_only("DROP TABLE sales.orders", "postgres")
except ReadOnlySQLError as e:
    print(e)
```

```text
allowed   SELECT id FROM sales.orders WHERE amount > 10
rejected  WITH d AS (DELETE FROM sales.orders RETURNING *) SELECT * FROM d -> forbidden_operation
rejected  SELECT 1; DROP TABLE sales.orders -> multiple_statements
rejected  SELECT pg_sleep(600) -> denied_function
Only a single read-only query can be run: one SELECT statement, optionally with CTEs or UNION/INTERSECT/EXCEPT. The statement is not a SELECT query (it parsed as DROP). Rewrite it as one SELECT statement that only reads data.
```

- `ensure_read_only(sql, dialect, *, extra_denied_functions=(), denied_functions=None)` raises
  `ReadOnlySQLError` (with `.code` and `.reason`) or returns the parsed sqlglot statement.
  `denied_functions` replaces the default list `DEFAULT_DENIED_FUNCTIONS`; `extra_denied_functions` adds to it.
  Names are matched case-insensitively, also when schema-qualified.
- `check_security(sql, dialect, policies=None)` returns a `CheckResult`. A policy is any object with
  `check(sql, dialect) -> list[Issue]`; the default is `[ReadOnlyPolicy()]`. That is the extension point for
  further rules, such as table allow-lists built on the lineage module.

Rejected: more than one statement, empty input, anything that does not parse, any root that is not a
`SELECT`/set operation, and any of these anywhere in the tree: `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `COPY`,
DDL, `TRUNCATE`, `COMMENT`, `GRANT`/`REVOKE`, `SELECT ... INTO`, `FOR UPDATE`/`FOR SHARE`, `SET`, `USE`,
transactions, `CALL`/`EXEC`, `SHOW`, `DESCRIBE`, `EXPLAIN`, `ANALYZE`, `VACUUM`, `VALUES` as a statement,
`PRAGMA`, `KILL`, `PUT`/`GET`, `UNLOAD`, and anything else sqlglot can only parse as an opaque command.
In Snowflake and Oracle, reading `seq.NEXTVAL` is rejected too, because it advances the sequence; in other
dialects that is an ordinary column reference.
`SHOW`, `DESCRIBE` and `EXPLAIN` are rejected on purpose: they are not data queries, `EXPLAIN ANALYZE` executes
its statement, and an agent can be given the schema another way.

The default denylist covers functions that run SQL from a string (`dblink`, `openquery`, `openrowset`,
`query_to_xml`, ...), change server or session state (`setval`, `nextval`, `NEXT VALUE FOR`, `set_config`,
`pg_terminate_backend`, Postgres large-object writes, statistics resets, replication and backup control,
Snowflake `system$cancel_*`/`system$abort_*` and pipe, task and account settings, ...), take locks that can block
other sessions (Postgres `pg_advisory_*`, MySQL `get_lock`, ...), notify listeners (`pg_notify`), or read or
write server files (`pg_read_file`, `pg_ls_dir`, `pg_file_write`, MySQL `load_file`, ...). See
`DEFAULT_DENIED_FUNCTIONS` for the full list.

Comments are only treated specially in MySQL and the dialects sqlglot derives from it (Doris, SingleStore and
StarRocks). There, executable comments (`/*! ... */`, `/*M! ... */`) are rejected, because MySQL runs their
contents, and so is `--` followed by anything other than a space or control character, because MySQL reads that
as two minus signs and runs the rest of the line. A comment that merely starts with `!`, such as `-- ! note` or
`/* ! note */`, is an ordinary comment and is allowed, as is the `/*!` syntax in every other dialect.

## `sql_ground.lineage`

```python
from sql_ground.lineage import analyze

sql = """
WITH s AS (SELECT region AS r, amount FROM sales.orders)
SELECT SUM(amount) FROM s WHERE LOWER(r) IN ('calif', 'texas')
"""
lineage = analyze(sql, dialect="postgres")
for ref in lineage.filters():
    print(ref.sql, ref.usage.value, [source.qualified_name for source in ref.sources])
    print(ref.predicate)
```

```text
r where ['sales.orders.region']
Predicate(operator='IN', values=('calif', 'texas'), negated=False, functions=('LOWER',), casts=(), sql="LOWER(r) IN ('calif', 'texas')", has_subquery=False)
```

`analyze(sql, dialect, schema=None)` returns a `QueryLineage` with:

- `columns`: a `ColumnReference` per column reference: `name` and `sql` as written, `usage` (`projection`,
  `where`, `having`, `join`, `group_by`, `order_by`, `qualify`, `other`), `sources` (`SourceColumn`s with
  `database`, `schema`, `table`, `column` and `direct`), `predicate`, and `unresolved` (`None`, `"ambiguous"`,
  `"not_found"` or `"untraceable"`).
- `tables`: the physical tables named (CTE names excluded), with alias and schema matches.
- `stars`: `*` projections that could not be expanded.
- `filters()`: references compared in `WHERE`, `HAVING`, `JOIN ... ON` or `QUALIFY`; `source_columns()`: every
  distinct physical column read.

`SourceColumn.direct` is True when values pass through unchanged (aliases, CTEs, subqueries, `UNION` branches,
`MIN`/`MAX`) and False when an expression sits in between (`CASE`, `CONCAT`, `SUM`, arithmetic). A predicate
lists `functions` innermost first, so `LOWER(TRIM(x))` gives `("TRIM", "LOWER")`; casts are in `casts`.
A predicate's `sql` is rendered by sqlglot from the parsed query, so it can differ in formatting from the
original text.

How it works: identifiers are case-folded (keeping their original spelling), tables are matched to the schema,
and sqlglot's own optimizer does the structural work: `qualify` qualifies columns, expands alias references
and, with a schema, expands `*`; `optimizer.scope` builds the scopes; `sqlglot.lineage` traces references into
CTEs, subqueries and set operations. The library adds what sqlglot does not do: resolving unqualified columns
that `qualify` leaves alone (to the only source in scope, or by schema lookup, which also detects ambiguity),
the `direct` flag, and predicate and literal extraction. Without a schema, a `*` over a single table is still
traced by name; a `*` over a join is not.

## `sql_ground.validate`

```python
from sql_ground import Schema
from sql_ground.validate import validate

schema = Schema.from_dict(
    {
        "schemas": {
            "sales": {
                "tables": {
                    "orders": {"columns": {"id": "integer", "customer_id": "integer", "amount": "numeric"}},
                    "customers": {
                        "columns": {
                            "id": "integer",
                            "state": {"type": "text", "values": ["California", "Texas", "New York"]},
                        }
                    },
                }
            }
        }
    }
)

sql = """
SELECT id, SUM(o.amont)
FROM sales.orders o JOIN sales.customer c ON o.customer_id = c.id
WHERE c.state = 'calif'
GROUP BY id
"""
print("First attempt:")
for issue in validate(sql, "postgres", schema).issues:
    print(" ", issue.code.value, issue.identifier, issue.suggestions)

print("With the table name fixed:")
result = validate(sql.replace("sales.customer ", "sales.customers "), "postgres", schema)
for issue in result.issues:
    print(" ", issue.code.value, issue.identifier, issue.suggestions)
print(result.feedback())
```

```text
First attempt:
  unknown_table sales.customer ('sales.customers', 'sales.orders')
  unknown_column sales.orders.amont ('amount',)
With the table name fixed:
  ambiguous_column id ('o.id', 'c.id')
  unknown_column sales.orders.amont ('amount',)
  ambiguous_column id ('o.id', 'c.id')
  unknown_value sales.customers.state ('California',)
The SQL query has 4 problems. Fix every one and write the whole query again.
- Column `id` in the SELECT list is ambiguous: more than one table in the FROM clause has it. Qualify it with a table alias, for example `o.id` or `c.id`.
- Column `o.amont` in the SELECT list does not exist in table `sales.orders`. Did you mean `amount`? Use only columns that exist.
- Column `id` in GROUP BY is ambiguous: more than one table in the FROM clause has it. Qualify it with a table alias, for example `o.id` or `c.id`.
- In WHERE, `sales.customers.state` is compared with 'calif', which is not one of its values, so the query will return no rows for it. For 'calif' did you mean 'California'? Its values are: 'California', 'Texas', 'New York'.
```

While a table is unknown, columns that might belong to it are not reported, to keep the feedback focused.

`validate(sql, dialect, schema, *, value_lookup=None, value_search=None, check_values=True,
max_listed_values=50, reject_star=False, auto_quote=True, max_query_length=None)` returns a `CheckResult`. Each `Issue` has a `code`, a `message` written for the LLM, a `severity` (`error` or
`warning`; only errors make `ok` false), an `identifier`, a `location` (`SELECT`, `WHERE`, `JOIN`, `FROM`, ...)
and `suggestions`. A query that cannot be parsed or analysed gives an `unanalysable` error: it is never passed
silently.

| Code | Severity | Meaning |
| --- | --- | --- |
| `query_too_long` | error | The query has more characters than `max_query_length` (only when it is set); no other check runs |
| `unanalysable` | error | The SQL could not be parsed or analysed |
| `unknown_table` / `ambiguous_table` | error | No table, or several tables, match the name |
| `unknown_column` / `ambiguous_column` | error | No source, or several sources, have the column |
| `identifier_case` | error | A case-sensitive identifier is spelled so the database would not find it (with auto-quoting on, only when the rewrite was refused) |
| `select_star` | error | A select list uses `*` (only with `reject_star=True`) |
| `unknown_value` | error | A literal compared with a column is not among its known values |
| `unresolved_column` | warning | A reference could not be traced to a table (for example `VALUES`, `UNNEST`) |
| `value_lookup_failed` | warning | The value callback raised; that column was not grounded |

Security issues use `parse_error`, `empty_query`, `multiple_statements`, `not_a_query`, `forbidden_operation`,
`executable_comment` and `denied_function`.

### How value grounding decides

- **Which comparisons.** `=`, `!=`/`<>`, `IN` and `NOT IN` need an exact match. `LIKE` and `ILIKE` patterns
  must match at least one known value (`%`, `_`, backslash escapes). Range comparisons, `BETWEEN`, `IS`,
  `SIMILAR TO`, regular expressions, `= ANY(ARRAY[...])`, `LIKE ANY` and row-value `IN` are not checked.
  Literals in a `CASE WHEN` condition are checked like any other comparison.
- **Negation.** A value that does not exist in `!=` or `NOT IN` is reported too, as a condition that excludes
  nothing. With `value_search` this relies on the callback's contract below.
- **Case-insensitive comparisons.** `LOWER`, `UPPER`, `TRIM`, `LTRIM` and `RTRIM` around the column are applied
  to the known values first, so `LOWER(status) = 'Open'` is reported (it can never match) with the suggestion
  `'open'`. `ILIKE` ignores case. In `mysql` and `tsql`, whose default collations are case-insensitive, all
  comparisons ignore case; elsewhere they are case-sensitive.
- **Other functions and expressions.** Any other function around the column (`COALESCE`, `SUBSTRING`,
  `CONCAT`, ...), or a comparison with an expression alias (a `CASE` in a CTE, say), skips the check.
- **Casts.** A cast to a text type is ignored; a cast to anything else skips the check.
- **Column types.** Columns whose schema type is not a text type are skipped (numbers, dates). Columns with no
  type, or a user-defined type such as a Postgres enum, are checked. Only string literals are checked.
- **Set operations.** A literal compared with a `UNION` output must match the values of at least one branch.
- **No known values.** Skipped, never failed.

### Supplying values from your database

When the schema lists no values for a column, one of two callbacks supplies them. Values in the schema always
take precedence. A callback that returns `None` skips the column; one that raises gives a `value_lookup_failed`
warning and the column is skipped.

- `value_lookup(column)` is called with a `SourceColumn` and returns **all** the column's distinct values. It is
  called at most once per column per check. An empty list means the column has no non-null values, so every
  literal compared with it is reported.

```python
import sqlite3

from sql_ground import Schema
from sql_ground.lineage import SourceColumn
from sql_ground.validate import validate

# Stand-in for your own database.
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE leads (id INTEGER, country TEXT)")
db.executemany("INSERT INTO leads VALUES (?, ?)", [(1, "United States"), (2, "Canada"), (3, "Mexico")])

schema = Schema.from_dict({"tables": {"leads": {"columns": {"id": "integer", "country": "text"}}}})


def distinct_values(column: SourceColumn) -> list[str] | None:
    # Only look up columns from your own schema; the names are spelled as the schema spells them.
    table = schema.table(column.table, schema=column.schema)
    if table is None or table.column(column.column) is None:
        return None
    rows = db.execute(f'SELECT DISTINCT "{column.column}" FROM "{column.table}" LIMIT 1000')
    return [row[0] for row in rows]


result = validate("SELECT COUNT(*) FROM leads WHERE country = 'USA'", "sqlite", schema, value_lookup=distinct_values)
print(result.feedback())
```

```text
The SQL query has 1 problem. Fix every one and write the whole query again.
- In WHERE, `leads.country` is compared with 'USA', which is not one of its values, so the query will return no rows for it. Its values are: 'United States', 'Canada', 'Mexico'.
```

With more than `max_listed_values` values the message quotes a sample. For high-cardinality columns, use
`value_search` instead.

- `value_search(column, predicate)` is also given the `Predicate`: `operator`, `values` (the literals),
  `negated`, `functions` (such as `("LOWER",)`) and `casts`. It returns **the column's values that could equal
  or match any of the literals**, and may return more (similar values, a sample). That lets you run a narrowing
  query instead of fetching every value. Return raw stored values: the predicate's `LOWER`, `UPPER` and `TRIM`
  are applied to them here. It is called at most once per column and predicate per check (results depend on the
  literals, so they are not cached per column).

  Because the list may be partial, messages say "does not match any value in the database" and "Values found in
  the database: ...", never "its values are". A literal missing from the list is reported, including in `!=`
  and `NOT IN` (as excluding nothing), which is sound as long as the contract holds: if your query is capped and
  hits the cap, return `None`. An empty list means nothing in the column matches any literal; the message then
  tells the model to check the value or ask the user.

The two forms are told apart by the parameter they are passed as, never by inspecting the callable, so lambdas,
`functools.partial` objects, bound methods and `*args` functions are all called the same predictable way.

`fuzzy_pattern(value)` builds the LIKE pattern for a narrowing query: lower-cased, every run of punctuation and
whitespace replaced by `%`, wrapped in `%`, so `'Acme, Inc.'` gives `'%acme%inc%'`. Compared with
`LOWER(column)` it finds every value equal to the literal (also through `LOWER`/`UPPER`/`TRIM`, for ASCII text)
or matched by it as a LIKE pattern. The library still never connects to a database; you run the query.

A complete callback, with the database cursor passed in by you. **The query execution is illustrative:** sqlite3
from the standard library stands in for your database, so adapt the parameter style (`?` here, `%s` for
psycopg), identifier quoting and `LIMIT` syntax (`TOP` in T-SQL) to your driver and dialect.

```python
import functools
import sqlite3

from sql_ground import Guardrails, Predicate, Schema, SourceColumn, fuzzy_pattern

schema = Schema.from_dict({"tables": {"leads": {"columns": {"id": "integer", "company": "text"}}}})

# Stand-in for your database.
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE leads (id INTEGER, company TEXT)")
db.executemany(
    "INSERT INTO leads VALUES (?, ?)",
    [(1, "Acme Corp"), (2, "ACME Inc."), (3, "Globex"), (4, "Initech"), (5, "Umbrella Health")],
)

MAX_MATCHES = 200


def search_values(cursor: sqlite3.Cursor, column: SourceColumn, predicate: Predicate) -> list[str] | None:
    # Only query tables and columns from your own schema; the names are spelled as the schema spells them.
    table = schema.table(column.table, schema=column.schema, database=column.database)
    if table is None or table.column(column.column) is None:
        return None
    name, source = f'"{column.column}"', f'"{column.table}"'
    patterns = [fuzzy_pattern(value) for value in predicate.string_values]
    where = " OR ".join(f"LOWER({name}) LIKE ?" for _ in patterns)
    rows = cursor.execute(
        f"SELECT DISTINCT {name} FROM {source} WHERE {where} LIMIT {MAX_MATCHES + 1}", patterns
    ).fetchall()
    if len(rows) > MAX_MATCHES:
        return None  # too many to be sure every match is in the list: skip this column
    if not rows:
        # Nothing resembles the literals. A few values still show the model their format.
        rows = cursor.execute(f"SELECT DISTINCT {name} FROM {source} LIMIT 20").fetchall()
    return [row[0] for row in rows]


guard = Guardrails("sqlite", schema, value_search=functools.partial(search_values, db.cursor()))
for company in ["Globex", "Acme", "Wayne Enterprises"]:
    print(guard.check(f"SELECT id FROM leads WHERE company = '{company}'").feedback() or "ok")
```

```text
ok
The SQL query has 1 problem. Fix every one and write the whole query again.
- In WHERE, `leads.company` is compared with 'Acme', which does not match any value in the database, so the query will return no rows for it. For 'Acme' did you mean 'Acme Corp' or 'ACME Inc.'? Values found in the database: 'Acme Corp', 'ACME Inc.'.
The SQL query has 1 problem. Fix every one and write the whole query again.
- In WHERE, `leads.company` is compared with 'Wayne Enterprises', which does not match any value in the database, so the query will return no rows for it. Values found in the database: 'Acme Corp', 'ACME Inc.', 'Globex', 'Initech', 'Umbrella Health'.
```

## Comparing two queries

`compare_queries` says how alike two queries are. Two uses in an agent: noticing that the model wrote the same
query again, and deciding whether a new query has the same shape as one a person already verified, apart from
its filter values.

```python
from sql_ground import compare_queries

previous = "SELECT o.region, SUM(o.amount) AS total FROM sales.orders o WHERE o.status = 'open' GROUP BY o.region"
candidates = [
    "select x.region, sum(x.amount) as revenue from sales.orders x where x.status = 'open' group by x.region",
    "SELECT SUM(o.amount) AS total, o.region FROM sales.orders o WHERE o.status = 'open' GROUP BY o.region",
    "SELECT o.region, SUM(o.amount) AS total FROM sales.orders o WHERE o.status = 'shipped' GROUP BY o.region",
    "SELECT name FROM sales.customers",
]
for sql in candidates:
    print(compare_queries(previous, sql, "postgres").value)

# Same shape, different filter: still matches a verified query once WHERE is ignored.
print(compare_queries(previous, candidates[2], "postgres", ignore_where=True).value)
```

```text
identical
equivalent
similar
different
identical
```

`compare_queries(sql_a, sql_b, dialect, *, ignore_where=False)` returns a `QuerySimilarity` (a `str` enum),
checked in this order:

- `identical` (`IDENTICAL`): no difference after canonicalising both queries. They can still differ in alias
  names (so in output column names), in quoting or identifier case the dialect ignores, in comments and in
  formatting.
- `equivalent` (`EQUIVALENT`): the only differences are children listed in another order where the order does
  not change the rows: the select list (so the column order can differ), `AND`/`OR` operands, the two sides of
  `=`, `<>` and `*`, `IN` lists and `GROUP BY` keys. Swapping `a - b`, `x > 1` or `ORDER BY` keys is a real
  difference.
- `similar` (`SIMILAR`): any other difference, when the queries read at least one table in common.
- `different` (`DIFFERENT`): no table in common.

So "the same query again" is `identical` or `equivalent`, and "same shape as a verified query" is `identical`
with `ignore_where=True`.

How queries are canonicalised:

- **Aliases.** Table aliases, derived-table aliases and CTE names are replaced by a label for what they refer
  to, and every reference that sqlglot's scope analysis binds to them (including from correlated subqueries)
  gets the same label. Column aliases get a label made from the aliased expression, and references to them
  from an outer query, or as a bare name in `ORDER BY`, are relabelled too. `SELECT o.id FROM sales.orders o`
  and `SELECT orders.id FROM sales.orders` are identical. A name is never merged with a different name: an
  unqualified column is only traced into a CTE or derived table when every source in its `FROM` is one whose
  columns are all known, and what cannot be traced is compared as written.
- **Identifiers** are compared the way the dialect looks them up: Postgres folds unquoted names to lower case
  and Snowflake to upper case, so `Region` and `"region"` are the same Postgres column but `"Region"` is not;
  case-insensitive dialects (DuckDB, T-SQL, ...) ignore case and quotes; MySQL and BigQuery column names are
  case-insensitive while their table names are compared exactly. **String literals are always compared
  exactly.**
- **Tables** are the physical tables read anywhere in the query; CTE names are not tables. Two names are the
  same table when every part both spell out agrees: `orders` matches `sales.orders`, but `sales.orders` does
  not match `crm.orders`.
- **`ignore_where=True`** removes the `WHERE` clause of every `SELECT` (top level, CTEs, derived tables and
  subqueries), with everything inside it, from both queries before comparing. Only `WHERE`: `JOIN ... ON`,
  `HAVING`, `QUALIFY`, aggregate `FILTER (WHERE ...)` and `LIMIT` are still compared, so a filter moved into
  `ON` or `HAVING` is a difference. Two queries that differ only in their `WHERE` clauses are `identical`
  however different those clauses are, including subqueries in them that read other tables.

Unknown dialects raise `UnsupportedDialectError`. Empty input, SQL that does not parse, more than one statement
and anything that is not a query raise `AnalysisError`.

This is a syntactic comparison. `identical` and `equivalent` do not prove that two queries return the same rows,
and two queries that do (`a + b` and `b + a`, a join written two ways, `IN` versus `EXISTS`) can be `similar`.
When the canonical form cannot tell, the label errs towards less similar, never towards `identical`.

## Auto-quoting

On by default. After the checks, every table and column name that refers to a schema identifier which must be
spelled exactly, and that the database would resolve to a different spelling as written, is replaced by the
quoted schema spelling. Only those tokens change: whitespace, comments, literals, keyword case, aliases and CTE
names stay exactly as written, and a query that needs no change comes back byte-identical. Fixed names are not
issues; they are listed in `result.fixes` (each with `identifier`, `written`, `replacement`, `location`, and
`start`/`end` offsets into `result.sql`, which keeps the query as given).

```python
from sql_ground import Schema, check

schema = Schema.from_dict(
    {
        "tables": {
            "Customers": {"columns": {"CustomerID": "integer", "name": "text", "region": "text"}},
            "orders": {"columns": {"id": "integer", "CustomerID": "integer", "amount": "numeric"}},
        }
    }
)

sql = """-- revenue per customer
SELECT c.name, SUM(o.amount) AS revenue
FROM Customers c JOIN orders o ON o.CustomerID = c.CustomerID
WHERE c.region = 'West'
GROUP BY c.name"""
result = check(sql, "postgres", schema)
print(result.ok)
print(result.corrected_sql)
for fix in result.fixes:
    print(fix.location, fix.written, "->", fix.replacement)
```

```text
True
-- revenue per customer
SELECT c.name, SUM(o.amount) AS revenue
FROM "Customers" c JOIN orders o ON o."CustomerID" = c."CustomerID"
WHERE c.region = 'West'
GROUP BY c.name
FROM Customers -> "Customers"
JOIN CustomerID -> "CustomerID"
JOIN CustomerID -> "CustomerID"
```

**When a name must be spelled exactly.** The schema's `case_sensitive` flag decides when it is set: `true`
(the database only accepts this spelling) or `false` (it does not; this is how you opt a name out). When it is
not set, the spelling decides, only where it is evidence:

| Dialect | Inferred to need its exact spelling when the flag is unset | With `case_sensitive: true` |
| --- | --- | --- |
| `postgres` (folds unquoted names to lower case) | the name contains an upper-case letter (`CustomerID`, `REGION`) | quoted when written with another spelling |
| `snowflake` (folds to upper case) | the name mixes upper and lower case (`CustomerID`); not all-lower-case names, because many tools list Snowflake's case-insensitive names in lower case | quoted when written with another spelling, so a lower-case `code` created as `"code"` must be marked |
| `mysql`, `bigquery` | nothing | table names only (column names are case-insensitive) |
| `redshift`, `athena`, `duckdb`, `tsql` | nothing | nothing: names are case-insensitive (Redshift folds quoted names too by default) |

Other sqlglot dialects follow the row of their folding rule. The schema is taken as the statement of the real
spelling: if a Postgres schema file says `CustomerID` for a column the database stores as `customerid`, a query
that works unquoted would be broken by quoting it, so write the name as stored or set `case_sensitive: false`.
A name with spaces or other characters that cannot be written bare needs no inference: a query can only refer
to it quoted, and a wrongly-cased quoted reference is corrected like any other when the name is exact. Reserved
words are not detected (see [Limits](#limits)).

A reference to a CTE or subquery column is quoted when that column passes a schema column through under its
own name (a bare column or a `*`), because its name is then the stored spelling; a name the query defines (a
column alias, a CTE column list, a CTE name) is never quoted. Schema and database names are not rewritten.

**When the query is not rewritten.** `corrected_sql` is `None` and `correction_skipped` says why when the query
has an `unanalysable`, `unknown_table`, `ambiguous_table`, `unknown_column` or `ambiguous_column` error (the
right spelling is not known yet), when a name that needs quotes is used where the analysis cannot follow it
(a `JOIN ... USING` list, or a reference that cannot be traced), or when the rewritten query does not analyse to
the same lineage. The result is then what `auto_quote=False` gives: names marked `case_sensitive: true` are
reported as `identifier_case` errors. Other errors, such as `unknown_value` or `select_star`, do not stop the
rewrite. Without a schema, `corrected_sql` is the query as given.

The security policies always run on the query as written, and `check()` and `Guardrails` also run them on
`corrected_sql`; if it failed them, it would be dropped like a refused rewrite. On a lineage you already have,
`sql_ground.quoting.quote_identifiers(lineage, schema)` returns the same rewrite.

**Auto-quoting is on by default.** With a schema, a name that must be spelled exactly and is written otherwise
is fixed in `corrected_sql` instead of being reported as an `identifier_case` error, so such a query now passes;
run `corrected_sql`, not the query as given. Names inferred from their spelling (see the table above) are fixed
too, which no `identifier_case` check ever reported. `Column.case_sensitive` and `Table.case_sensitive` default
to `None` (unset) instead of `False`. Pass `auto_quote=False` to keep the query as written: `corrected_sql` is
then `None` and every issue is reported exactly as without the option.

## Rejecting `SELECT *`

Off by default. With `reject_star=True`, every `*` in a select list is a `select_star` error telling the model
to name the columns, with the table's columns listed when the star reads one schema table. It works with and
without a schema, from `check()`, `Guardrails` and `validate_sql()`.

```python
from sql_ground import Schema, check

schema = Schema.from_dict({"tables": {"orders": {"columns": {"id": "integer", "region": "text", "amount": "numeric"}}}})

result = check("SELECT * FROM orders WHERE EXISTS (SELECT * FROM orders)", "postgres", schema, reject_star=True)
print(result.feedback())
```

```text
The SQL query has 1 problem. Fix every one and write the whole query again.
- The query selects `*`. Selecting columns with * is not allowed: name each column you need instead. The columns of `orders` are: `id`, `region`, `amount`.
```

What counts: `SELECT *` and `SELECT t.*`, also with `EXCEPT`, `EXCLUDE`, `REPLACE` or `RENAME` (the output
still depends on the table definition), in the main query, CTEs, derived tables, set-operation branches, and
scalar and `IN` subqueries. What does not: `COUNT(*)` and any other star that is a function argument, and the
select list of an `EXISTS` subquery, which only tests whether a row exists (a CTE or derived table inside the
`EXISTS` still counts).

## Limiting query length

Off by default: with `max_query_length=None` no query is rejected for its length. With
`max_query_length=4000`, a query of more than 4000 characters is a `query_too_long` error telling the model to
write a shorter one. It works with and without a schema, from `check()`, `Guardrails` and `validate_sql()`.

```python
from sql_ground import check

result = check("SELECT id FROM orders WHERE region = 'CA'", "postgres", max_query_length=20)
print(result.feedback())
```

```text
The SQL query has 1 problem. Fix every one and write the whole query again.
- The query is 41 characters long. Queries longer than 20 characters are not allowed: write a shorter query.
```

The length is `len(sql)`: characters of the string as given, including whitespace and comments. It is not a
count of bytes or of tokens. A query of exactly `max_query_length` characters passes. The check runs first and
the query is never handed to the SQL parser when it is over the limit, so `query_too_long` is the only issue in
the result, with no lineage and no `corrected_sql`. `max_query_length` must be a positive integer or `None`;
anything else raises `ValueError`.

## Schema format

A YAML file (or the same structure as a Python dict for `Schema.from_dict`):

```yaml schema.yml
version: 1
default_schema: sales        # unqualified table names resolve here
schemas:
  sales:
    tables:
      orders:
        columns:
          id: integer                  # shorthand: just the type
          region:
            type: varchar(2)
            values: [CA, TX, NY]       # the complete set of values, used for grounding
          status:
            type: text
            values: [open, shipped, cancelled]
            description: Order lifecycle state
          amount: numeric(10, 2)
          note:                        # no type, no values
      customers:
        columns:
          id: integer
          State:
            type: text
            case_sensitive: true       # created as "State"; the database needs this exact spelling
tables:                                # tables with no schema
  audit_log:
    columns:
      event: text
```

```python
from sql_ground import Guardrails, load_schema

schema = load_schema("schema.yml")
print(Guardrails("postgres", schema).check("SELECT state FROM customers WHERE state = 'Texas'").corrected_sql)

result = Guardrails("postgres", schema, auto_quote=False).check("SELECT state FROM customers WHERE state = 'Texas'")
print(result.feedback())
```

```text
SELECT "State" FROM customers WHERE "State" = 'Texas'
The SQL query has 2 problems. Fix every one and write the whole query again.
- Column `state` in the SELECT list must be written as "State" (quoted, with exactly this capitalisation); as written the database looks for `state`.
- Column `state` in WHERE must be written as "State" (quoted, with exactly this capitalisation); as written the database looks for `state`.
```

- Top-level keys: `version` (1), `default_schema`, `schemas`, `tables` (tables with no schema) and `databases`
  (`databases: {warehouse: {schemas: {...}}}` for three-part names).
- A table has `columns` and optionally `case_sensitive`. A schema can set `case_sensitive` for all its tables.
- A column is `null`, a type string, or a mapping with `type`, `values`, `case_sensitive` and `description`.
- Names match case-insensitively. Mark an identifier `case_sensitive: true` when the database only accepts its
  exact spelling (for example created quoted with capitals in Postgres or Snowflake), and `false` when it does
  not. Unset (`None` on `Table` and `Column`), auto-quoting infers it from the spelling as described in
  [Auto-quoting](#auto-quoting); `auto_quote=False` uses only names marked `true`. Dialects that sqlglot treats
  as case-insensitive (`tsql`, `redshift`, `athena`, `duckdb`, and BigQuery and MySQL column names) never get
  case issues.
- Without `default_schema`, an unqualified table name matches a table in any schema if exactly one has that
  name; if several do, you get `ambiguous_table`.
- You can also build `Schema(tables=(Table(...), ...))` directly from `Table` and `Column` dataclasses.

## dbt

`load_dbt_schema(paths, schema=None, database=None, default_schema=None)` reads dbt `schema.yml` files:

```yaml models/schema.yml
version: 2
models:
  - name: stg_orders
    columns:
      - name: order_id
        data_type: integer
        tests: [unique, not_null]
      - name: status
        tests:
          - accepted_values:
              values: ['placed', 'shipped', 'completed', 'returned']
```

```python
from sql_ground import check, load_dbt_schema

schema = load_dbt_schema(["models/schema.yml"], schema="analytics")
print([table.qualified_name for table in schema.tables])
result = check("SELECT order_id FROM analytics.stg_orders WHERE status = 'complete'", "snowflake", schema)
print(result.feedback())
```

```text
['analytics.stg_orders']
The SQL query has 1 problem. Fix every one and write the whole query again.
- In WHERE, `analytics.stg_orders.status` is compared with 'complete', which is not one of its values, so the query will return no rows for it. For 'complete' did you mean 'completed'? Its values are: 'placed', 'shipped', 'completed', 'returned'.
```

What it reads: `models` (a table named by the model, or its `config.alias`) and `sources` (a table in the
source's `schema`, defaulting to the source name, and `database`, named by `identifier` if set); `columns` with
`data_type` and `quote` (as `case_sensitive`, unset when `quote` is not given); and `accepted_values` tests under `tests` or `data_tests`, with
`values` directly or under `arguments`, which become known values.

What it does not do: run dbt, read `dbt_project.yml`, `manifest.json` or `catalog.json`, render Jinja, or work
out a model's real schema. dbt picks that at run time from the target and `generate_schema_name`, so pass the
schema your models are built in as `schema=`; a model's `config.schema` is ignored. Columns not documented in
YAML are unknown to it, so a query using them gets `unknown_column`.

## Dialects

Any sqlglot dialect name is accepted. The test suite runs every module on `athena`, `bigquery`, `duckdb`,
`mysql`, `postgres`, `redshift`, `snowflake` and `tsql`. All eight work without special handling, with one
dialect rule to know: BigQuery requires `UNION ALL` or `UNION DISTINCT`, and sqlglot rejects a bare `UNION`
there, so such a query fails both the security check and analysis.

## Limits

Read these before relying on the library for safety.

- **The security check is a static check of SQL text.** It does not replace connecting with a database role
  that can only read. Use both: the role is the control, this check gives the model a clear message before the
  database refuses and stops obvious mistakes early.
- **A SELECT that calls a user-defined function can do anything.** `SELECT app.archive_orders()` passes,
  because nothing in the text says what the function does.
- **The function denylist is best-effort.** It lists well-known built-ins, not all of them. For example
  `pg_sleep`, MySQL `SLEEP` and `BENCHMARK`, and Snowflake `SYSTEM$WAIT` pass by default; add what matters to you
  with `extra_denied_functions`.
- **sqlglot and a database can tokenize edge cases differently.** The check sees the text as sqlglot reads it.
  Server settings it cannot see change how the same text reads: with Postgres `standard_conforming_strings=off`
  a backslash escapes a quote, and MySQL's `NO_BACKSLASH_ESCAPES` and `ANSI_QUOTES` modes change strings and
  identifiers. sqlglot fails closed on what it cannot tokenize, but where both tokenize successfully and
  differently, the check can be wrong. (These setting behaviours come from the databases' documentation; the
  test suite only pins what sqlglot does.)
- **Lineage gaps.** These are reported as `untraceable` (a warning in validation), never guessed:
  a `*` over a join when no schema is given; recursive CTEs (only partly traced); `VALUES`, `UNNEST` and table
  functions; `PIVOT` output columns. Paths into semi-structured columns (`payload:city`) are attributed to the
  top-level column and not grounded.
- **Grounding gaps.** Not checked: numeric literals, functions other than `LOWER`/`UPPER`/`TRIM`, expression
  aliases, `USING` join columns (sqlglot rewrites them as `COALESCE`), `= ANY(ARRAY[...])`, `LIKE ANY`,
  row-value `IN`, `SIMILAR TO` and regular expressions. Collation is assumed to be the dialect default.
- **Case checks follow the schema's spelling.** A name that is neither marked case-sensitive nor inferred to
  be is matched case-insensitively, so a quoted `"Region"` for a Postgres column named `region` is not reported
  or rewritten, though Postgres would reject it. Inference trusts the schema: a Postgres schema that spells a
  column `CustomerID` when the database stores `customerid` makes auto-quoting break a working query (set
  `case_sensitive: false`). Two schema names that differ only by case (`Code` and `code` in one table) are
  treated as one; the first wins.
- **Auto-quoting gaps.** It refuses (and reports as without it) when a name that needs quotes appears in a
  `JOIN ... USING` list or in a reference the lineage cannot trace, and when a BigQuery name is written as one
  backticked path (`` `project.dataset.Table` ``). Schema and database names are never quoted. Column names
  that are reserved words are not quoted, because sqlglot has no reserved-word list for these dialects:
  `SELECT user FROM accounts` passes unchanged in Postgres, which reads `user` as `CURRENT_USER`, and
  `SELECT order FROM accounts` passes although Postgres rejects it.
- **Query comparison is syntactic.** Labels come from sqlglot's syntax trees and edit script, not from running
  or reasoning about the queries. Not relabelled, so compared as written: aliases with a column list
  (`AS s(a, b)`), `UNNEST`, `VALUES` and `LATERAL` aliases, and column aliases referred to from `WHERE`,
  `GROUP BY`, `HAVING` or later in the same select list. Listing CTEs, derived tables or self-joined tables in
  another order, or a BigQuery path in one pair of backticks versus separate ones, gives a less similar label
  than the queries deserve. Nothing here has been measured on real LLM output.
- **Suggestions are heuristics** (case-only differences, prefixes, word initials, then string similarity). They
  can miss, as in `'USA'` against `'United States'` above, or suggest the wrong value. Nothing here has been
  measured for accuracy on real LLM output.

## Development

```bash
python3 -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/pre-commit install            # run the linters on every commit
.venv/bin/pytest --cov                  # tests with line and branch coverage
.venv/bin/mypy
.venv/bin/pre-commit run --all-files    # black, ruff, flake8, isort, codespell and file checks
```

`pytest --cov` prints the lines and branches the tests do not reach; add `--cov-report=html` for a browsable
report in `htmlcov/`. CI (`.github/workflows/ci.yml`) runs the same pre-commit hooks and mypy, and the tests with
coverage on Python 3.10 to 3.13, on every pull request and before a release is published. It fails if coverage
drops below the threshold set there. The coverage badge is updated on each push to `main` by
`.github/workflows/coverage-badge.yml`, which runs the tests once and stores the result on the `badges` branch. The CI
badge shows whether that run on `main` passed.

The tests run offline and include `tests/test_readme.py`, which runs every Python example in this README and
compares the output with what is shown here. `tests/test_limits.py` pins the limits above, so a change that
lifts one shows up as a failing test.

The library was extracted from the SQL agent in [Basejump](https://github.com/Basejump-AI/Basejump).

## License

MIT. See [LICENSE](LICENSE).
