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/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """groundsql: schema-grounded, read-only Text-to-SQL agent with an MCP server."""
2
+
3
+ __version__ = "0.2.1"
4
+
5
+ from .agent import Agent, Answer, format_table # noqa: E402
6
+ from .db import ( # noqa: E402
7
+ BaseDatabase, Database, InvalidSQL, SQLError, SQLiteDatabase, UnsafeSQL, open_database,
8
+ )
9
+
10
+ __all__ = [
11
+ "Agent", "Answer", "BaseDatabase", "Database", "InvalidSQL", "SQLError", "SQLiteDatabase",
12
+ "UnsafeSQL", "format_table", "open_database",
13
+ ]
groundsql/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
groundsql/agent.py ADDED
@@ -0,0 +1,147 @@
1
+ """Question -> SQL -> rows, with schema grounding and a bounded repair loop.
2
+
3
+ Design rule: the model writes SQL, the database computes every number. The answer is
4
+ the result set itself, never a model-written summary of it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import time
11
+ from dataclasses import dataclass, field
12
+
13
+ from .db import BaseDatabase, Result, SQLError
14
+ from .llm import LLM
15
+
16
+ SYSTEM_PROMPT = """You translate a question into ONE {dialect} query.
17
+
18
+ Rules:
19
+ - Use only the tables and columns in the schema you are given. Never invent names.
20
+ - Read-only: a single SELECT (CTEs allowed). No INSERT/UPDATE/DELETE/DDL/PRAGMA.
21
+ - Match text values exactly as they appear in the schema samples.
22
+ - Give computed columns short descriptive aliases.
23
+ - Prefer explicit JOIN ... ON using the listed foreign keys.
24
+ - If the question cannot be answered from this schema, reply with exactly: CANNOT_ANSWER
25
+
26
+ Reply with the query in a ```sql code block and nothing else."""
27
+
28
+ _FENCE = re.compile(r"```(?:sql|sqlite)?\s*(.*?)```", re.DOTALL | re.IGNORECASE)
29
+ _BARE = re.compile(r"\b(SELECT|WITH)\b.*", re.DOTALL | re.IGNORECASE)
30
+
31
+
32
+ def extract_sql(text: str) -> str | None:
33
+ """Pull the query out of a model reply. Returns None for CANNOT_ANSWER."""
34
+ if "CANNOT_ANSWER" in text:
35
+ return None
36
+ m = _FENCE.search(text)
37
+ if m:
38
+ return m.group(1).strip()
39
+ m = _BARE.search(text)
40
+ return m.group(0).strip() if m else text.strip()
41
+
42
+
43
+ @dataclass
44
+ class Attempt:
45
+ sql: str | None
46
+ error: str | None
47
+
48
+
49
+ @dataclass
50
+ class Answer:
51
+ question: str
52
+ result: Result | None
53
+ attempts: list[Attempt] = field(default_factory=list)
54
+ tables_shown: list[str] = field(default_factory=list)
55
+ elapsed_ms: float = 0.0
56
+ error: str | None = None
57
+
58
+ @property
59
+ def ok(self) -> bool:
60
+ return self.result is not None
61
+
62
+ @property
63
+ def sql(self) -> str | None:
64
+ return self.result.sql if self.result else None
65
+
66
+ def as_dict(self) -> dict:
67
+ r = self.result
68
+ return {
69
+ "question": self.question,
70
+ "ok": self.ok,
71
+ "sql": self.sql,
72
+ "columns": r.columns if r else [],
73
+ "rows": [list(row) for row in r.rows] if r else [],
74
+ "truncated": r.truncated if r else False,
75
+ "attempts": [a.__dict__ for a in self.attempts],
76
+ "tables_shown": self.tables_shown,
77
+ "elapsed_ms": round(self.elapsed_ms, 1),
78
+ "error": self.error,
79
+ }
80
+
81
+
82
+ class AgentError(RuntimeError):
83
+ pass
84
+
85
+
86
+ class Agent:
87
+ def __init__(self, db: BaseDatabase, llm: LLM, max_repairs: int = 2, top_k: int = 4):
88
+ self.db = db
89
+ self.llm = llm
90
+ self.max_repairs = max_repairs
91
+ self.top_k = top_k
92
+
93
+ def ask(self, question: str) -> Answer:
94
+ start = time.perf_counter()
95
+ tables = self.db.relevant_tables(question, self.top_k)
96
+ shown = {t.name for t in tables}
97
+ answer = Answer(question=question, result=None, tables_shown=sorted(shown))
98
+ messages = [{
99
+ "role": "user",
100
+ "content": f"Schema:\n{self.db.schema_text(tables)}\n\nQuestion: {question}",
101
+ }]
102
+
103
+ for _ in range(self.max_repairs + 1):
104
+ reply = self.llm.complete(SYSTEM_PROMPT.format(dialect=self.db.dialect), messages)
105
+ sql = extract_sql(reply)
106
+ if sql is None:
107
+ answer.attempts.append(Attempt(sql=None, error="model said CANNOT_ANSWER"))
108
+ answer.error = "the model could not answer this from the schema"
109
+ break
110
+ try:
111
+ answer.result = self.db.run(sql)
112
+ answer.attempts.append(Attempt(sql=answer.result.sql, error=None))
113
+ break
114
+ except SQLError as e:
115
+ answer.attempts.append(Attempt(sql=sql, error=str(e)))
116
+ feedback = f"That query failed: {e}\nFix it and reply with the corrected query."
117
+ # Retrieval can miss a table; on a 'no such table/column' error,
118
+ # show the full schema so the repair has what it needs.
119
+ if "no such" in str(e) and len(shown) < len(self.db.tables):
120
+ shown = set(self.db.tables)
121
+ answer.tables_shown = sorted(shown)
122
+ feedback += f"\n\nFull schema:\n{self.db.schema_text()}"
123
+ messages += [
124
+ {"role": "assistant", "content": reply},
125
+ {"role": "user", "content": feedback},
126
+ ]
127
+ else:
128
+ answer.error = f"no valid query after {len(answer.attempts)} attempts"
129
+
130
+ answer.elapsed_ms = (time.perf_counter() - start) * 1000
131
+ return answer
132
+
133
+
134
+ def format_table(result: Result, max_width: int = 40) -> str:
135
+ """Plain-text table for terminals."""
136
+ def cell(v) -> str:
137
+ s = "NULL" if v is None else (f"{v:,.2f}" if isinstance(v, float) else str(v))
138
+ return s if len(s) <= max_width else s[: max_width - 1] + "…"
139
+
140
+ header = [cell(c) for c in result.columns]
141
+ body = [[cell(v) for v in row] for row in result.rows]
142
+ widths = [max(len(r[i]) for r in [header, *body]) for i in range(len(header))]
143
+ line = lambda r: " ".join(v.ljust(w) for v, w in zip(r, widths)) # noqa: E731
144
+ out = [line(header), " ".join("-" * w for w in widths), *map(line, body)]
145
+ if result.truncated:
146
+ out.append(f"... truncated at {len(result.rows)} rows")
147
+ return "\n".join(out)
groundsql/cli.py ADDED
@@ -0,0 +1,203 @@
1
+ """Command line: groundsql {ask,sql,schema,serve,eval,spider,sample}."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import pathlib
9
+ import sys
10
+
11
+ from .agent import Agent, format_table
12
+ from .db import SQLError, open_database
13
+ from .llm import LLMError, from_spec
14
+
15
+ DEFAULT_MODEL = "ollama:llama3.2"
16
+ BUILTIN_CASES = pathlib.Path(__file__).with_name("data") / "questions.jsonl"
17
+
18
+
19
+ def load_dotenv(path: str | pathlib.Path = ".env") -> None:
20
+ """Read KEY=value lines from ./.env into the environment (existing variables win).
21
+
22
+ Lets you keep GROQ_API_KEY and friends in a git-ignored file instead of the shell.
23
+ """
24
+ p = pathlib.Path(path)
25
+ if not p.is_file():
26
+ return
27
+ for line in p.read_text(encoding="utf-8-sig").splitlines():
28
+ line = line.strip()
29
+ if not line or line.startswith("#") or "=" not in line:
30
+ continue
31
+ if line.startswith("export "):
32
+ line = line[len("export "):]
33
+ key, _, value = line.partition("=")
34
+ os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
35
+
36
+
37
+ def _agent(args) -> Agent:
38
+ return Agent(open_database(args.db), from_spec(args.model), max_repairs=args.repairs)
39
+
40
+
41
+ def _write_report(report: dict, out: str | None) -> None:
42
+ if out:
43
+ pathlib.Path(out).parent.mkdir(parents=True, exist_ok=True)
44
+ pathlib.Path(out).write_text(json.dumps(report, indent=2, default=str), encoding="utf-8")
45
+ print(f"report -> {out}")
46
+
47
+
48
+ def _print_result(r: dict) -> None:
49
+ mark = "PASS" if r["passed"] else "FAIL"
50
+ note = " (repaired)" if r["repaired"] else ""
51
+ where = f" {r['db_id']}" if "db_id" in r else ""
52
+ print(f"{mark} {r['id']}{where} [{r['level']}] {r['question']}{note}", flush=True)
53
+
54
+
55
+ def _summary(report: dict) -> str:
56
+ return (f"{report['model']}: execution accuracy {report['execution_accuracy']:.0%} "
57
+ f"({report['by_level']}), valid SQL {report['valid_sql_rate']:.0%}, "
58
+ f"{report['repaired_and_passed']} passed after repair")
59
+
60
+
61
+ def cmd_ask(args) -> int:
62
+ answer = _agent(args).ask(args.question)
63
+ if args.json:
64
+ print(json.dumps(answer.as_dict(), indent=2, default=str))
65
+ return 0 if answer.ok else 1
66
+ for i, a in enumerate(answer.attempts, 1):
67
+ if a.error:
68
+ print(f"[attempt {i}] rejected: {a.error}", file=sys.stderr)
69
+ if answer.result is None:
70
+ print(f"error: {answer.error}", file=sys.stderr)
71
+ return 1
72
+ print(answer.sql, end="\n\n")
73
+ print(format_table(answer.result))
74
+ return 0
75
+
76
+
77
+ def cmd_sql(args) -> int:
78
+ try:
79
+ print(format_table(open_database(args.db).run(args.query)))
80
+ return 0
81
+ except SQLError as e:
82
+ print(f"rejected: {e}", file=sys.stderr)
83
+ return 1
84
+
85
+
86
+ def cmd_schema(args) -> int:
87
+ db = open_database(args.db)
88
+ tables = db.relevant_tables(args.question) if args.question else None
89
+ print(db.schema_text(tables))
90
+ return 0
91
+
92
+
93
+ def cmd_serve(args) -> int:
94
+ from .mcp_server import MCPServer
95
+
96
+ db = open_database(args.db)
97
+ agent = Agent(db, from_spec(args.model), max_repairs=args.repairs) if args.model else None
98
+ MCPServer(db, agent).serve()
99
+ return 0
100
+
101
+
102
+ def cmd_eval(args) -> int:
103
+ from .evals import load_cases, run_eval
104
+
105
+ report = run_eval(_agent(args), load_cases(args.cases))
106
+ for r in report["results"]:
107
+ _print_result(r)
108
+ if not r["passed"]:
109
+ print(f" sql: {r['sql']}\n err: {r['error']}")
110
+ print("\n" + _summary(report))
111
+ _write_report(report, args.out)
112
+ return 0
113
+
114
+
115
+ def cmd_spider(args) -> int:
116
+ from .spider import run_spider
117
+
118
+ report = run_spider(from_spec(args.model), n=args.n or None, seed=args.seed,
119
+ max_repairs=args.repairs, progress=_print_result)
120
+ print(f"\nSpider dev, {report['sample']['n']} questions over {report['sample']['databases']} "
121
+ f"databases (seed {args.seed})")
122
+ print(_summary(report))
123
+ if report["skipped"]:
124
+ print(f"{len(report['skipped'])} skipped: gold query rejected by the safety gates")
125
+ _write_report(report, args.out)
126
+ return 0
127
+
128
+
129
+ def cmd_sample(args) -> int:
130
+ if args.postgres:
131
+ from .sample import build_postgres
132
+
133
+ build_postgres(args.postgres)
134
+ print("loaded the sample tables into PostgreSQL")
135
+ return 0
136
+ from .sample import build
137
+
138
+ print(f"wrote {build(args.path)}")
139
+ return 0
140
+
141
+
142
+ def main(argv: list[str] | None = None) -> int:
143
+ load_dotenv()
144
+ p = argparse.ArgumentParser(prog="groundsql", description=__doc__)
145
+ sub = p.add_subparsers(dest="cmd", required=True)
146
+ db_help = "a SQLite file, or postgresql://user:pass@host/db"
147
+
148
+ def with_model(sp, model_default: str | None = DEFAULT_MODEL):
149
+ sp.add_argument("--model", default=model_default,
150
+ help="provider:model, e.g. ollama:llama3.2, groq:openai/gpt-oss-120b, "
151
+ "anthropic:claude-sonnet-4-6")
152
+ sp.add_argument("--repairs", type=int, default=2, help="max repair attempts (default 2)")
153
+ return sp
154
+
155
+ def with_db(sp, model_default: str | None = DEFAULT_MODEL):
156
+ sp.add_argument("--db", required=True, help=db_help)
157
+ return with_model(sp, model_default)
158
+
159
+ s = with_db(sub.add_parser("ask", help="ask a question in plain English"))
160
+ s.add_argument("question")
161
+ s.add_argument("--json", action="store_true")
162
+ s.set_defaults(fn=cmd_ask)
163
+
164
+ s = sub.add_parser("sql", help="run a read-only query through the safety gates")
165
+ s.add_argument("--db", required=True, help=db_help)
166
+ s.add_argument("query")
167
+ s.set_defaults(fn=cmd_sql)
168
+
169
+ s = sub.add_parser("schema", help="print the schema (or the slice relevant to a question)")
170
+ s.add_argument("--db", required=True, help=db_help)
171
+ s.add_argument("question", nargs="?")
172
+ s.set_defaults(fn=cmd_schema)
173
+
174
+ s = with_db(sub.add_parser("serve", help="run as an MCP server over stdio"), model_default=None)
175
+ s.set_defaults(fn=cmd_serve)
176
+
177
+ s = with_db(sub.add_parser("eval", help="execution-accuracy eval against gold SQL"))
178
+ s.add_argument("--cases", default=str(BUILTIN_CASES),
179
+ help="JSONL of {id, level, question, gold} (default: the 15 sample-shop questions)")
180
+ s.add_argument("--out", help="write the JSON report here")
181
+ s.set_defaults(fn=cmd_eval)
182
+
183
+ s = with_model(sub.add_parser("spider", help="execution accuracy on a sample of the Spider dev set"))
184
+ s.add_argument("--n", type=int, default=100, help="questions to sample (0 = all 1,034)")
185
+ s.add_argument("--seed", type=int, default=0)
186
+ s.add_argument("--out", help="write the JSON report here")
187
+ s.set_defaults(fn=cmd_spider)
188
+
189
+ s = sub.add_parser("sample", help="build the sample retail database")
190
+ s.add_argument("path", nargs="?", default="shop.db")
191
+ s.add_argument("--postgres", metavar="URL", help="load it into PostgreSQL instead")
192
+ s.set_defaults(fn=cmd_sample)
193
+
194
+ args = p.parse_args(argv)
195
+ try:
196
+ return args.fn(args)
197
+ except (LLMError, FileNotFoundError, RuntimeError) as e:
198
+ print(f"error: {e}", file=sys.stderr)
199
+ return 2
200
+
201
+
202
+ if __name__ == "__main__":
203
+ sys.exit(main())
@@ -0,0 +1,15 @@
1
+ {"id": "q01", "level": "easy", "question": "How many customers are there?", "gold": "SELECT COUNT(*) FROM customers"}
2
+ {"id": "q02", "level": "easy", "question": "How many customers are based in India?", "gold": "SELECT COUNT(*) FROM customers WHERE country = 'India'"}
3
+ {"id": "q03", "level": "easy", "question": "How many orders were cancelled?", "gold": "SELECT COUNT(*) FROM orders WHERE status = 'cancelled'"}
4
+ {"id": "q04", "level": "easy", "question": "What is the most expensive product by list price?", "gold": "SELECT product_name FROM products ORDER BY list_price DESC LIMIT 1"}
5
+ {"id": "q05", "level": "medium", "question": "How many products are in each category?", "gold": "SELECT c.category_name, COUNT(*) FROM products p JOIN categories c ON c.category_id = p.category_id GROUP BY c.category_name"}
6
+ {"id": "q06", "level": "medium", "question": "How many orders came from each sales channel?", "gold": "SELECT channel, COUNT(*) FROM orders GROUP BY channel"}
7
+ {"id": "q07", "level": "medium", "question": "What is the total revenue from delivered orders? Revenue is quantity times unit price.", "gold": "SELECT ROUND(SUM(oi.quantity * oi.unit_price), 2) FROM order_items oi JOIN orders o ON o.order_id = oi.order_id WHERE o.status = 'delivered'"}
8
+ {"id": "q08", "level": "medium", "question": "How many orders were placed in 2026?", "gold": "SELECT COUNT(*) FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'"}
9
+ {"id": "q09", "level": "medium", "question": "Which return reason is the most common, and how many returns have it?", "gold": "SELECT reason, COUNT(*) FROM returns GROUP BY reason ORDER BY COUNT(*) DESC LIMIT 1"}
10
+ {"id": "q10", "level": "medium", "question": "Which city has the most customers, and how many customers are there?", "gold": "SELECT city, COUNT(*) FROM customers GROUP BY city ORDER BY COUNT(*) DESC LIMIT 1"}
11
+ {"id": "q11", "level": "hard", "question": "What is the total revenue per category for delivered orders? Revenue is quantity times unit price.", "gold": "SELECT c.category_name, ROUND(SUM(oi.quantity * oi.unit_price), 2) FROM order_items oi JOIN orders o ON o.order_id = oi.order_id JOIN products p ON p.product_id = oi.product_id JOIN categories c ON c.category_id = p.category_id WHERE o.status = 'delivered' GROUP BY c.category_name"}
12
+ {"id": "q12", "level": "hard", "question": "Which 3 products have been returned the most times? Give their names.", "gold": "SELECT p.product_name FROM returns r JOIN products p ON p.product_id = r.product_id GROUP BY p.product_id ORDER BY COUNT(*) DESC, p.product_name LIMIT 3"}
13
+ {"id": "q13", "level": "hard", "question": "How many distinct customers from the United States have placed at least one order?", "gold": "SELECT COUNT(DISTINCT o.customer_id) FROM orders o JOIN customers c ON c.customer_id = o.customer_id WHERE c.country = 'United States'"}
14
+ {"id": "q14", "level": "hard", "question": "Which country generated the most revenue from delivered orders, and how much? Revenue is quantity times unit price.", "gold": "SELECT c.country, ROUND(SUM(oi.quantity * oi.unit_price), 2) FROM order_items oi JOIN orders o ON o.order_id = oi.order_id JOIN customers c ON c.customer_id = o.customer_id WHERE o.status = 'delivered' GROUP BY c.country ORDER BY SUM(oi.quantity * oi.unit_price) DESC LIMIT 1"}
15
+ {"id": "q15", "level": "hard", "question": "How many customers have not placed any order since 1 January 2026?", "gold": "SELECT COUNT(*) FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.order_date >= '2026-01-01')"}
groundsql/db.py ADDED
@@ -0,0 +1,248 @@
1
+ """Read-only database access with layered SQL safety checks.
2
+
3
+ Every query passes four gates before rows come back. On SQLite:
4
+
5
+ 1. Static check: exactly one statement, starting with SELECT or WITH, with no
6
+ write/DDL keywords outside string literals.
7
+ 2. The connection is opened with ``mode=ro``, so SQLite itself refuses writes.
8
+ 3. An authorizer callback allows only read actions, even if a write slipped
9
+ past the static check.
10
+ 4. ``EXPLAIN`` compiles the query first, so unknown tables or columns fail
11
+ fast with SQLite's own error message (which the agent feeds back to the
12
+ model for repair) instead of a half-run query.
13
+
14
+ PostgreSQL gets the same shape (see ``postgres.py``): the static check plus a
15
+ blocklist of side-effecting functions, a session that is read-only by default,
16
+ every query inside a transaction that is always rolled back, and ``EXPLAIN``
17
+ before execution.
18
+
19
+ Execution is bounded by a wall-clock timeout, a row cap and (SQLite) a per-value size cap.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import pathlib
25
+ import re
26
+ import sqlite3
27
+ import time
28
+ from dataclasses import dataclass
29
+
30
+ from .schema import Table, introspect, relevant_tables
31
+
32
+
33
+ class SQLError(ValueError):
34
+ """The query is invalid or unsafe. The message is safe to show the model."""
35
+
36
+
37
+ class UnsafeSQL(SQLError):
38
+ pass
39
+
40
+
41
+ class InvalidSQL(SQLError):
42
+ pass
43
+
44
+
45
+ _FORBIDDEN = re.compile(
46
+ r"\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|ATTACH|DETACH|PRAGMA|"
47
+ r"VACUUM|REINDEX|TRUNCATE|GRANT|REVOKE|MERGE|INTO)\b", # REPLACE INTO is caught by INTO;
48
+ re.IGNORECASE, # replace() the function stays usable
49
+ )
50
+ _ALLOWED_ACTIONS = {
51
+ getattr(sqlite3, name)
52
+ for name in ("SQLITE_SELECT", "SQLITE_READ", "SQLITE_FUNCTION", "SQLITE_RECURSIVE")
53
+ if hasattr(sqlite3, name)
54
+ }
55
+
56
+
57
+ def _scan(sql: str) -> tuple[str, str]:
58
+ """One pass over the query, so comments and literals can't be confused.
59
+
60
+ Returns ``(clean, bare)``: ``clean`` has comments replaced by a space and string
61
+ literals untouched; ``bare`` is ``clean`` with every quoted span ('...' and "...")
62
+ replaced by ``''``, which is what the keyword checks look at. ``--`` or ``/*``
63
+ inside a literal is text, not a comment. ``E'...'`` (PostgreSQL) honours
64
+ backslash escapes.
65
+ """
66
+ clean: list[str] = []
67
+ bare: list[str] = []
68
+ i, n = 0, len(sql)
69
+ while i < n:
70
+ c = sql[i]
71
+ if sql.startswith("--", i):
72
+ end = sql.find("\n", i)
73
+ i = n if end < 0 else end
74
+ clean.append(" ")
75
+ bare.append(" ")
76
+ elif sql.startswith("/*", i):
77
+ end = sql.find("*/", i + 2)
78
+ i = n if end < 0 else end + 2
79
+ clean.append(" ")
80
+ bare.append(" ")
81
+ elif c in "'\"":
82
+ backslash = (c == "'" and i > 0 and sql[i - 1] in "eE"
83
+ and (i < 2 or not (sql[i - 2].isalnum() or sql[i - 2] == "_")))
84
+ j = i + 1
85
+ while True:
86
+ if j >= n:
87
+ raise InvalidSQL("unterminated quoted string or identifier")
88
+ if backslash and sql[j] == "\\":
89
+ j += 2
90
+ elif sql[j] == c:
91
+ if j + 1 < n and sql[j + 1] == c: # doubled quote is an escape
92
+ j += 2
93
+ else:
94
+ break
95
+ else:
96
+ j += 1
97
+ clean.append(sql[i:j + 1])
98
+ bare.append("''")
99
+ i = j + 1
100
+ else:
101
+ clean.append(c)
102
+ bare.append(c)
103
+ i += 1
104
+ return "".join(clean), "".join(bare)
105
+
106
+
107
+ def _strip_semicolons(sql: str, bare: str) -> tuple[str, str]:
108
+ sql, bare = sql.strip(), bare.strip()
109
+ while sql.endswith(";"):
110
+ sql, bare = sql[:-1].rstrip(), bare[:-1].rstrip()
111
+ return sql, bare
112
+
113
+
114
+ def clean_sql(sql: str) -> str:
115
+ """Strip comments (outside string literals) and trailing semicolons."""
116
+ return _strip_semicolons(*_scan(sql))[0]
117
+
118
+
119
+ def static_check(sql: str, extra: re.Pattern | None = None) -> str:
120
+ """Reject anything but one read-only SELECT. ``extra`` adds a dialect's own blocklist."""
121
+ sql, bare = _strip_semicolons(*_scan(sql))
122
+ if not sql:
123
+ raise InvalidSQL("empty query")
124
+ if ";" in bare:
125
+ raise UnsafeSQL("only one statement is allowed")
126
+ first = bare.split(None, 1)[0].upper()
127
+ if first not in ("SELECT", "WITH"):
128
+ raise UnsafeSQL(f"only SELECT queries are allowed, got {first}")
129
+ for pattern in (_FORBIDDEN, extra):
130
+ m = pattern.search(bare) if pattern else None
131
+ if m:
132
+ raise UnsafeSQL(f"{m.group(1).upper()} is not allowed in a read-only query")
133
+ return sql
134
+
135
+
136
+ @dataclass
137
+ class Result:
138
+ sql: str
139
+ columns: list[str]
140
+ rows: list[tuple]
141
+ truncated: bool
142
+ elapsed_ms: float
143
+
144
+
145
+ class BaseDatabase:
146
+ """What the agent, the MCP server and the evals need from a database."""
147
+
148
+ dialect = "SQL"
149
+ tables: dict[str, Table]
150
+ timeout_s: float
151
+ max_rows: int
152
+
153
+ def relevant_tables(self, question: str, top_k: int = 4) -> list[Table]:
154
+ return relevant_tables(question, self.tables, top_k)
155
+
156
+ def schema_text(self, tables: list[Table] | None = None) -> str:
157
+ return "\n\n".join(t.render() for t in (tables or self.tables.values()))
158
+
159
+ def check(self, sql: str) -> str:
160
+ raise NotImplementedError
161
+
162
+ def run(self, sql: str) -> Result:
163
+ raise NotImplementedError
164
+
165
+ def close(self) -> None:
166
+ raise NotImplementedError
167
+
168
+ def _result(self, sql: str, columns: list[str], rows: list, start: float) -> Result:
169
+ return Result(
170
+ sql=sql,
171
+ columns=columns,
172
+ rows=[tuple(r) for r in rows[: self.max_rows]],
173
+ truncated=len(rows) > self.max_rows,
174
+ elapsed_ms=(time.perf_counter() - start) * 1000,
175
+ )
176
+
177
+
178
+ class SQLiteDatabase(BaseDatabase):
179
+ dialect = "SQLite"
180
+
181
+ def __init__(self, path: str | pathlib.Path, timeout_s: float = 5.0, max_rows: int = 200,
182
+ max_value_bytes: int = 10_000_000):
183
+ self.path = pathlib.Path(path)
184
+ if not self.path.exists():
185
+ raise FileNotFoundError(self.path)
186
+ uri = f"file:{self.path.resolve().as_posix()}?mode=ro"
187
+ self.conn = sqlite3.connect(uri, uri=True, check_same_thread=False)
188
+ # Cap any single string or blob, so SELECT randomblob(1e9) can't allocate a
189
+ # gigabyte. Connection.setlimit needs Python 3.11+.
190
+ if hasattr(self.conn, "setlimit"):
191
+ self.conn.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, max_value_bytes)
192
+ # Real-world databases (Spider among them) hold text that is not valid UTF-8.
193
+ self.conn.text_factory = lambda b: b.decode("utf-8", errors="replace")
194
+ self.tables: dict[str, Table] = introspect(self.conn)
195
+ self.timeout_s = timeout_s
196
+ self.max_rows = max_rows
197
+ # Installed after introspection, which needs PRAGMA.
198
+ self.conn.set_authorizer(self._authorize)
199
+
200
+ @staticmethod
201
+ def _authorize(action, *_args):
202
+ return sqlite3.SQLITE_OK if action in _ALLOWED_ACTIONS else sqlite3.SQLITE_DENY
203
+
204
+ def close(self) -> None:
205
+ self.conn.close()
206
+
207
+ def check(self, sql: str) -> str:
208
+ sql = static_check(sql)
209
+ try:
210
+ self.conn.execute("EXPLAIN " + sql)
211
+ except sqlite3.Error as e:
212
+ msg = str(e)
213
+ if "not authorized" in msg:
214
+ raise UnsafeSQL("query tried a non-read operation") from e
215
+ raise InvalidSQL(msg) from e
216
+ return sql
217
+
218
+ def run(self, sql: str) -> Result:
219
+ sql = self.check(sql)
220
+ deadline = time.monotonic() + self.timeout_s
221
+ self.conn.set_progress_handler(lambda: int(time.monotonic() > deadline), 10_000)
222
+ start = time.perf_counter()
223
+ try:
224
+ cur = self.conn.execute(sql)
225
+ rows = cur.fetchmany(self.max_rows + 1)
226
+ except sqlite3.Error as e: # OperationalError, DataError ('string or blob too big'), ...
227
+ if "interrupted" in str(e):
228
+ raise InvalidSQL(f"query exceeded {self.timeout_s}s timeout") from e
229
+ raise InvalidSQL(str(e)) from e
230
+ finally:
231
+ self.conn.set_progress_handler(None, 0)
232
+ return self._result(sql, [d[0] for d in cur.description or []], rows, start)
233
+
234
+
235
+ # Backwards-compatible name: v0.1 had one SQLite-only Database class.
236
+ Database = SQLiteDatabase
237
+
238
+
239
+ def open_database(spec: str | pathlib.Path, **kwargs) -> BaseDatabase:
240
+ """A path (or sqlite:///path) opens SQLite; postgres:// or postgresql:// opens PostgreSQL."""
241
+ s = str(spec)
242
+ if s.startswith(("postgres://", "postgresql://")):
243
+ from .postgres import PostgresDatabase
244
+
245
+ return PostgresDatabase(s, **kwargs)
246
+ if s.startswith("sqlite:///"):
247
+ s = s[len("sqlite:///"):]
248
+ return SQLiteDatabase(s, **kwargs)