postgres-schema-mcp 0.1.0__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.
- postgres_schema_mcp/__init__.py +0 -0
- postgres_schema_mcp/adapters/__init__.py +1 -0
- postgres_schema_mcp/adapters/backends.py +101 -0
- postgres_schema_mcp/adapters/db.py +430 -0
- postgres_schema_mcp/core/__init__.py +1 -0
- postgres_schema_mcp/core/ddl.py +52 -0
- postgres_schema_mcp/core/guard.py +269 -0
- postgres_schema_mcp/core/retrieval.py +429 -0
- postgres_schema_mcp/core/types.py +136 -0
- postgres_schema_mcp/py.typed +0 -0
- postgres_schema_mcp/server.py +339 -0
- postgres_schema_mcp-0.1.0.dist-info/METADATA +267 -0
- postgres_schema_mcp-0.1.0.dist-info/RECORD +16 -0
- postgres_schema_mcp-0.1.0.dist-info/WHEEL +4 -0
- postgres_schema_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- postgres_schema_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""All I/O: databases, HTTP, files, model clients. Passed into core, never imported by it."""
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Retrieval backend selection: BM25 from the core, or Titan embeddings via Bedrock.
|
|
2
|
+
|
|
3
|
+
Titan makes network calls, so it lives here and not in core/retrieval.py.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import Any, Final
|
|
11
|
+
|
|
12
|
+
from ..core.retrieval import (
|
|
13
|
+
DEFAULT_NEIGHBOUR_WEIGHT,
|
|
14
|
+
BM25Backend,
|
|
15
|
+
RetrievalBackend,
|
|
16
|
+
SchemaIndex,
|
|
17
|
+
)
|
|
18
|
+
from ..core.types import TableDetail
|
|
19
|
+
|
|
20
|
+
__all__ = ["TITAN_MODEL_ID", "TitanBackend", "build_backend", "make_index"]
|
|
21
|
+
|
|
22
|
+
TITAN_MODEL_ID: Final = "amazon.titan-embed-text-v2:0"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TitanBackend:
|
|
26
|
+
"""Amazon Titan Text Embeddings V2 via Bedrock.
|
|
27
|
+
|
|
28
|
+
Measured against the real service on the 26-question eval set, and it does
|
|
29
|
+
not win: recall@8 0.926 versus BM25's 0.955 (22/26 complete versus 24/26).
|
|
30
|
+
Both backends score ~0.84 before foreign-key propagation, so the embeddings
|
|
31
|
+
add nothing here that the lexical path was not already getting.
|
|
32
|
+
|
|
33
|
+
That is a defensible result rather than a disappointing one. These documents
|
|
34
|
+
are mostly identifiers and one-line comments, not prose, which is the regime
|
|
35
|
+
BM25 is good at. Two caveats worth stating: Titan is handed the same
|
|
36
|
+
identifier-heavy document text as BM25, and a prose rendering might suit it
|
|
37
|
+
better; and the lexicon and stemmer in this module were tuned with BM25 in
|
|
38
|
+
mind, so the comparison is not perfectly even-handed.
|
|
39
|
+
|
|
40
|
+
BM25 therefore remains the default, on evidence rather than convenience.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
name = "titan"
|
|
44
|
+
|
|
45
|
+
def __init__(self, documents: Sequence[str], client: Any | None = None) -> None:
|
|
46
|
+
self._client = client if client is not None else self._default_client()
|
|
47
|
+
self._doc_vectors = [self._embed(d) for d in documents]
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def _default_client() -> Any:
|
|
51
|
+
import boto3
|
|
52
|
+
|
|
53
|
+
return boto3.client(
|
|
54
|
+
"bedrock-runtime", region_name=os.environ.get("AWS_REGION", "us-east-1")
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def _embed(self, text: str) -> list[float]:
|
|
58
|
+
import json
|
|
59
|
+
|
|
60
|
+
response = self._client.invoke_model(
|
|
61
|
+
modelId=os.environ.get("PGSS_TITAN_MODEL_ID", TITAN_MODEL_ID),
|
|
62
|
+
body=json.dumps({"inputText": text, "dimensions": 1024, "normalize": True}),
|
|
63
|
+
accept="application/json",
|
|
64
|
+
contentType="application/json",
|
|
65
|
+
)
|
|
66
|
+
payload = json.loads(response["body"].read())
|
|
67
|
+
return [float(x) for x in payload["embedding"]]
|
|
68
|
+
|
|
69
|
+
def rank(self, question: str, limit: int) -> list[tuple[int, float]]:
|
|
70
|
+
query = self._embed(question)
|
|
71
|
+
# Titan is asked for normalised vectors, so a dot product is cosine
|
|
72
|
+
# similarity.
|
|
73
|
+
scored = [
|
|
74
|
+
(i, sum(a * b for a, b in zip(query, doc, strict=False)))
|
|
75
|
+
for i, doc in enumerate(self._doc_vectors)
|
|
76
|
+
]
|
|
77
|
+
ordered = sorted(scored, key=lambda pair: (-pair[1], pair[0]))
|
|
78
|
+
return [(i, float(s)) for i, s in ordered[:limit]]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def build_backend(documents: Sequence[str], name: str | None = None) -> RetrievalBackend:
|
|
82
|
+
"""Pick a backend by name, defaulting to the env var and then to BM25."""
|
|
83
|
+
chosen = (name or os.environ.get("PGSS_RETRIEVAL_BACKEND") or "bm25").strip().lower()
|
|
84
|
+
if chosen == "titan":
|
|
85
|
+
return TitanBackend(documents)
|
|
86
|
+
if chosen != "bm25":
|
|
87
|
+
raise ValueError(f"Unknown retrieval backend {chosen!r}; expected 'bm25' or 'titan'.")
|
|
88
|
+
return BM25Backend(documents)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def make_index(
|
|
92
|
+
tables: Sequence[TableDetail],
|
|
93
|
+
backend: str | None = None,
|
|
94
|
+
neighbour_weight: float = DEFAULT_NEIGHBOUR_WEIGHT,
|
|
95
|
+
) -> SchemaIndex:
|
|
96
|
+
"""Build the index with the backend named by `backend` or PGSS_RETRIEVAL_BACKEND."""
|
|
97
|
+
return SchemaIndex(
|
|
98
|
+
tables,
|
|
99
|
+
backend_factory=lambda documents: build_backend(documents, backend),
|
|
100
|
+
neighbour_weight=neighbour_weight,
|
|
101
|
+
)
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"""Connection pool and the read-only execution path.
|
|
2
|
+
|
|
3
|
+
Layer 3 of the safety model lives here in the sense that this module is what
|
|
4
|
+
chooses *which role to authenticate as*. It connects as scout_ro, which holds
|
|
5
|
+
SELECT and nothing else (see init/20-grants.sql). Everything below that is
|
|
6
|
+
belt-and-braces on top of a role that already cannot write:
|
|
7
|
+
|
|
8
|
+
* `default_transaction_read_only=on` at the session level, so every
|
|
9
|
+
transaction is READ ONLY without the caller having to remember;
|
|
10
|
+
* an explicit `BEGIN READ ONLY` around each query (the pool's `configure` step sets
|
|
11
|
+
it on every connection), which a query cannot switch off from inside the transaction;
|
|
12
|
+
* a connection reset when a connection goes back to the pool, so a session-level lock
|
|
13
|
+
or setting left by one request is gone before the next;
|
|
14
|
+
* `statement_timeout`, so a legitimate but expensive query cannot become a
|
|
15
|
+
denial of service;
|
|
16
|
+
* `idle_in_transaction_session_timeout`, so a wedged client cannot hold locks;
|
|
17
|
+
* a server-side cursor read in small batches, a row cap, a per-cell cap and a total
|
|
18
|
+
size cap, with the truncation reported to the model rather than hidden.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import datetime as dt
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from decimal import Decimal
|
|
28
|
+
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
|
|
29
|
+
from typing import Any, Self
|
|
30
|
+
from uuid import UUID
|
|
31
|
+
|
|
32
|
+
import psycopg
|
|
33
|
+
from psycopg.rows import tuple_row
|
|
34
|
+
from psycopg_pool import AsyncConnectionPool
|
|
35
|
+
|
|
36
|
+
from ..core.ddl import render_ddl
|
|
37
|
+
from ..core.types import ColumnInfo, ForeignKey, QueryPlan, QueryResult, TableDetail
|
|
38
|
+
|
|
39
|
+
__all__ = ["Database", "Settings"]
|
|
40
|
+
|
|
41
|
+
DEFAULT_DSN = "postgresql://scout_ro:scout_ro_pw@localhost:55432/adventureworks"
|
|
42
|
+
|
|
43
|
+
# The five real AdventureWorks schemas. The shorthand view schemas that the
|
|
44
|
+
# upstream loader also creates (pe, hr, pr, pu, sa) are excluded: they are 68
|
|
45
|
+
# convenience views over these same 68 tables, so indexing them would double
|
|
46
|
+
# every table and inflate the "full schema" baseline that the README compares
|
|
47
|
+
# against. Excluding them makes the headline ratio harder to hit, not easier.
|
|
48
|
+
DEFAULT_SCHEMAS = ("person", "humanresources", "production", "purchasing", "sales")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _env_int(name: str, default: int) -> int:
|
|
52
|
+
raw = os.environ.get(name)
|
|
53
|
+
return default if raw is None or not raw.strip() else int(raw)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Settings:
|
|
58
|
+
"""Runtime configuration, all overridable by environment variable."""
|
|
59
|
+
|
|
60
|
+
# repr=False: a DSN carries the password, and a repr ends up in logs and tracebacks.
|
|
61
|
+
dsn: str = field(default_factory=lambda: os.environ.get("PGSS_DSN", DEFAULT_DSN), repr=False)
|
|
62
|
+
schemas: tuple[str, ...] = field(
|
|
63
|
+
default_factory=lambda: tuple(
|
|
64
|
+
s.strip()
|
|
65
|
+
for s in os.environ.get("PGSS_SCHEMAS", ",".join(DEFAULT_SCHEMAS)).split(",")
|
|
66
|
+
if s.strip()
|
|
67
|
+
)
|
|
68
|
+
)
|
|
69
|
+
statement_timeout_ms: int = field(
|
|
70
|
+
default_factory=lambda: _env_int("PGSS_STATEMENT_TIMEOUT_MS", 10_000)
|
|
71
|
+
)
|
|
72
|
+
idle_in_transaction_timeout_ms: int = field(
|
|
73
|
+
default_factory=lambda: _env_int("PGSS_IDLE_TX_TIMEOUT_MS", 10_000)
|
|
74
|
+
)
|
|
75
|
+
# Hard ceiling on max_rows, regardless of what the caller asks for.
|
|
76
|
+
max_rows_cap: int = field(default_factory=lambda: _env_int("PGSS_MAX_ROWS_CAP", 1_000))
|
|
77
|
+
# A string cell longer than this is cut, with a marker that says how much was dropped.
|
|
78
|
+
max_cell_chars: int = field(default_factory=lambda: _env_int("PGSS_MAX_CELL_CHARS", 2_000))
|
|
79
|
+
# Ceiling on the JSON size of all rows returned for one query.
|
|
80
|
+
max_result_bytes: int = field(
|
|
81
|
+
default_factory=lambda: _env_int("PGSS_MAX_RESULT_BYTES", 200_000)
|
|
82
|
+
)
|
|
83
|
+
pool_min_size: int = field(default_factory=lambda: _env_int("PGSS_POOL_MIN", 1))
|
|
84
|
+
pool_max_size: int = field(default_factory=lambda: _env_int("PGSS_POOL_MAX", 4))
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def session_options(self) -> str:
|
|
88
|
+
"""libpq `options` string applied to every connection in the pool."""
|
|
89
|
+
return " ".join(
|
|
90
|
+
(
|
|
91
|
+
f"-c statement_timeout={self.statement_timeout_ms}",
|
|
92
|
+
f"-c idle_in_transaction_session_timeout={self.idle_in_transaction_timeout_ms}",
|
|
93
|
+
"-c default_transaction_read_only=on",
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _jsonable(value: Any) -> Any:
|
|
99
|
+
"""Coerce a Postgres value into something that survives JSON serialisation.
|
|
100
|
+
|
|
101
|
+
Decimal becomes a string rather than a float: these are money and quantity
|
|
102
|
+
columns, and silently rounding them would be worse than a type change the
|
|
103
|
+
model can see.
|
|
104
|
+
"""
|
|
105
|
+
match value:
|
|
106
|
+
case None | bool() | int() | float() | str():
|
|
107
|
+
return value
|
|
108
|
+
case Decimal():
|
|
109
|
+
return str(value)
|
|
110
|
+
case dt.datetime() | dt.date() | dt.time():
|
|
111
|
+
return value.isoformat()
|
|
112
|
+
case dt.timedelta():
|
|
113
|
+
return str(value)
|
|
114
|
+
case UUID() | IPv4Address() | IPv6Address() | IPv4Network() | IPv6Network():
|
|
115
|
+
return str(value)
|
|
116
|
+
case bytes() | bytearray() | memoryview():
|
|
117
|
+
return bytes(value).hex()
|
|
118
|
+
case list():
|
|
119
|
+
return [_jsonable(v) for v in value]
|
|
120
|
+
case tuple():
|
|
121
|
+
return [_jsonable(v) for v in value]
|
|
122
|
+
case dict():
|
|
123
|
+
return {str(k): _jsonable(v) for k, v in value.items()}
|
|
124
|
+
case _:
|
|
125
|
+
return str(value)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# Rows are pulled from the server in batches of this size.
|
|
129
|
+
_FETCH_BATCH = 200
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _clip(value: Any, limit: int) -> tuple[Any, bool]:
|
|
133
|
+
"""Cut a long string to `limit` characters. Returns the value and whether it was cut."""
|
|
134
|
+
if isinstance(value, str) and len(value) > limit:
|
|
135
|
+
return f"{value[:limit]}... [{len(value) - limit} more characters]", True
|
|
136
|
+
return value, False
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def _configure(conn: psycopg.AsyncConnection[Any]) -> None:
|
|
140
|
+
"""Runs once per new connection. Every transaction on it then starts as BEGIN READ ONLY.
|
|
141
|
+
|
|
142
|
+
A query can change the session default with set_config('default_transaction_read_only',
|
|
143
|
+
'off', false). It cannot change a transaction that was started read only.
|
|
144
|
+
"""
|
|
145
|
+
await conn.set_read_only(True)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def _reset(conn: psycopg.AsyncConnection[Any]) -> None:
|
|
149
|
+
"""Runs when a connection goes back to the pool. Forgets what the last query left behind.
|
|
150
|
+
|
|
151
|
+
DISCARD ALL drops session-level advisory locks and any session setting a query changed.
|
|
152
|
+
The options passed at connect time (timeouts, read-only default) are the session
|
|
153
|
+
defaults, so they come back as they were.
|
|
154
|
+
"""
|
|
155
|
+
await conn.set_autocommit(True) # DISCARD cannot run inside a transaction block
|
|
156
|
+
try:
|
|
157
|
+
await conn.execute("DISCARD ALL")
|
|
158
|
+
finally:
|
|
159
|
+
await conn.set_autocommit(False)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
_COLUMNS_SQL = """
|
|
163
|
+
SELECT n.nspname AS schema_name,
|
|
164
|
+
c.relname AS table_name,
|
|
165
|
+
a.attname AS column_name,
|
|
166
|
+
format_type(a.atttypid, a.atttypmod) AS data_type,
|
|
167
|
+
NOT a.attnotnull AS nullable,
|
|
168
|
+
pg_get_expr(ad.adbin, ad.adrelid) AS column_default,
|
|
169
|
+
col_description(c.oid, a.attnum) AS column_comment,
|
|
170
|
+
a.attnum AS ordinal
|
|
171
|
+
FROM pg_class c
|
|
172
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
173
|
+
JOIN pg_attribute a ON a.attrelid = c.oid
|
|
174
|
+
LEFT JOIN pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum
|
|
175
|
+
WHERE c.relkind = 'r'
|
|
176
|
+
AND a.attnum > 0
|
|
177
|
+
AND NOT a.attisdropped
|
|
178
|
+
AND n.nspname = ANY(%(schemas)s)
|
|
179
|
+
ORDER BY n.nspname, c.relname, a.attnum
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
_TABLES_SQL = """
|
|
183
|
+
SELECT n.nspname AS schema_name,
|
|
184
|
+
c.relname AS table_name,
|
|
185
|
+
obj_description(c.oid) AS table_comment,
|
|
186
|
+
c.reltuples::bigint AS row_estimate
|
|
187
|
+
FROM pg_class c
|
|
188
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
189
|
+
WHERE c.relkind = 'r' AND n.nspname = ANY(%(schemas)s)
|
|
190
|
+
ORDER BY n.nspname, c.relname
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
_CONSTRAINTS_SQL = """
|
|
194
|
+
SELECT con.contype AS kind,
|
|
195
|
+
con.conname AS constraint_name,
|
|
196
|
+
sn.nspname AS schema_name,
|
|
197
|
+
sc.relname AS table_name,
|
|
198
|
+
(SELECT array_agg(att.attname ORDER BY u.ord)
|
|
199
|
+
FROM unnest(con.conkey) WITH ORDINALITY AS u(attnum, ord)
|
|
200
|
+
JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = u.attnum
|
|
201
|
+
) AS columns,
|
|
202
|
+
tn.nspname AS ref_schema,
|
|
203
|
+
tc.relname AS ref_table,
|
|
204
|
+
(SELECT array_agg(att.attname ORDER BY u.ord)
|
|
205
|
+
FROM unnest(con.confkey) WITH ORDINALITY AS u(attnum, ord)
|
|
206
|
+
JOIN pg_attribute att ON att.attrelid = con.confrelid AND att.attnum = u.attnum
|
|
207
|
+
) AS ref_columns
|
|
208
|
+
FROM pg_constraint con
|
|
209
|
+
JOIN pg_class sc ON sc.oid = con.conrelid
|
|
210
|
+
JOIN pg_namespace sn ON sn.oid = sc.relnamespace
|
|
211
|
+
LEFT JOIN pg_class tc ON tc.oid = con.confrelid
|
|
212
|
+
LEFT JOIN pg_namespace tn ON tn.oid = tc.relnamespace
|
|
213
|
+
WHERE con.contype IN ('p', 'f') AND sn.nspname = ANY(%(schemas)s)
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Database:
|
|
218
|
+
"""Async connection pool, always connected as the read-only role."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, settings: Settings | None = None) -> None:
|
|
221
|
+
self.settings = settings or Settings()
|
|
222
|
+
self._pool: AsyncConnectionPool | None = None
|
|
223
|
+
|
|
224
|
+
async def __aenter__(self) -> Self:
|
|
225
|
+
await self.open()
|
|
226
|
+
return self
|
|
227
|
+
|
|
228
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
229
|
+
await self.close()
|
|
230
|
+
|
|
231
|
+
async def open(self) -> None:
|
|
232
|
+
if self._pool is not None:
|
|
233
|
+
return
|
|
234
|
+
pool = AsyncConnectionPool(
|
|
235
|
+
conninfo=self.settings.dsn,
|
|
236
|
+
min_size=self.settings.pool_min_size,
|
|
237
|
+
max_size=self.settings.pool_max_size,
|
|
238
|
+
kwargs={"options": self.settings.session_options, "row_factory": tuple_row},
|
|
239
|
+
configure=_configure,
|
|
240
|
+
reset=_reset,
|
|
241
|
+
open=False,
|
|
242
|
+
)
|
|
243
|
+
await pool.open(wait=True, timeout=30)
|
|
244
|
+
self._pool = pool
|
|
245
|
+
|
|
246
|
+
async def close(self) -> None:
|
|
247
|
+
if self._pool is not None:
|
|
248
|
+
await self._pool.close()
|
|
249
|
+
self._pool = None
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def pool(self) -> AsyncConnectionPool:
|
|
253
|
+
if self._pool is None:
|
|
254
|
+
raise RuntimeError("Database.open() has not been called")
|
|
255
|
+
return self._pool
|
|
256
|
+
|
|
257
|
+
async def fetch_rows(self, sql: str, max_rows: int) -> QueryResult:
|
|
258
|
+
"""Run an already-guarded SELECT and return at most `max_rows` rows.
|
|
259
|
+
|
|
260
|
+
The caller is responsible for having passed `sql` through guard.py first.
|
|
261
|
+
"""
|
|
262
|
+
limit = max(1, min(max_rows, self.settings.max_rows_cap))
|
|
263
|
+
fetched: list[tuple[Any, ...]] = []
|
|
264
|
+
# The pool's configure step makes this transaction BEGIN READ ONLY.
|
|
265
|
+
#
|
|
266
|
+
# The cursor is a server-side cursor: rows come in small batches, so a query that
|
|
267
|
+
# matches a billion rows costs a few batches, not the whole result in memory. It also
|
|
268
|
+
# sends the statement through the extended protocol, where PostgreSQL refuses a second
|
|
269
|
+
# statement, which is a check that does not depend on the parser.
|
|
270
|
+
async with (
|
|
271
|
+
self.pool.connection() as conn,
|
|
272
|
+
conn.transaction(),
|
|
273
|
+
conn.cursor(name="pgss_query") as cur,
|
|
274
|
+
):
|
|
275
|
+
await cur.execute(psycopg.sql.SQL(sql))
|
|
276
|
+
columns = [d.name for d in cur.description or ()]
|
|
277
|
+
# One row more than the limit: that is how truncation is detected without a
|
|
278
|
+
# second COUNT query.
|
|
279
|
+
while len(fetched) <= limit:
|
|
280
|
+
batch = await cur.fetchmany(min(_FETCH_BATCH, limit + 1 - len(fetched)))
|
|
281
|
+
if not batch:
|
|
282
|
+
break
|
|
283
|
+
fetched.extend(batch)
|
|
284
|
+
|
|
285
|
+
rows: list[list[Any]] = []
|
|
286
|
+
size = 0
|
|
287
|
+
clipped = False
|
|
288
|
+
over_budget = False
|
|
289
|
+
for raw in fetched[:limit]:
|
|
290
|
+
row: list[Any] = []
|
|
291
|
+
for value in raw:
|
|
292
|
+
cell, was_clipped = _clip(_jsonable(value), self.settings.max_cell_chars)
|
|
293
|
+
clipped = clipped or was_clipped
|
|
294
|
+
row.append(cell)
|
|
295
|
+
size += len(json.dumps(row, ensure_ascii=False, default=str))
|
|
296
|
+
if size > self.settings.max_result_bytes:
|
|
297
|
+
over_budget = True
|
|
298
|
+
break
|
|
299
|
+
rows.append(row)
|
|
300
|
+
|
|
301
|
+
truncated = len(fetched) > limit or over_budget
|
|
302
|
+
notes: list[str] = []
|
|
303
|
+
if len(fetched) > limit:
|
|
304
|
+
notes.append(
|
|
305
|
+
f"Truncated to {limit} rows; more rows matched. This is a display limit, not the "
|
|
306
|
+
"full answer. To see the rest, narrow the query: add a WHERE clause, aggregate "
|
|
307
|
+
"with GROUP BY, or raise max_rows (capped at "
|
|
308
|
+
f"{self.settings.max_rows_cap})."
|
|
309
|
+
)
|
|
310
|
+
if over_budget:
|
|
311
|
+
notes.append(
|
|
312
|
+
f"Output stopped at {len(rows)} rows because the result passed "
|
|
313
|
+
f"{self.settings.max_result_bytes} bytes. Select fewer or narrower columns."
|
|
314
|
+
)
|
|
315
|
+
if clipped:
|
|
316
|
+
notes.append(
|
|
317
|
+
f"Text longer than {self.settings.max_cell_chars} characters was cut and marked."
|
|
318
|
+
)
|
|
319
|
+
return QueryResult(
|
|
320
|
+
columns=columns,
|
|
321
|
+
rows=rows,
|
|
322
|
+
row_count=len(rows),
|
|
323
|
+
truncated=truncated,
|
|
324
|
+
note=" ".join(notes) or None,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
async def explain(self, sql: str) -> QueryPlan:
|
|
328
|
+
"""EXPLAIN a guarded SELECT. Never ANALYZE, so the query does not run."""
|
|
329
|
+
async with self.pool.connection() as conn, conn.transaction(), conn.cursor() as cur:
|
|
330
|
+
await cur.execute(psycopg.sql.SQL(f"EXPLAIN (FORMAT JSON) {sql}"))
|
|
331
|
+
row = await cur.fetchone()
|
|
332
|
+
|
|
333
|
+
payload: Any = row[0] if row else None
|
|
334
|
+
top: dict[str, Any] = {}
|
|
335
|
+
if isinstance(payload, list) and payload and isinstance(payload[0], dict):
|
|
336
|
+
top = payload[0].get("Plan", {})
|
|
337
|
+
|
|
338
|
+
async with self.pool.connection() as conn, conn.transaction(), conn.cursor() as cur:
|
|
339
|
+
await cur.execute(psycopg.sql.SQL(f"EXPLAIN {sql}"))
|
|
340
|
+
text_rows = await cur.fetchall()
|
|
341
|
+
|
|
342
|
+
return QueryPlan(
|
|
343
|
+
sql=sql,
|
|
344
|
+
plan="\n".join(str(r[0]) for r in text_rows),
|
|
345
|
+
total_cost=top.get("Total Cost"),
|
|
346
|
+
plan_rows=top.get("Plan Rows"),
|
|
347
|
+
note=(
|
|
348
|
+
"Planner estimate only; the query was not executed. Costs are in arbitrary "
|
|
349
|
+
"planner units, useful for comparing two queries against each other."
|
|
350
|
+
),
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
async def introspect(self) -> list[TableDetail]:
|
|
354
|
+
"""Read the schema once. Called at startup to build the retrieval index."""
|
|
355
|
+
params = {"schemas": list(self.settings.schemas)}
|
|
356
|
+
async with self.pool.connection() as conn, conn.transaction(), conn.cursor() as cur:
|
|
357
|
+
await cur.execute(_TABLES_SQL, params)
|
|
358
|
+
table_rows = await cur.fetchall()
|
|
359
|
+
await cur.execute(_COLUMNS_SQL, params)
|
|
360
|
+
column_rows = await cur.fetchall()
|
|
361
|
+
await cur.execute(_CONSTRAINTS_SQL, params)
|
|
362
|
+
constraint_rows = await cur.fetchall()
|
|
363
|
+
|
|
364
|
+
primary_keys: dict[tuple[str, str], list[str]] = {}
|
|
365
|
+
outgoing: dict[tuple[str, str], list[ForeignKey]] = {}
|
|
366
|
+
incoming: dict[tuple[str, str], list[ForeignKey]] = {}
|
|
367
|
+
|
|
368
|
+
for (
|
|
369
|
+
kind,
|
|
370
|
+
name,
|
|
371
|
+
schema_name,
|
|
372
|
+
table_name,
|
|
373
|
+
cols,
|
|
374
|
+
ref_schema,
|
|
375
|
+
ref_table,
|
|
376
|
+
ref_cols,
|
|
377
|
+
) in constraint_rows:
|
|
378
|
+
key = (schema_name, table_name)
|
|
379
|
+
if kind == "p":
|
|
380
|
+
primary_keys[key] = list(cols or [])
|
|
381
|
+
continue
|
|
382
|
+
if not ref_schema or not ref_table:
|
|
383
|
+
continue
|
|
384
|
+
fk = ForeignKey(
|
|
385
|
+
constraint_name=name,
|
|
386
|
+
columns=list(cols or []),
|
|
387
|
+
references_schema=ref_schema,
|
|
388
|
+
references_table=ref_table,
|
|
389
|
+
references_columns=list(ref_cols or []),
|
|
390
|
+
)
|
|
391
|
+
outgoing.setdefault(key, []).append(fk)
|
|
392
|
+
incoming.setdefault((ref_schema, ref_table), []).append(fk)
|
|
393
|
+
|
|
394
|
+
columns_by_table: dict[tuple[str, str], list[ColumnInfo]] = {}
|
|
395
|
+
for schema_name, table_name, col, dtype, nullable, default, comment, _ord in column_rows:
|
|
396
|
+
key = (schema_name, table_name)
|
|
397
|
+
columns_by_table.setdefault(key, []).append(
|
|
398
|
+
ColumnInfo(
|
|
399
|
+
name=col,
|
|
400
|
+
type=dtype,
|
|
401
|
+
nullable=bool(nullable),
|
|
402
|
+
default=default,
|
|
403
|
+
comment=comment,
|
|
404
|
+
is_primary_key=False,
|
|
405
|
+
)
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
tables: list[TableDetail] = []
|
|
409
|
+
for schema_name, table_name, comment, row_estimate in table_rows:
|
|
410
|
+
key = (schema_name, table_name)
|
|
411
|
+
pk = primary_keys.get(key, [])
|
|
412
|
+
cols = columns_by_table.get(key, [])
|
|
413
|
+
for c in cols:
|
|
414
|
+
c.is_primary_key = c.name in pk
|
|
415
|
+
detail = TableDetail(
|
|
416
|
+
schema_name=schema_name,
|
|
417
|
+
name=table_name,
|
|
418
|
+
qualified_name=f"{schema_name}.{table_name}",
|
|
419
|
+
comment=comment,
|
|
420
|
+
columns=cols,
|
|
421
|
+
primary_key=pk,
|
|
422
|
+
foreign_keys=sorted(outgoing.get(key, []), key=lambda f: f.constraint_name),
|
|
423
|
+
referenced_by=sorted(incoming.get(key, []), key=lambda f: f.constraint_name),
|
|
424
|
+
ddl="",
|
|
425
|
+
row_estimate=int(row_estimate) if row_estimate is not None else None,
|
|
426
|
+
)
|
|
427
|
+
detail.ddl = render_ddl(detail)
|
|
428
|
+
tables.append(detail)
|
|
429
|
+
|
|
430
|
+
return tables
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Pure logic: no network, no disk, no model calls. Never imports from adapters."""
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Render a table as CREATE TABLE text for the model to read."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .types import TableDetail
|
|
6
|
+
|
|
7
|
+
__all__ = ["render_ddl"]
|
|
8
|
+
|
|
9
|
+
_MAX_COMMENT_CHARS = 300
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _one_line(comment: str) -> str:
|
|
13
|
+
"""A database comment as one short line.
|
|
14
|
+
|
|
15
|
+
A comment is text anyone with COMMENT privilege wrote, and it is shown to the model
|
|
16
|
+
inside the DDL. A line break would let it start a line of its own that reads like part
|
|
17
|
+
of the schema, so line breaks become spaces and the length is capped.
|
|
18
|
+
"""
|
|
19
|
+
text = " ".join(comment.splitlines())
|
|
20
|
+
if len(text) > _MAX_COMMENT_CHARS:
|
|
21
|
+
text = text[:_MAX_COMMENT_CHARS] + "..."
|
|
22
|
+
return text
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def render_ddl(table: TableDetail) -> str:
|
|
26
|
+
"""A CREATE TABLE rendering of a table, for the model to read.
|
|
27
|
+
|
|
28
|
+
Deliberately not pg_dump output: no storage parameters, no tablespaces, no
|
|
29
|
+
ownership. Those cost tokens and answer no question a query author has.
|
|
30
|
+
"""
|
|
31
|
+
lines = [f"CREATE TABLE {table.qualified_name} ("]
|
|
32
|
+
body: list[str] = []
|
|
33
|
+
for col in table.columns:
|
|
34
|
+
piece = f" {col.name} {col.type}"
|
|
35
|
+
if not col.nullable:
|
|
36
|
+
piece += " NOT NULL"
|
|
37
|
+
if col.comment:
|
|
38
|
+
piece += f" -- {_one_line(col.comment)}"
|
|
39
|
+
body.append(piece)
|
|
40
|
+
if table.primary_key:
|
|
41
|
+
body.append(f" PRIMARY KEY ({', '.join(table.primary_key)})")
|
|
42
|
+
for fk in table.foreign_keys:
|
|
43
|
+
body.append(
|
|
44
|
+
f" FOREIGN KEY ({', '.join(fk.columns)}) "
|
|
45
|
+
f"REFERENCES {fk.references_schema}.{fk.references_table} "
|
|
46
|
+
f"({', '.join(fk.references_columns)})"
|
|
47
|
+
)
|
|
48
|
+
lines.append(",\n".join(body))
|
|
49
|
+
lines.append(");")
|
|
50
|
+
if table.comment:
|
|
51
|
+
lines.append(f"-- {_one_line(table.comment)}")
|
|
52
|
+
return "\n".join(lines)
|