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 +13 -0
- groundsql/__main__.py +5 -0
- groundsql/agent.py +147 -0
- groundsql/cli.py +203 -0
- groundsql/data/questions.jsonl +15 -0
- groundsql/db.py +248 -0
- groundsql/evals.py +110 -0
- groundsql/llm.py +140 -0
- groundsql/mcp_server.py +127 -0
- groundsql/postgres.py +155 -0
- groundsql/sample.py +167 -0
- groundsql/schema.py +159 -0
- groundsql/spider.py +137 -0
- groundsql-0.2.1.dist-info/METADATA +191 -0
- groundsql-0.2.1.dist-info/RECORD +19 -0
- groundsql-0.2.1.dist-info/WHEEL +5 -0
- groundsql-0.2.1.dist-info/entry_points.txt +2 -0
- groundsql-0.2.1.dist-info/licenses/LICENSE +21 -0
- groundsql-0.2.1.dist-info/top_level.txt +1 -0
groundsql/evals.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Execution-accuracy evals: does the agent's query return the same answer as gold SQL?
|
|
2
|
+
|
|
3
|
+
Comparison is on result values, not SQL text, and ignores column names and
|
|
4
|
+
row order (unless only one row is asked for, where order does not matter
|
|
5
|
+
anyway). Floats are rounded to 2 places so 1234.5 == 1234.50.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import itertools
|
|
11
|
+
import json
|
|
12
|
+
import pathlib
|
|
13
|
+
import time
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
|
|
18
|
+
from .agent import Agent
|
|
19
|
+
from .db import BaseDatabase, SQLError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _norm(value):
|
|
23
|
+
if isinstance(value, Decimal): # PostgreSQL NUMERIC
|
|
24
|
+
value = float(value)
|
|
25
|
+
if isinstance(value, float):
|
|
26
|
+
return round(value, 2)
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def same_result(a: list[tuple], b: list[tuple]) -> bool:
|
|
31
|
+
"""Order-insensitive multiset comparison of rows.
|
|
32
|
+
|
|
33
|
+
Also accepts a result whose rows are the gold rows plus extra columns
|
|
34
|
+
(e.g. the model returned name AND count when only the name was asked).
|
|
35
|
+
"""
|
|
36
|
+
pred = [tuple(_norm(v) for v in r) for r in a]
|
|
37
|
+
gold = Counter(tuple(_norm(v) for v in r) for r in b)
|
|
38
|
+
if Counter(pred) == gold:
|
|
39
|
+
return True
|
|
40
|
+
if not b or len(a) != len(b):
|
|
41
|
+
return False
|
|
42
|
+
gold_width, pred_width = len(b[0]), len(a[0])
|
|
43
|
+
if pred_width <= gold_width or pred_width > 8:
|
|
44
|
+
return False
|
|
45
|
+
# Some choice of the predicted columns must reproduce the gold rows exactly.
|
|
46
|
+
for idx in itertools.permutations(range(pred_width), gold_width):
|
|
47
|
+
if Counter(tuple(r[i] for i in idx) for r in pred) == gold:
|
|
48
|
+
return True
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Case:
|
|
54
|
+
id: str
|
|
55
|
+
level: str
|
|
56
|
+
question: str
|
|
57
|
+
gold: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_cases(path: str | pathlib.Path) -> list[Case]:
|
|
61
|
+
lines = pathlib.Path(path).read_text(encoding="utf-8").splitlines()
|
|
62
|
+
return [Case(**json.loads(line)) for line in lines if line.strip()]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def run_eval(agent: Agent, cases: list[Case]) -> dict:
|
|
66
|
+
db: BaseDatabase = agent.db
|
|
67
|
+
results = []
|
|
68
|
+
skipped = []
|
|
69
|
+
for case in cases:
|
|
70
|
+
try:
|
|
71
|
+
gold = db.run(case.gold).rows
|
|
72
|
+
except SQLError as e: # a benchmark's own gold query can trip the safety gates
|
|
73
|
+
skipped.append({"id": case.id, "reason": f"gold query rejected: {e}"})
|
|
74
|
+
continue
|
|
75
|
+
t0 = time.perf_counter()
|
|
76
|
+
try:
|
|
77
|
+
answer = agent.ask(case.question)
|
|
78
|
+
error = answer.error
|
|
79
|
+
except Exception as e: # a provider outage should not abort the whole run
|
|
80
|
+
answer, error = None, f"{type(e).__name__}: {e}"
|
|
81
|
+
passed = bool(
|
|
82
|
+
answer is not None and answer.result is not None
|
|
83
|
+
and same_result(answer.result.rows, gold)
|
|
84
|
+
)
|
|
85
|
+
results.append({
|
|
86
|
+
"id": case.id,
|
|
87
|
+
"level": case.level,
|
|
88
|
+
"question": case.question,
|
|
89
|
+
"passed": passed,
|
|
90
|
+
"sql": answer.sql if answer else None,
|
|
91
|
+
"attempts": len(answer.attempts) if answer else 0,
|
|
92
|
+
"repaired": bool(answer and answer.ok and len(answer.attempts) > 1),
|
|
93
|
+
"error": error,
|
|
94
|
+
"seconds": round(time.perf_counter() - t0, 2),
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
by_level: dict[str, list[bool]] = {}
|
|
98
|
+
for r in results:
|
|
99
|
+
by_level.setdefault(r["level"], []).append(r["passed"])
|
|
100
|
+
n = len(results)
|
|
101
|
+
return {
|
|
102
|
+
"model": agent.llm.name,
|
|
103
|
+
"cases": n,
|
|
104
|
+
"execution_accuracy": round(sum(r["passed"] for r in results) / n, 3) if n else 0.0,
|
|
105
|
+
"valid_sql_rate": round(sum(r["sql"] is not None for r in results) / n, 3) if n else 0.0,
|
|
106
|
+
"by_level": {k: f"{sum(v)}/{len(v)}" for k, v in sorted(by_level.items())},
|
|
107
|
+
"repaired_and_passed": sum(r["repaired"] and r["passed"] for r in results),
|
|
108
|
+
"skipped": skipped,
|
|
109
|
+
"results": results,
|
|
110
|
+
}
|
groundsql/llm.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Minimal LLM clients over plain HTTP (no SDK dependencies).
|
|
2
|
+
|
|
3
|
+
A model is named with a provider prefix:
|
|
4
|
+
|
|
5
|
+
ollama:llama3.2 local Ollama (OpenAI-compatible endpoint)
|
|
6
|
+
groq:openai/gpt-oss-120b
|
|
7
|
+
openai:gpt-4o-mini
|
|
8
|
+
anthropic:claude-sonnet-4-6
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from typing import Protocol
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LLM(Protocol):
|
|
24
|
+
name: str
|
|
25
|
+
|
|
26
|
+
def complete(self, system: str, messages: list[dict]) -> str: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LLMError(RuntimeError):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _post(url: str, payload: dict, headers: dict, timeout: float, retries: int = 6) -> dict:
|
|
34
|
+
body = json.dumps(payload).encode()
|
|
35
|
+
all_headers = {"Content-Type": "application/json",
|
|
36
|
+
# Cloudflare-fronted APIs (Groq among them) reject urllib's default agent
|
|
37
|
+
# with "error code: 1010".
|
|
38
|
+
"User-Agent": f"groundsql/{__version__}", **headers}
|
|
39
|
+
for attempt in range(retries + 1):
|
|
40
|
+
req = urllib.request.Request(url, data=body, headers=all_headers, method="POST")
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
43
|
+
return json.load(resp)
|
|
44
|
+
except urllib.error.HTTPError as e:
|
|
45
|
+
# Rate limits and overloads are worth waiting out; anything else is a real error.
|
|
46
|
+
if e.code in (429, 500, 502, 503, 529) and attempt < retries:
|
|
47
|
+
wait = e.headers.get("retry-after")
|
|
48
|
+
try:
|
|
49
|
+
delay = min(float(wait), 60.0) if wait else 2.0 * 2 ** attempt
|
|
50
|
+
except ValueError:
|
|
51
|
+
delay = 2.0 * 2 ** attempt
|
|
52
|
+
time.sleep(delay)
|
|
53
|
+
continue
|
|
54
|
+
raise LLMError(f"{url} -> HTTP {e.code}: {e.read().decode(errors='replace')[:300]}") from e
|
|
55
|
+
except urllib.error.URLError as e:
|
|
56
|
+
raise LLMError(f"{url} unreachable: {e.reason}") from e
|
|
57
|
+
raise LLMError(f"{url}: gave up after {retries} retries") # pragma: no cover
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class OpenAICompatible:
|
|
61
|
+
def __init__(self, model: str, base_url: str, api_key: str | None = None, timeout: float = 120):
|
|
62
|
+
self.name = model
|
|
63
|
+
self.base_url = base_url.rstrip("/")
|
|
64
|
+
self.api_key = api_key
|
|
65
|
+
self.timeout = timeout
|
|
66
|
+
|
|
67
|
+
def complete(self, system: str, messages: list[dict]) -> str:
|
|
68
|
+
headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
|
|
69
|
+
data = _post(
|
|
70
|
+
f"{self.base_url}/chat/completions",
|
|
71
|
+
{
|
|
72
|
+
"model": self.name,
|
|
73
|
+
"temperature": 0,
|
|
74
|
+
"messages": [{"role": "system", "content": system}, *messages],
|
|
75
|
+
},
|
|
76
|
+
headers,
|
|
77
|
+
self.timeout,
|
|
78
|
+
)
|
|
79
|
+
return data["choices"][0]["message"]["content"] or ""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Anthropic:
|
|
83
|
+
def __init__(self, model: str, api_key: str, timeout: float = 120):
|
|
84
|
+
self.name = model
|
|
85
|
+
self.api_key = api_key
|
|
86
|
+
self.timeout = timeout
|
|
87
|
+
|
|
88
|
+
def complete(self, system: str, messages: list[dict]) -> str:
|
|
89
|
+
data = _post(
|
|
90
|
+
"https://api.anthropic.com/v1/messages",
|
|
91
|
+
{
|
|
92
|
+
"model": self.name,
|
|
93
|
+
"max_tokens": 1024,
|
|
94
|
+
"temperature": 0,
|
|
95
|
+
"system": system,
|
|
96
|
+
"messages": messages,
|
|
97
|
+
},
|
|
98
|
+
{"x-api-key": self.api_key, "anthropic-version": "2023-06-01"},
|
|
99
|
+
self.timeout,
|
|
100
|
+
)
|
|
101
|
+
return "".join(b.get("text", "") for b in data.get("content", []))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class Scripted:
|
|
105
|
+
"""Replays canned responses. Used by tests and offline demos."""
|
|
106
|
+
|
|
107
|
+
def __init__(self, responses: list[str], name: str = "scripted"):
|
|
108
|
+
self.name = name
|
|
109
|
+
self.responses = list(responses)
|
|
110
|
+
self.calls: list[list[dict]] = []
|
|
111
|
+
|
|
112
|
+
def complete(self, system: str, messages: list[dict]) -> str:
|
|
113
|
+
self.calls.append([dict(m) for m in messages])
|
|
114
|
+
if not self.responses:
|
|
115
|
+
raise LLMError("scripted LLM ran out of responses")
|
|
116
|
+
return self.responses.pop(0)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _key(var: str) -> str:
|
|
120
|
+
value = os.environ.get(var)
|
|
121
|
+
if not value:
|
|
122
|
+
raise LLMError(f"set {var} to use this provider")
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def from_spec(spec: str) -> LLM:
|
|
127
|
+
provider, _, model = spec.partition(":")
|
|
128
|
+
if not model:
|
|
129
|
+
raise LLMError(f"model spec must look like provider:model, got {spec!r}")
|
|
130
|
+
if provider == "ollama":
|
|
131
|
+
host = os.environ.get("OLLAMA_HOST", "http://localhost:11434")
|
|
132
|
+
return OpenAICompatible(model, f"{host}/v1")
|
|
133
|
+
if provider == "groq":
|
|
134
|
+
return OpenAICompatible(model, "https://api.groq.com/openai/v1", _key("GROQ_API_KEY"))
|
|
135
|
+
if provider == "openai":
|
|
136
|
+
base = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
|
137
|
+
return OpenAICompatible(model, base, _key("OPENAI_API_KEY"))
|
|
138
|
+
if provider == "anthropic":
|
|
139
|
+
return Anthropic(model, _key("ANTHROPIC_API_KEY"))
|
|
140
|
+
raise LLMError(f"unknown provider {provider!r} (use ollama, groq, openai or anthropic)")
|
groundsql/mcp_server.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""MCP server over stdio (JSON-RPC 2.0, newline-delimited), no SDK required.
|
|
2
|
+
|
|
3
|
+
Exposes the database to any MCP client (Claude Desktop, Claude Code, Cursor...):
|
|
4
|
+
|
|
5
|
+
list_tables table names with row counts
|
|
6
|
+
describe_table columns, keys and sample values for one table
|
|
7
|
+
run_sql run a read-only query through the same safety gates
|
|
8
|
+
ask natural-language question -> SQL -> rows (needs --model)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any, TextIO
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .agent import Agent, format_table
|
|
19
|
+
from .db import BaseDatabase, SQLError
|
|
20
|
+
|
|
21
|
+
PROTOCOL_VERSION = "2025-06-18"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MCPServer:
|
|
25
|
+
def __init__(self, db: BaseDatabase, agent: Agent | None = None):
|
|
26
|
+
self.db = db
|
|
27
|
+
self.agent = agent
|
|
28
|
+
|
|
29
|
+
def tools(self) -> list[dict]:
|
|
30
|
+
tools = [
|
|
31
|
+
{
|
|
32
|
+
"name": "list_tables",
|
|
33
|
+
"description": "List the database tables with their row counts.",
|
|
34
|
+
"inputSchema": {"type": "object", "properties": {}},
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"name": "describe_table",
|
|
38
|
+
"description": "Columns, types, keys and sample values for one table.",
|
|
39
|
+
"inputSchema": {
|
|
40
|
+
"type": "object",
|
|
41
|
+
"properties": {"table": {"type": "string"}},
|
|
42
|
+
"required": ["table"],
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"name": "run_sql",
|
|
47
|
+
"description": f"Run ONE read-only {self.db.dialect} SELECT query and return the rows.",
|
|
48
|
+
"inputSchema": {
|
|
49
|
+
"type": "object",
|
|
50
|
+
"properties": {"sql": {"type": "string"}},
|
|
51
|
+
"required": ["sql"],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
]
|
|
55
|
+
if self.agent:
|
|
56
|
+
tools.append({
|
|
57
|
+
"name": "ask",
|
|
58
|
+
"description": "Answer a question about the data: writes SQL, validates it, runs it.",
|
|
59
|
+
"inputSchema": {
|
|
60
|
+
"type": "object",
|
|
61
|
+
"properties": {"question": {"type": "string"}},
|
|
62
|
+
"required": ["question"],
|
|
63
|
+
},
|
|
64
|
+
})
|
|
65
|
+
return tools
|
|
66
|
+
|
|
67
|
+
def call_tool(self, name: str, args: dict) -> tuple[str, bool]:
|
|
68
|
+
if name == "list_tables":
|
|
69
|
+
return "\n".join(f"{t.name} ({t.row_count} rows)" for t in self.db.tables.values()), False
|
|
70
|
+
if name == "describe_table":
|
|
71
|
+
table = self.db.tables.get(args.get("table", ""))
|
|
72
|
+
if not table:
|
|
73
|
+
return f"unknown table {args.get('table')!r}; try list_tables", True
|
|
74
|
+
return table.render(), False
|
|
75
|
+
if name == "run_sql":
|
|
76
|
+
try:
|
|
77
|
+
return format_table(self.db.run(args.get("sql", ""))), False
|
|
78
|
+
except SQLError as e:
|
|
79
|
+
return f"query rejected: {e}", True
|
|
80
|
+
if name == "ask" and self.agent:
|
|
81
|
+
answer = self.agent.ask(args.get("question", ""))
|
|
82
|
+
if answer.result is None:
|
|
83
|
+
return f"could not answer: {answer.error}", True
|
|
84
|
+
return f"SQL:\n{answer.sql}\n\n{format_table(answer.result)}", False
|
|
85
|
+
return f"unknown tool {name!r}", True
|
|
86
|
+
|
|
87
|
+
def handle(self, msg: dict) -> dict | None:
|
|
88
|
+
method, mid = msg.get("method"), msg.get("id")
|
|
89
|
+
if mid is None: # notification, e.g. notifications/initialized
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
result: Any
|
|
93
|
+
if method == "initialize":
|
|
94
|
+
result = {
|
|
95
|
+
"protocolVersion": msg.get("params", {}).get("protocolVersion", PROTOCOL_VERSION),
|
|
96
|
+
"capabilities": {"tools": {}},
|
|
97
|
+
"serverInfo": {"name": "groundsql", "version": __version__},
|
|
98
|
+
}
|
|
99
|
+
elif method == "ping":
|
|
100
|
+
result = {}
|
|
101
|
+
elif method == "tools/list":
|
|
102
|
+
result = {"tools": self.tools()}
|
|
103
|
+
elif method == "tools/call":
|
|
104
|
+
params = msg.get("params", {})
|
|
105
|
+
text, is_error = self.call_tool(params.get("name", ""), params.get("arguments") or {})
|
|
106
|
+
result = {"content": [{"type": "text", "text": text}], "isError": is_error}
|
|
107
|
+
else:
|
|
108
|
+
return {"jsonrpc": "2.0", "id": mid,
|
|
109
|
+
"error": {"code": -32601, "message": f"method not found: {method}"}}
|
|
110
|
+
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
|
111
|
+
except Exception as e: # never kill the stdio loop on one bad call
|
|
112
|
+
return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}}
|
|
113
|
+
|
|
114
|
+
def serve(self, stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None:
|
|
115
|
+
for line in stdin:
|
|
116
|
+
line = line.strip()
|
|
117
|
+
if not line:
|
|
118
|
+
continue
|
|
119
|
+
try:
|
|
120
|
+
msg = json.loads(line)
|
|
121
|
+
except json.JSONDecodeError:
|
|
122
|
+
reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}
|
|
123
|
+
else:
|
|
124
|
+
reply = self.handle(msg)
|
|
125
|
+
if reply is not None:
|
|
126
|
+
stdout.write(json.dumps(reply, default=str) + "\n")
|
|
127
|
+
stdout.flush()
|
groundsql/postgres.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""PostgreSQL backend (``pip install groundsql[postgres]``).
|
|
2
|
+
|
|
3
|
+
The same four gates as SQLite, in Postgres terms:
|
|
4
|
+
|
|
5
|
+
1. The shared static check, plus a blocklist of functions with side effects
|
|
6
|
+
that a read-only transaction would still let through (``pg_terminate_backend``,
|
|
7
|
+
``pg_read_file``, ``dblink``, ``pg_sleep``...).
|
|
8
|
+
2. The session starts with ``default_transaction_read_only=on``, so the server
|
|
9
|
+
refuses any write, and every query runs in a transaction that is rolled back.
|
|
10
|
+
3. ``statement_timeout`` bounds execution on the server side.
|
|
11
|
+
4. ``EXPLAIN`` compiles the query first, so a wrong column fails with the
|
|
12
|
+
server's own message before anything runs.
|
|
13
|
+
|
|
14
|
+
Defence in depth still wants a least-privilege role: connect as a user with
|
|
15
|
+
SELECT on the tables it should see and nothing else.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
from .db import BaseDatabase, InvalidSQL, Result, UnsafeSQL, static_check
|
|
24
|
+
from .schema import CATEGORICAL_MAX, Column, ForeignKey, Table, pick_samples
|
|
25
|
+
|
|
26
|
+
_PG_FUNCTIONS = re.compile(
|
|
27
|
+
r"\b(pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|"
|
|
28
|
+
r"pg_read_file|pg_read_binary_file|pg_ls_dir|pg_stat_file|lo_import|lo_export|lo_unlink|"
|
|
29
|
+
r"dblink\w*|pg_sleep\w*|set_config|pg_advisory\w*|pg_notify|nextval|setval|"
|
|
30
|
+
r"pg_logical_emit_message|query_to_xml\w*)\s*\(",
|
|
31
|
+
re.IGNORECASE,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
_TEXT_TYPES = {"text", "character varying", "character", "citext"}
|
|
35
|
+
_ROW_CAP = 1_000_000 # count rows up to this, then say "1000000+"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _ident(name: str) -> str:
|
|
39
|
+
return '"' + name.replace('"', '""') + '"'
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class PostgresDatabase(BaseDatabase):
|
|
43
|
+
dialect = "PostgreSQL"
|
|
44
|
+
|
|
45
|
+
def __init__(self, url: str, schema: str = "public", timeout_s: float = 5.0,
|
|
46
|
+
max_rows: int = 200, sample_values: int = 3):
|
|
47
|
+
try:
|
|
48
|
+
import psycopg
|
|
49
|
+
except ImportError as e: # pragma: no cover - exercised only without the extra
|
|
50
|
+
raise RuntimeError("PostgreSQL needs psycopg: pip install 'groundsql[postgres]'") from e
|
|
51
|
+
self._psycopg = psycopg
|
|
52
|
+
self.url = url
|
|
53
|
+
self.schema = schema
|
|
54
|
+
self.timeout_s = timeout_s
|
|
55
|
+
self.max_rows = max_rows
|
|
56
|
+
self.conn = psycopg.connect(url, options="-c default_transaction_read_only=on")
|
|
57
|
+
with self.conn.cursor() as cur:
|
|
58
|
+
# Unqualified names in the model's SQL resolve to this schema.
|
|
59
|
+
cur.execute(f"SET search_path TO {_ident(schema)}")
|
|
60
|
+
self.conn.commit()
|
|
61
|
+
try:
|
|
62
|
+
self.tables = self._introspect(sample_values)
|
|
63
|
+
finally:
|
|
64
|
+
self.conn.rollback()
|
|
65
|
+
|
|
66
|
+
def close(self) -> None:
|
|
67
|
+
self.conn.close()
|
|
68
|
+
|
|
69
|
+
# ── introspection ──────────────────────────────────────────────────────
|
|
70
|
+
def _introspect(self, sample_values: int) -> dict[str, Table]:
|
|
71
|
+
tables: dict[str, Table] = {}
|
|
72
|
+
with self.conn.cursor() as cur:
|
|
73
|
+
cur.execute(f"SET LOCAL statement_timeout = {int(self.timeout_s * 1000)}")
|
|
74
|
+
cur.execute(
|
|
75
|
+
"SELECT table_name FROM information_schema.tables "
|
|
76
|
+
"WHERE table_schema = %s AND table_type IN ('BASE TABLE', 'VIEW') ORDER BY 1",
|
|
77
|
+
(self.schema,),
|
|
78
|
+
)
|
|
79
|
+
names = [r[0] for r in cur.fetchall()]
|
|
80
|
+
for name in names:
|
|
81
|
+
qualified = f"{_ident(self.schema)}.{_ident(name)}"
|
|
82
|
+
cur.execute(
|
|
83
|
+
"SELECT a.attname FROM pg_index i JOIN pg_attribute a "
|
|
84
|
+
"ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) "
|
|
85
|
+
"WHERE i.indrelid = %s::regclass AND i.indisprimary",
|
|
86
|
+
(qualified,),
|
|
87
|
+
)
|
|
88
|
+
pks = {r[0] for r in cur.fetchall()}
|
|
89
|
+
cur.execute(
|
|
90
|
+
"SELECT column_name, data_type FROM information_schema.columns "
|
|
91
|
+
"WHERE table_schema = %s AND table_name = %s ORDER BY ordinal_position",
|
|
92
|
+
(self.schema, name),
|
|
93
|
+
)
|
|
94
|
+
columns = []
|
|
95
|
+
for col, dtype in cur.fetchall():
|
|
96
|
+
column = Column(name=col, type=dtype.upper(), pk=col in pks)
|
|
97
|
+
if sample_values and dtype in _TEXT_TYPES:
|
|
98
|
+
cur.execute(
|
|
99
|
+
f"SELECT {_ident(col)} FROM {qualified} WHERE {_ident(col)} IS NOT NULL "
|
|
100
|
+
f"GROUP BY 1 ORDER BY COUNT(*) DESC, 1 LIMIT %s",
|
|
101
|
+
(CATEGORICAL_MAX + 1,),
|
|
102
|
+
)
|
|
103
|
+
pick_samples(column, [r[0] for r in cur.fetchall()], sample_values)
|
|
104
|
+
columns.append(column)
|
|
105
|
+
cur.execute(
|
|
106
|
+
"SELECT kcu.column_name, ccu.table_name, ccu.column_name "
|
|
107
|
+
"FROM information_schema.table_constraints tc "
|
|
108
|
+
"JOIN information_schema.key_column_usage kcu "
|
|
109
|
+
" ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema "
|
|
110
|
+
"JOIN information_schema.constraint_column_usage ccu "
|
|
111
|
+
" ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema "
|
|
112
|
+
"WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s",
|
|
113
|
+
(self.schema, name),
|
|
114
|
+
)
|
|
115
|
+
fks = [ForeignKey(column=c, ref_table=t, ref_column=rc) for c, t, rc in cur.fetchall()]
|
|
116
|
+
cur.execute(f"SELECT count(*) FROM (SELECT 1 FROM {qualified} LIMIT {_ROW_CAP}) s")
|
|
117
|
+
count = cur.fetchone()[0]
|
|
118
|
+
tables[name] = Table(name=name, columns=columns, foreign_keys=fks, row_count=count)
|
|
119
|
+
return tables
|
|
120
|
+
|
|
121
|
+
# ── the gates ──────────────────────────────────────────────────────────
|
|
122
|
+
def _message(self, e: Exception) -> str:
|
|
123
|
+
diag = getattr(e, "diag", None)
|
|
124
|
+
primary = getattr(diag, "message_primary", None) if diag else None
|
|
125
|
+
return primary or str(e).splitlines()[0]
|
|
126
|
+
|
|
127
|
+
def _execute(self, sql: str, fetch: bool):
|
|
128
|
+
errors = self._psycopg.errors
|
|
129
|
+
try:
|
|
130
|
+
with self.conn.cursor() as cur:
|
|
131
|
+
cur.execute(f"SET LOCAL statement_timeout = {int(self.timeout_s * 1000)}")
|
|
132
|
+
cur.execute(sql)
|
|
133
|
+
if not fetch:
|
|
134
|
+
return None, None
|
|
135
|
+
rows = cur.fetchmany(self.max_rows + 1)
|
|
136
|
+
return [d.name for d in cur.description or []], rows
|
|
137
|
+
except errors.QueryCanceled as e:
|
|
138
|
+
raise InvalidSQL(f"query exceeded {self.timeout_s}s timeout") from e
|
|
139
|
+
except (errors.ReadOnlySqlTransaction, errors.InsufficientPrivilege) as e:
|
|
140
|
+
raise UnsafeSQL(f"query tried a non-read operation: {self._message(e)}") from e
|
|
141
|
+
except self._psycopg.Error as e:
|
|
142
|
+
raise InvalidSQL(self._message(e)) from e
|
|
143
|
+
finally:
|
|
144
|
+
self.conn.rollback() # nothing a query does survives it
|
|
145
|
+
|
|
146
|
+
def check(self, sql: str) -> str:
|
|
147
|
+
sql = static_check(sql, extra=_PG_FUNCTIONS)
|
|
148
|
+
self._execute("EXPLAIN " + sql, fetch=False)
|
|
149
|
+
return sql
|
|
150
|
+
|
|
151
|
+
def run(self, sql: str) -> Result:
|
|
152
|
+
sql = self.check(sql)
|
|
153
|
+
start = time.perf_counter()
|
|
154
|
+
columns, rows = self._execute(sql, fetch=True)
|
|
155
|
+
return self._result(sql, columns or [], rows or [], start)
|