groundsql 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
groundsql/sample.py ADDED
@@ -0,0 +1,167 @@
1
+ """Build a deterministic sample retail database for demos, tests and evals.
2
+
3
+ Six tables: customers, categories, products, orders, order_items, returns.
4
+ Same seed -> byte-for-byte the same data, so eval gold answers stay stable.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import pathlib
11
+ import random
12
+ import sqlite3
13
+
14
+ SCHEMA = """
15
+ CREATE TABLE customers (
16
+ customer_id INTEGER PRIMARY KEY,
17
+ full_name TEXT NOT NULL,
18
+ city TEXT NOT NULL,
19
+ country TEXT NOT NULL,
20
+ signup_date TEXT NOT NULL
21
+ );
22
+ CREATE TABLE categories (
23
+ category_id INTEGER PRIMARY KEY,
24
+ category_name TEXT NOT NULL
25
+ );
26
+ CREATE TABLE products (
27
+ product_id INTEGER PRIMARY KEY,
28
+ product_name TEXT NOT NULL,
29
+ category_id INTEGER NOT NULL REFERENCES categories(category_id),
30
+ list_price REAL NOT NULL
31
+ );
32
+ CREATE TABLE orders (
33
+ order_id INTEGER PRIMARY KEY,
34
+ customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
35
+ order_date TEXT NOT NULL,
36
+ status TEXT NOT NULL,
37
+ channel TEXT NOT NULL
38
+ );
39
+ CREATE TABLE order_items (
40
+ order_id INTEGER NOT NULL REFERENCES orders(order_id),
41
+ product_id INTEGER NOT NULL REFERENCES products(product_id),
42
+ quantity INTEGER NOT NULL,
43
+ unit_price REAL NOT NULL,
44
+ PRIMARY KEY (order_id, product_id)
45
+ );
46
+ CREATE TABLE returns (
47
+ return_id INTEGER PRIMARY KEY,
48
+ order_id INTEGER NOT NULL REFERENCES orders(order_id),
49
+ product_id INTEGER NOT NULL REFERENCES products(product_id),
50
+ reason TEXT NOT NULL,
51
+ return_date TEXT NOT NULL
52
+ );
53
+ """
54
+
55
+ CITIES = [
56
+ ("Bengaluru", "India"), ("Mumbai", "India"), ("Delhi", "India"), ("Pune", "India"),
57
+ ("London", "United Kingdom"), ("Manchester", "United Kingdom"),
58
+ ("New York", "United States"), ("Austin", "United States"), ("Seattle", "United States"),
59
+ ("Berlin", "Germany"), ("Singapore", "Singapore"), ("Dubai", "United Arab Emirates"),
60
+ ]
61
+ FIRST = ["Aarav", "Diya", "Kabir", "Meera", "Rohan", "Anaya", "Liam", "Emma", "Noah", "Olivia",
62
+ "Lukas", "Mia", "Wei", "Sara", "Omar", "Zara", "Arjun", "Isha", "Ethan", "Ava"]
63
+ LAST = ["Sharma", "Iyer", "Khan", "Patel", "Reddy", "Smith", "Jones", "Brown", "Müller",
64
+ "Tan", "Lee", "Hassan", "Gupta", "Nair", "Wilson", "Garcia"]
65
+ CATALOG = {
66
+ "Footwear": ["Running Shoe", "Trail Shoe", "Court Sneaker", "Slide Sandal", "Hiking Boot"],
67
+ "Apparel": ["Dri-Fit Tee", "Fleece Hoodie", "Track Pant", "Rain Jacket", "Compression Tight"],
68
+ "Accessories": ["Gym Bag", "Water Bottle", "Cap", "Crew Socks 3-Pack", "Wrist Band"],
69
+ "Electronics": ["Fitness Band", "Wireless Earbuds", "Smart Scale", "Heart Rate Strap"],
70
+ "Equipment": ["Yoga Mat", "Dumbbell Set", "Resistance Bands", "Jump Rope", "Foam Roller"],
71
+ }
72
+ PRICE = {"Footwear": (60, 180), "Apparel": (20, 120), "Accessories": (8, 60),
73
+ "Electronics": (40, 250), "Equipment": (10, 150)}
74
+ STATUSES = ["delivered"] * 14 + ["shipped"] * 3 + ["cancelled"] * 2 + ["processing"]
75
+ CHANNELS = ["web"] * 5 + ["app"] * 4 + ["marketplace"] * 3
76
+ REASONS = ["wrong size", "damaged", "not as described", "changed mind", "late delivery"]
77
+
78
+
79
+ TABLES = ["customers", "categories", "products", "orders", "order_items", "returns"]
80
+
81
+ # PostgreSQL keeps money exact (NUMERIC), so ROUND(SUM(...), 2) means the same in both dialects.
82
+ SCHEMA_POSTGRES = (
83
+ SCHEMA.replace("list_price REAL", "list_price NUMERIC(10,2)")
84
+ .replace("unit_price REAL", "unit_price NUMERIC(10,2)")
85
+ )
86
+
87
+
88
+ def generate(seed: int = 42, n_customers: int = 250, n_orders: int = 2000) -> dict[str, list[tuple]]:
89
+ """Every row of the sample database. Same seed, same rows, in either dialect."""
90
+ rng = random.Random(seed)
91
+ rows: dict[str, list[tuple]] = {t: [] for t in TABLES}
92
+
93
+ start = dt.date(2025, 1, 1)
94
+ for cid in range(1, n_customers + 1):
95
+ city, country = rng.choice(CITIES)
96
+ name = f"{rng.choice(FIRST)} {rng.choice(LAST)}"
97
+ signup = start + dt.timedelta(days=rng.randrange(0, 500))
98
+ rows["customers"].append((cid, name, city, country, signup.isoformat()))
99
+
100
+ products = []
101
+ pid = 0
102
+ for cat_id, (cat, items) in enumerate(CATALOG.items(), start=1):
103
+ rows["categories"].append((cat_id, cat))
104
+ lo, hi = PRICE[cat]
105
+ for item in items:
106
+ pid += 1
107
+ price = round(rng.uniform(lo, hi), 2)
108
+ products.append((pid, price))
109
+ rows["products"].append((pid, item, cat_id, price))
110
+
111
+ return_id = 0
112
+ for oid in range(1, n_orders + 1):
113
+ cid = rng.randint(1, n_customers)
114
+ day = start + dt.timedelta(days=rng.randrange(0, 700))
115
+ status = rng.choice(STATUSES)
116
+ rows["orders"].append((oid, cid, day.isoformat(), status, rng.choice(CHANNELS)))
117
+ for prod_id, price in rng.sample(products, rng.choice([1, 1, 1, 2, 2, 3])):
118
+ discount = rng.choice([1.0, 1.0, 1.0, 0.9, 0.8])
119
+ rows["order_items"].append(
120
+ (oid, prod_id, rng.choice([1, 1, 1, 2, 3]), round(price * discount, 2)))
121
+ if status == "delivered" and rng.random() < 0.08:
122
+ return_id += 1
123
+ rows["returns"].append((
124
+ return_id, oid, prod_id, rng.choice(REASONS),
125
+ (day + dt.timedelta(days=rng.randint(3, 30))).isoformat(),
126
+ ))
127
+ return rows
128
+
129
+
130
+ def build(path: str | pathlib.Path, seed: int = 42, **sizes) -> pathlib.Path:
131
+ """Write the sample database to a SQLite file (replacing it)."""
132
+ path = pathlib.Path(path)
133
+ if path.exists():
134
+ path.unlink()
135
+ conn = sqlite3.connect(path)
136
+ conn.executescript(SCHEMA)
137
+ for table, rows in generate(seed, **sizes).items():
138
+ if rows:
139
+ marks = ",".join("?" * len(rows[0]))
140
+ conn.executemany(f"INSERT INTO {table} VALUES ({marks})", rows)
141
+ conn.commit()
142
+ conn.close()
143
+ return path
144
+
145
+
146
+ def build_postgres(url: str, seed: int = 42, **sizes) -> str:
147
+ """Load the sample database into PostgreSQL's public schema (replacing those six tables).
148
+
149
+ Needs a user that may create tables; groundsql itself then connects read-only.
150
+ """
151
+ import psycopg
152
+
153
+ with psycopg.connect(url) as conn, conn.cursor() as cur:
154
+ cur.execute("DROP TABLE IF EXISTS " + ", ".join(reversed(TABLES)) + " CASCADE")
155
+ cur.execute(SCHEMA_POSTGRES)
156
+ for table, rows in generate(seed, **sizes).items():
157
+ if rows:
158
+ marks = ",".join(["%s"] * len(rows[0]))
159
+ cur.executemany(f"INSERT INTO {table} VALUES ({marks})", rows)
160
+ return url
161
+
162
+
163
+ if __name__ == "__main__":
164
+ import sys
165
+
166
+ out = build(sys.argv[1] if len(sys.argv) > 1 else "shop.db")
167
+ print(f"wrote {out}")
groundsql/schema.py ADDED
@@ -0,0 +1,159 @@
1
+ """Database introspection and schema retrieval.
2
+
3
+ The model only ever sees the slice of the schema that is relevant to the
4
+ question: tables whose names, columns or sample values match the question,
5
+ plus their foreign-key neighbours so join paths stay visible.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import sqlite3
12
+ from dataclasses import dataclass, field
13
+
14
+
15
+ @dataclass
16
+ class Column:
17
+ name: str
18
+ type: str
19
+ pk: bool = False
20
+ samples: list[str] = field(default_factory=list)
21
+ complete: bool = False # samples are every distinct value (a categorical column)
22
+
23
+
24
+ @dataclass
25
+ class ForeignKey:
26
+ column: str
27
+ ref_table: str
28
+ ref_column: str
29
+
30
+
31
+ @dataclass
32
+ class Table:
33
+ name: str
34
+ columns: list[Column]
35
+ foreign_keys: list[ForeignKey]
36
+ row_count: int
37
+
38
+ def render(self) -> str:
39
+ lines = [f"TABLE {self.name} ({self.row_count} rows)"]
40
+ for c in self.columns:
41
+ line = f" {c.name} {c.type or 'ANY'}"
42
+ if c.pk:
43
+ line += " PRIMARY KEY"
44
+ if c.samples:
45
+ label = "one of" if c.complete else "e.g."
46
+ line += f" -- {label} " + ", ".join(repr(s) for s in c.samples)
47
+ lines.append(line)
48
+ for fk in self.foreign_keys:
49
+ lines.append(f" FOREIGN KEY {fk.column} -> {fk.ref_table}.{fk.ref_column}")
50
+ return "\n".join(lines)
51
+
52
+
53
+ # A text column with at most this many distinct values is shown in full, most common
54
+ # first: the model must see 'delivered' even when three arbitrary samples would miss it.
55
+ CATEGORICAL_MAX = 10
56
+
57
+
58
+ def pick_samples(column: Column, values: list, sample_values: int) -> None:
59
+ """``values`` are up to CATEGORICAL_MAX + 1 distinct values, most frequent first."""
60
+ column.complete = len(values) <= CATEGORICAL_MAX
61
+ keep = values if column.complete else values[:sample_values]
62
+ column.samples = [str(v)[:40] for v in keep]
63
+
64
+
65
+ def _quote(identifier: str) -> str:
66
+ return '"' + identifier.replace('"', '""') + '"'
67
+
68
+
69
+ def introspect(conn: sqlite3.Connection, sample_values: int = 3) -> dict[str, Table]:
70
+ """Read every user table: columns, keys, row counts and a few sample text values."""
71
+ names = [
72
+ r[0]
73
+ for r in conn.execute(
74
+ "SELECT name FROM sqlite_master WHERE type='table' "
75
+ "AND name NOT LIKE 'sqlite_%' ORDER BY name"
76
+ )
77
+ ]
78
+ tables: dict[str, Table] = {}
79
+ for name in names:
80
+ q = _quote(name)
81
+ columns = []
82
+ for _cid, col, ctype, _notnull, _default, pk in conn.execute(f"PRAGMA table_info({q})"):
83
+ column = Column(name=col, type=(ctype or "").upper(), pk=bool(pk))
84
+ # Sample values ground the model on real spellings ('Electronics', 'shipped').
85
+ if sample_values and ("CHAR" in column.type or column.type in ("TEXT", "")):
86
+ rows = conn.execute(
87
+ f"SELECT {_quote(col)} FROM {q} WHERE {_quote(col)} IS NOT NULL "
88
+ f"GROUP BY 1 ORDER BY COUNT(*) DESC, 1 LIMIT ?",
89
+ (CATEGORICAL_MAX + 1,),
90
+ ).fetchall()
91
+ pick_samples(column, [r[0] for r in rows], sample_values)
92
+ columns.append(column)
93
+ fks = [
94
+ ForeignKey(column=r[3], ref_table=r[2], ref_column=r[4] or "rowid")
95
+ for r in conn.execute(f"PRAGMA foreign_key_list({q})")
96
+ ]
97
+ count = conn.execute(f"SELECT COUNT(*) FROM {q}").fetchone()[0]
98
+ tables[name] = Table(name=name, columns=columns, foreign_keys=fks, row_count=count)
99
+ return tables
100
+
101
+
102
+ _WORD = re.compile(r"[a-z0-9]+")
103
+ _STOP = {
104
+ "the", "a", "an", "of", "in", "on", "for", "to", "by", "and", "or", "with", "is",
105
+ "are", "was", "were", "what", "which", "who", "how", "many", "much", "show", "me",
106
+ "list", "give", "all", "each", "per", "top", "most", "least", "number", "total",
107
+ "id", "name", "from", "that", "have", "has", "did", "do", "does", "their", "its",
108
+ }
109
+
110
+
111
+ def _stem(word: str) -> str:
112
+ for suffix in ("ies", "es", "s"):
113
+ if word.endswith(suffix) and len(word) - len(suffix) >= 3:
114
+ return word[: -len(suffix)] + ("y" if suffix == "ies" else "")
115
+ return word
116
+
117
+
118
+ def tokens(text: str) -> set[str]:
119
+ """Lower-case word stems; splits snake_case and camelCase identifiers."""
120
+ text = re.sub(r"([a-z])([A-Z])", r"\1 \2", text).replace("_", " ").lower()
121
+ return {_stem(w) for w in _WORD.findall(text) if w not in _STOP}
122
+
123
+
124
+ def score_tables(question: str, tables: dict[str, Table]) -> dict[str, float]:
125
+ q = tokens(question)
126
+ scores = {}
127
+ for t in tables.values():
128
+ s = 3.0 * len(q & tokens(t.name))
129
+ for c in t.columns:
130
+ s += 1.0 * len(q & tokens(c.name))
131
+ for v in c.samples:
132
+ s += 2.0 * len(q & tokens(v))
133
+ scores[t.name] = s
134
+ return scores
135
+
136
+
137
+ def relevant_tables(question: str, tables: dict[str, Table], top_k: int = 4) -> list[Table]:
138
+ """Best-matching tables plus their foreign-key neighbours.
139
+
140
+ Falls back to the whole schema when the database is small or nothing matches,
141
+ because a missing table is a worse failure than a slightly longer prompt.
142
+ """
143
+ if len(tables) <= top_k:
144
+ return list(tables.values())
145
+ scores = score_tables(question, tables)
146
+ ranked = [n for n in sorted(scores, key=lambda n: (-scores[n], n)) if scores[n] > 0]
147
+ if not ranked:
148
+ return list(tables.values())
149
+ chosen = ranked[:top_k]
150
+ # Pull in join partners in both directions so the model can see the path.
151
+ for name in list(chosen):
152
+ for fk in tables[name].foreign_keys:
153
+ if fk.ref_table in tables and fk.ref_table not in chosen:
154
+ chosen.append(fk.ref_table)
155
+ for other in tables.values():
156
+ if other.name not in chosen and any(fk.ref_table == name for fk in other.foreign_keys):
157
+ if scores.get(other.name, 0) > 0:
158
+ chosen.append(other.name)
159
+ return [tables[n] for n in chosen]
groundsql/spider.py ADDED
@@ -0,0 +1,137 @@
1
+ """Spider benchmark (Yu et al., 2018): execution accuracy on a sample of the dev set.
2
+
3
+ Spider's dev databases are ones no training question used, so a score here says how
4
+ well the agent handles a schema it has never seen. The data is CC BY-SA 4.0 and is not
5
+ shipped with groundsql: ``fetch()`` downloads a checksum-pinned mirror of the Yale
6
+ release (about 206 MB) once into the cache, and extracts only what the dev set needs.
7
+
8
+ Scoring matches the rest of groundsql: the agent's result set must equal the gold
9
+ query's result set, ignoring row order and float noise and allowing extra columns.
10
+ That is a little more lenient than Spider's official order-sensitive comparison for
11
+ gold queries with ORDER BY; the report says so.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import pathlib
20
+ import random
21
+ import re
22
+ import sys
23
+ import urllib.request
24
+ import zipfile
25
+
26
+ from .agent import Agent
27
+ from .db import SQLiteDatabase
28
+ from .evals import Case, run_eval
29
+ from .llm import LLM
30
+
31
+ SPIDER_URL = "https://huggingface.co/datasets/HAL-9001/spider-databases/resolve/main/spider_data.zip"
32
+ SPIDER_SHA256 = "00636695dabed6b5f4b8328a16b13e069a2f16591d5efcce57660669c85b121b"
33
+ CITATION = ("Yu et al., Spider: A Large-Scale Human-Labeled Dataset for Complex and Cross-Domain "
34
+ "Semantic Parsing and Text-to-SQL Task, EMNLP 2018. CC BY-SA 4.0.")
35
+
36
+
37
+ def cache_dir() -> pathlib.Path:
38
+ return pathlib.Path(os.environ.get("GROUNDSQL_CACHE", pathlib.Path.home() / ".cache" / "groundsql"))
39
+
40
+
41
+ def _sha256(path: pathlib.Path) -> str:
42
+ h = hashlib.sha256()
43
+ with open(path, "rb") as f:
44
+ for block in iter(lambda: f.read(1 << 20), b""):
45
+ h.update(block)
46
+ return h.hexdigest()
47
+
48
+
49
+ def fetch(quiet: bool = False) -> pathlib.Path:
50
+ """Download (once), verify and extract the dev split. Returns the spider_data folder."""
51
+ root = cache_dir()
52
+ out = root / "spider_data"
53
+ if (out / "dev.json").exists():
54
+ return out
55
+ root.mkdir(parents=True, exist_ok=True)
56
+ archive = root / "spider_data.zip"
57
+ if not archive.exists():
58
+ if not quiet:
59
+ print(f"downloading Spider (~206 MB) to {archive}", file=sys.stderr)
60
+ tmp = archive.with_suffix(".part")
61
+ urllib.request.urlretrieve(SPIDER_URL, tmp)
62
+ tmp.replace(archive)
63
+ digest = _sha256(archive)
64
+ if digest != SPIDER_SHA256:
65
+ raise RuntimeError(f"{archive} has sha256 {digest}, expected {SPIDER_SHA256}; delete it and retry")
66
+ with zipfile.ZipFile(archive) as z:
67
+ dev = json.loads(z.read("spider_data/dev.json"))
68
+ wanted = {"spider_data/dev.json"} | {
69
+ f"spider_data/database/{d}/{d}.sqlite" for d in {q["db_id"] for q in dev}}
70
+ for name in wanted:
71
+ z.extract(name, root)
72
+ return out
73
+
74
+
75
+ def _level(sql: str) -> str:
76
+ """A rough difficulty bucket from the gold SQL's shape (not Spider's official hardness)."""
77
+ s = sql.upper()
78
+ if re.search(r"\b(INTERSECT|UNION|EXCEPT)\b", s) or s.count("SELECT") > 1:
79
+ return "nested/set"
80
+ if " JOIN " in s:
81
+ return "join"
82
+ return "single-table"
83
+
84
+
85
+ def load_dev(n: int | None = 100, seed: int = 0) -> list[tuple[str, Case]]:
86
+ """A reproducible random sample of the dev set: (db_id, Case) pairs."""
87
+ data = json.loads((fetch() / "dev.json").read_text(encoding="utf-8"))
88
+ idx = list(range(len(data)))
89
+ if n is not None and n < len(idx):
90
+ idx = sorted(random.Random(seed).sample(idx, n))
91
+ return [
92
+ (data[i]["db_id"], Case(id=f"dev{i:04d}", level=_level(data[i]["query"]),
93
+ question=data[i]["question"], gold=data[i]["query"]))
94
+ for i in idx
95
+ ]
96
+
97
+
98
+ def run_spider(llm: LLM, n: int | None = 100, seed: int = 0, max_repairs: int = 2,
99
+ progress=None) -> dict:
100
+ root = fetch()
101
+ by_db: dict[str, list[Case]] = {}
102
+ for db_id, case in load_dev(n, seed):
103
+ by_db.setdefault(db_id, []).append(case)
104
+
105
+ results, skipped = [], []
106
+ for db_id, cases in sorted(by_db.items()):
107
+ db = SQLiteDatabase(root / "database" / db_id / f"{db_id}.sqlite", max_rows=10_000)
108
+ try:
109
+ part = run_eval(Agent(db, llm, max_repairs=max_repairs), cases)
110
+ finally:
111
+ db.close()
112
+ skipped += [dict(s, db_id=db_id) for s in part["skipped"]]
113
+ for r in part["results"]:
114
+ r["db_id"] = db_id
115
+ results.append(r)
116
+ if progress:
117
+ progress(r)
118
+
119
+ results.sort(key=lambda r: r["id"])
120
+ total = len(results)
121
+ by_level: dict[str, list[bool]] = {}
122
+ for r in results:
123
+ by_level.setdefault(r["level"], []).append(r["passed"])
124
+ return {
125
+ "benchmark": "spider-dev",
126
+ "model": llm.name,
127
+ "sample": {"n": total, "seed": seed, "of": 1034, "databases": len(by_db)},
128
+ "max_repairs": max_repairs,
129
+ "execution_accuracy": round(sum(r["passed"] for r in results) / total, 3) if total else 0.0,
130
+ "valid_sql_rate": round(sum(r["sql"] is not None for r in results) / total, 3) if total else 0.0,
131
+ "by_level": {k: f"{sum(v)}/{len(v)}" for k, v in sorted(by_level.items())},
132
+ "repaired_and_passed": sum(r["repaired"] and r["passed"] for r in results),
133
+ "skipped": skipped,
134
+ "scoring": "result-set match, order-insensitive, floats to 2 dp, extra columns allowed",
135
+ "data": {"url": SPIDER_URL, "sha256": SPIDER_SHA256, "citation": CITATION},
136
+ "results": results,
137
+ }
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: groundsql
3
+ Version: 0.2.1
4
+ Summary: Schema-grounded, read-only Text-to-SQL agent for SQLite and PostgreSQL: repair loop, layered SQL safety, execution-accuracy evals (incl. Spider), MCP server.
5
+ Author-email: Aryan Sinha <aryan.sinha1212@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/aryansinha16/groundsql
8
+ Project-URL: Issues, https://github.com/aryansinha16/groundsql/issues
9
+ Keywords: text-to-sql,llm,agents,mcp,sqlite,postgresql,evals,spider
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: postgres
20
+ Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7; extra == "dev"
23
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # groundsql
27
+
28
+ [![tests](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml/badge.svg)](https://github.com/aryansinha16/groundsql/actions/workflows/tests.yml)
29
+
30
+ **Ask a SQLite or PostgreSQL database questions in plain English, safely.** A schema-grounded Text-to-SQL agent with a repair loop, layered read-only safety, execution-accuracy evals (including the Spider benchmark), and an MCP server for Claude, Cursor or any MCP client.
31
+
32
+ **79% execution accuracy on a 100-question sample of Spider dev** with `gpt-oss-120b`, and 15/15 on the built-in eval on both SQLite and PostgreSQL ([results](#evals)).
33
+
34
+ Zero runtime dependencies for SQLite: standard library only, any LLM (Ollama, Groq, OpenAI-compatible, Anthropic) over plain HTTP. PostgreSQL adds `psycopg`.
35
+
36
+ ```
37
+ $ groundsql ask --db shop.db --model ollama:llama3.2:1b "How many customers are based in India?"
38
+ SELECT COUNT(*)
39
+ FROM customers AS T1
40
+ WHERE country = 'India'
41
+
42
+ COUNT(*)
43
+ --------
44
+ 98
45
+ ```
46
+
47
+ ## Why
48
+
49
+ Text-to-SQL demos break in production in three predictable ways. Each one has a mechanism here:
50
+
51
+ | Failure | What groundsql does |
52
+ |---|---|
53
+ | The model invents tables or columns | **Schema grounding**: the prompt holds only the relevant tables (matched on table names, column names *and sample values*), plus their foreign-key neighbours so join paths stay visible. Low-cardinality text columns list *every* value (`status TEXT -- one of 'delivered', 'shipped', ...`), so the model never guesses a spelling |
54
+ | The query is wrong but plausible | **Repair loop**: the database compiles the query with `EXPLAIN` before it runs, and the exact error (`no such column: revenue`) goes back to the model. If retrieval missed a table, the repair turn gets the full schema |
55
+ | The query is dangerous | **Four independent safety gates** (below). Writes are impossible, not just discouraged |
56
+
57
+ And one rule from running this kind of system for real: **the model writes SQL, the database computes every number.** The answer is the result set, never a model-written summary of it, so totals can't be hallucinated.
58
+
59
+ ## Safety gates
60
+
61
+ Every query passes all four:
62
+
63
+ 1. **Static check**: exactly one statement, starting `SELECT`/`WITH`, no write/DDL keywords outside string literals (`SELECT 'drop table'` is fine, `SELECT 1; DROP TABLE x` is not). Comments and literals are parsed in one pass, so `--` inside a string is text, not a comment
64
+ 2. **Read-only connection**: `mode=ro`, so SQLite itself refuses writes
65
+ 3. **Authorizer callback**: only read actions are allowed, even if something slipped past gate 1
66
+ 4. **Compile before run**: `EXPLAIN` validates names first; execution then has a wall-clock timeout (a runaway recursive CTE is killed), a row cap, and on SQLite a 10 MB cap on any single value (so `SELECT randomblob(1e9)` fails instead of allocating a gigabyte)
67
+
68
+ The tests bypass gate 1 deliberately to prove gates 2 and 3 still hold.
69
+
70
+ On **PostgreSQL** the same four, in Postgres terms: the static check plus a blocklist of side-effecting functions a read-only transaction would still allow (`pg_sleep`, `pg_terminate_backend`, `pg_read_file`, `dblink`, `set_config`, `nextval`...); a session with `default_transaction_read_only=on` and every query in a transaction that is always rolled back; `statement_timeout` on the server; and `EXPLAIN` first. For defence in depth, connect as a role that only has `SELECT`.
71
+
72
+ ## Quick start
73
+
74
+ ```bash
75
+ pip install -e . # or: pip install -e ".[postgres]"
76
+ groundsql sample shop.db # deterministic 6-table retail database
77
+
78
+ # any of these model specs work
79
+ groundsql ask --db shop.db --model ollama:llama3.2 "How many orders were cancelled?"
80
+ groundsql ask --db shop.db --model groq:openai/gpt-oss-120b "Revenue per category for delivered orders"
81
+ groundsql ask --db shop.db --model anthropic:claude-sonnet-4-6 "Top 3 most returned products" --json
82
+
83
+ groundsql sql --db shop.db "SELECT channel, COUNT(*) FROM orders GROUP BY channel" # safety gates, no LLM
84
+ groundsql schema --db shop.db "revenue from Footwear" # what the model will see
85
+
86
+ # PostgreSQL: any --db that is a postgresql:// URL
87
+ groundsql sample --postgres postgresql://admin@localhost/shop # load the same data (needs CREATE)
88
+ groundsql ask --db postgresql://readonly@localhost/shop "How many orders were cancelled?"
89
+ ```
90
+
91
+ Keys come from `GROQ_API_KEY`, `OPENAI_API_KEY` (+ optional `OPENAI_BASE_URL`), `ANTHROPIC_API_KEY`; Ollama needs none. A `.env` file in the working directory is read too (git-ignored), and shell variables win over it. Rate limits (HTTP 429/5xx) are retried with backoff.
92
+
93
+ ## MCP server
94
+
95
+ ```bash
96
+ groundsql serve --db shop.db # tools: list_tables, describe_table, run_sql
97
+ groundsql serve --db shop.db --model ollama:llama3.2 # + ask
98
+ ```
99
+
100
+ Claude Desktop / Claude Code config:
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "shop-db": { "command": "groundsql", "args": ["serve", "--db", "/path/to/shop.db"] }
106
+ }
107
+ }
108
+ ```
109
+
110
+ The server is a small, dependency-free JSON-RPC 2.0 implementation of the MCP stdio transport (`initialize`, `tools/list`, `tools/call`, `ping`). `run_sql` goes through the same four safety gates, so an MCP client can't write to the database either.
111
+
112
+ ## Evals
113
+
114
+ Scoring everywhere is **execution accuracy**: does the agent's result set equal the gold query's result set? Row order and float noise are ignored, and extra columns are allowed (returning `city, count` when only `city` was asked still passes). Every number below comes from a JSON report in [`evals/results/`](evals/results) with the exact SQL the model wrote for each question. Models ran at temperature 0, with the default 2 repairs unless noted.
115
+
116
+ ### Spider (cross-domain, unseen schemas)
117
+
118
+ [Spider](https://yale-lily.github.io/spider) dev uses 20 databases that no training question touched, so it measures how well the agent copes with a schema it has never seen. `groundsql spider` downloads a checksum-pinned copy once (about 206 MB, CC BY-SA 4.0, not shipped in this repo) and samples questions with a fixed seed.
119
+
120
+ ```bash
121
+ groundsql spider --n 100 --seed 0 --model groq:openai/gpt-oss-120b --out evals/results/spider-dev-100-gpt-oss-120b.json
122
+ ```
123
+
124
+ 100 questions over 19 databases (seed 0):
125
+
126
+ | Model | Execution accuracy | Valid SQL | single-table | join | nested / set ops |
127
+ |---|---|---|---|---|---|
128
+ | `gpt-oss-120b` (Groq) | **79%** | 100% | 40/45 | 27/40 | 12/15 |
129
+ | `gpt-oss-120b`, `--repairs 0` | 76% | 100% | 38/45 | 26/40 | 12/15 |
130
+ | Llama 3.2 1B (Ollama, laptop) | 35% | 62% | 24/45 | 11/40 | 0/15 |
131
+
132
+ How to read this, honestly:
133
+
134
+ - **The big model never needed a repair**: every first query compiled. The 79% vs 76% gap is run-to-run variation of a hosted model, not the repair loop. The repair loop earns its keep on small models: 9 of Llama 1B's 100 questions went through a repair, and 5 of those then passed.
135
+ - **Joins look like the weak spot (27/40), but most of those misses are not wrong SQL.** I read all 13 by hand and checked the data:
136
+
137
+ | Why it was scored wrong | Count | Example |
138
+ |---|---|---|
139
+ | The gold answer is wrong | 2 | `flight_2`: cities are stored as `'Aberdeen '` (trailing space), so the gold `City = "Aberdeen"` returns 0 flights; the agent matched the real value |
140
+ | A tie under `LIMIT 1` | 3 | `orchestra`: every conductor leads exactly one orchestra, so "the conductor with the most" is any of them |
141
+ | A defensible reading that differs from the benchmark's | 7 | `LEFT JOIN` keeps shops with 0 employees; in `car_1`, `Model` holds the brand (`'ford'`) and `Make` holds the model (`'ford pinto'`) |
142
+ | A real mistake | 1 | `student_transcripts_tracking`: counted per student and semester instead of per student |
143
+
144
+ I tried prompt rules aimed at these conventions (inner joins by default, prefer the column named in the question). Accuracy stayed at 79% on this sample and on a fresh held-out sample (seed 1, 79% before and after), and the model ignored the rules. So that change was not shipped.
145
+ - **This is a sample, not the official leaderboard.** It is 100 of 1,034 dev questions, the difficulty buckets come from the gold SQL's shape (not Spider's official hardness), and the comparison is order-insensitive, which is a little more lenient than Spider's official evaluator for `ORDER BY` questions. Run `--n 0` for the full dev set.
146
+
147
+ ### Built-in eval (sample retail database)
148
+
149
+ `groundsql/data/questions.jsonl` has 15 questions (easy / medium / hard: filters, joins, multi-hop aggregates, anti-joins) with gold SQL, run against the deterministic sample database.
150
+
151
+ ```bash
152
+ groundsql eval --db shop.db --model groq:openai/gpt-oss-120b
153
+ groundsql eval --db postgresql://localhost/shop --model groq:openai/gpt-oss-120b # same questions on Postgres
154
+ ```
155
+
156
+ | Model | Database | Execution accuracy | Valid SQL | easy | medium | hard |
157
+ |---|---|---|---|---|---|---|
158
+ | `gpt-oss-120b` | SQLite | **100%** | 100% | 4/4 | 6/6 | 5/5 |
159
+ | `gpt-oss-120b` | PostgreSQL 18 | **100%** | 100% | 4/4 | 6/6 | 5/5 |
160
+ | Llama 3.2 1B | SQLite | 33% | 53% | 3/4 | 1/6 | 1/5 |
161
+ | Llama 3.2 1B, `--repairs 0` | SQLite | 33% | 40% | 3/4 | 1/6 | 1/5 |
162
+
163
+ The PostgreSQL row found a real grounding bug. With three arbitrary sample values per column, Postgres happened to show `status` as `'cancelled', 'shipped', 'processing'`, so the model filtered "delivered" orders on `'shipped'` and scored 80%. Now low-cardinality columns list every value, most common first, and both databases score 15/15. The 1B model went from 40% to 33% between versions; at that size, small prompt changes move single questions either way.
164
+
165
+ Two eval design choices worth copying: questions with a `LIMIT 1` answer also ask for the count, so a wrong query can't pass by landing on the same top row; and no gold answer is zero, so a wrong filter can't pass by accident.
166
+
167
+ ## Layout
168
+
169
+ ```
170
+ groundsql/
171
+ schema.py introspection, sample values, table retrieval + FK expansion
172
+ db.py SQLite backend, the shared static check, open_database()
173
+ postgres.py PostgreSQL backend: read-only session, function blocklist, statement_timeout
174
+ agent.py dialect-aware prompt, SQL extraction, repair loop, CANNOT_ANSWER handling
175
+ llm.py Ollama / Groq / OpenAI-compatible / Anthropic over urllib, retries, + Scripted for tests
176
+ mcp_server.py MCP stdio server
177
+ evals.py execution-accuracy scoring
178
+ spider.py Spider download (checksum-pinned), sampling, scoring
179
+ sample.py deterministic sample database, SQLite or PostgreSQL
180
+ tests/ 55 tests: safety gates, retrieval, repair loop, evals, Spider runner, MCP over a
181
+ real subprocess; the 15 PostgreSQL tests run against a real server in CI
182
+ ```
183
+
184
+ ```bash
185
+ pip install -e ".[dev]" && pytest -q
186
+ GROUNDSQL_TEST_PG=postgresql://postgres@localhost/postgres pytest -q # include PostgreSQL
187
+ ```
188
+
189
+ ## License
190
+
191
+ MIT
@@ -0,0 +1,19 @@
1
+ groundsql/__init__.py,sha256=i2xFY-j8gFyLO8aY2TucFGWI3QxhOzpgVC9_-7TbT78,453
2
+ groundsql/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ groundsql/agent.py,sha256=HRiJMzqQgb8SK-e2LcYCgaVIU62hD5i7DU8VTj-EO2U,5460
4
+ groundsql/cli.py,sha256=lfN5Pbe8VD1J_NlAChVjMoNTRffpmyKaQorbpqpVUVo,7197
5
+ groundsql/db.py,sha256=7wGrvKC9v46GnhsRFdWXCWabIIS5B-MqLLXrzJ-gnLE,8898
6
+ groundsql/evals.py,sha256=dvGQzJ0EqJyV5BPHJkkhI2T5N2qashi6Y0_iVK4Q4ns,3788
7
+ groundsql/llm.py,sha256=dnbQxD7PArMxJXgiPsz1zaywLiaqEgvzeJOOik_SDGU,5025
8
+ groundsql/mcp_server.py,sha256=3jFUZIbrVi2HkBfVnMihH4VP0-mRj-L6DbKpL8RdMTs,5206
9
+ groundsql/postgres.py,sha256=1uEWT0-rCxg4b9ImeumiCHoivGJQfnBFn2-DzVxWjJc,7552
10
+ groundsql/sample.py,sha256=oy05WMcC0pK-3Z0nw0FQ-TVHxATcwcKn4n-h9tfH9ak,6678
11
+ groundsql/schema.py,sha256=ZNNDbykhU0rHb_YcU5KpQM7mpFkfRjx8Z2zThqD6lGA,5983
12
+ groundsql/spider.py,sha256=B2bGjQOonlcUim0ySVYLgCMaMZifSuxQujYaabqaKcE,5464
13
+ groundsql/data/questions.jsonl,sha256=vuHWRDpR60PHzWD-dhLNx0WrdBspNctyOCflxk6-wcw,3577
14
+ groundsql-0.2.1.dist-info/licenses/LICENSE,sha256=IFAjTcNDr1W4gLJ9nJQygFe9DOUvougfN7ym_4rNS5Q,1068
15
+ groundsql-0.2.1.dist-info/METADATA,sha256=9p_bN24rP_2T2YOUx7bbeghCt8NaTN9tdIFMvgzrOEM,11947
16
+ groundsql-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ groundsql-0.2.1.dist-info/entry_points.txt,sha256=Iq_4E_RTRzpuG1ius5r59x_k-EfFdfG3SxbBoIE2kcA,49
18
+ groundsql-0.2.1.dist-info/top_level.txt,sha256=UwzlLu5_kEuC5GJMHnM53q68Bz9r9_YvQtlz0hqn0ms,10
19
+ groundsql-0.2.1.dist-info/RECORD,,