Repository navigation
Expand file tree
/
Copy pathtest_db_adapters.py
More file actions
317 lines (252 loc) · 11.5 KB
/
Copy pathtest_db_adapters.py
File metadata and controls
317 lines (252 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""DB explorer adapters: factory routing, SQLAlchemy (real sqlite), D1 (mocked).
The SQLAlchemy explorer is exercised against a real on-disk SQLite DB (a
SQLAlchemy dialect that ships with Python), proving introspection + execute end
to end. The D1 explorer uses an injected transport so its request/response
handling is tested with no network.
"""
from __future__ import annotations
import asyncio
import pytest
from lang2sql.adapters.db import (
D1Explorer,
SqlAlchemyExplorer,
build_explorer,
explorer_from_env,
)
from lang2sql.core.ports.explorer import QueryTimeoutUnsupportedError
# --- factory routing -------------------------------------------------------
def test_factory_routes_d1():
exp = build_explorer("d1://acct123/db456")
assert isinstance(exp, D1Explorer)
assert exp.account_id == "acct123" and exp.database_id == "db456"
def test_factory_routes_sqlalchemy_without_connecting():
# No psycopg installed here; routing must not import a driver or connect.
exp = build_explorer("postgresql+psycopg://u:p@h/db")
assert isinstance(exp, SqlAlchemyExplorer)
assert exp._engine is None # lazy: not built yet
def test_factory_rejects_empty_and_schemeless():
for bad in ["", " ", "just-a-name"]:
with pytest.raises(ValueError):
build_explorer(bad)
def test_factory_bad_d1_url():
with pytest.raises(ValueError):
build_explorer("d1://account-only")
def test_explorer_from_env(monkeypatch):
monkeypatch.delenv("LANG2SQL_DB_URL", raising=False)
monkeypatch.delenv("CLOUDFLARE_D1_ACCOUNT_ID", raising=False)
monkeypatch.delenv("CLOUDFLARE_D1_DATABASE_ID", raising=False)
assert explorer_from_env() is None
monkeypatch.setenv("LANG2SQL_DB_URL", "duckdb:///:memory:")
assert isinstance(explorer_from_env(), SqlAlchemyExplorer)
monkeypatch.delenv("LANG2SQL_DB_URL")
monkeypatch.setenv("CLOUDFLARE_D1_ACCOUNT_ID", "a")
monkeypatch.setenv("CLOUDFLARE_D1_DATABASE_ID", "b")
assert isinstance(explorer_from_env(), D1Explorer)
# --- SQLAlchemy explorer against real SQLite -------------------------------
def _seed_sqlite(path: str) -> None:
from sqlalchemy import create_engine, text
eng = create_engine(f"sqlite:///{path}")
with eng.begin() as conn:
conn.execute(
text("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL)")
)
conn.execute(
text("INSERT INTO users (id, email) VALUES (1, 'a@x.com'), (2, 'b@x.com')")
)
def test_sqlalchemy_explorer_introspect_and_execute(tmp_path):
db = tmp_path / "demo.db"
_seed_sqlite(str(db))
exp = SqlAlchemyExplorer(f"sqlite:///{db}")
tables = asyncio.run(exp.list_tables())
assert "users" in {t.name for t in tables}
desc = asyncio.run(exp.describe_table("users"))
cols = {c.name: c for c in desc.columns}
assert set(cols) == {"id", "email"}
assert cols["email"].nullable is False
rows = asyncio.run(exp.execute("SELECT email FROM users ORDER BY id"))
assert rows == [{"email": "a@x.com"}, {"email": "b@x.com"}]
sample = asyncio.run(exp.sample_rows("users", limit=1))
assert len(sample) == 1
metadata = asyncio.run(exp.catalog_metadata())
assert metadata["tables"]["users"]["primary_key"] == ["id"]
def test_sqlalchemy_explorer_describes_names_in_its_configured_schema(tmp_path):
db = tmp_path / "demo.db"
_seed_sqlite(str(db))
exp = SqlAlchemyExplorer(f"sqlite:///{db}", schema="main")
qualified = asyncio.run(exp.describe_table("main.users"))
bare = asyncio.run(exp.describe_table("users"))
assert qualified == bare
assert qualified.qualified == "main.users"
assert [column.name for column in qualified.columns] == ["id", "email"]
def test_run_sql_enforces_safety_deadline_and_reuses_connection(tmp_path):
from lang2sql.core.identity import Identity
from lang2sql.safety.pipeline import SafetyPipeline
from lang2sql.tenancy.tool_runtime import build_tool_context
from lang2sql.tools.run_sql import RunSQL
class ShortDeadline:
def evaluate(self, sql, context):
context.timeout_seconds = 0.01
return SafetyPipeline().evaluate(sql, context)
_seed_sqlite(str(tmp_path / "timeout.db"))
explorer = SqlAlchemyExplorer(f"sqlite:///{tmp_path / 'timeout.db'}")
ctx = build_tool_context(
Identity(user_id="test"), store_path=":memory:", explorer=explorer
)
ctx.safety = ShortDeadline()
query = "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<2000000) SELECT SUM(x) AS total FROM n"
try:
blocked = asyncio.run(RunSQL().run({"sql": query}, ctx))
assert blocked.is_error and "query_timeout" in blocked.content
# The timed-out progress handler must not leak into the pooled connection.
assert asyncio.run(explorer.execute(query.replace("2000000", "20000"))) == [
{"total": 200010000}
]
result = asyncio.run(RunSQL().run({"sql": "SELECT 42 AS value"}, ctx))
assert not result.is_error and "42" in result.content
assert "query_timeout_enforced=true" in result.content
assert "query_timeout_scope=driver_interrupt" in result.content
finally:
ctx.store.close()
explorer._get_engine().dispose()
def test_sqlite_deadline_covers_fetch_and_preserves_other_errors(tmp_path):
from sqlalchemy.exc import OperationalError
_seed_sqlite(str(tmp_path / "fetch.db"))
explorer = SqlAlchemyExplorer(f"sqlite:///{tmp_path / 'fetch.db'}")
query = "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<2000000) SELECT x FROM n"
try:
assert asyncio.run(explorer.execute_with_timeout(query, 1, 0.01)) == [{"x": 1}]
with pytest.raises(TimeoutError, match="deadline"):
asyncio.run(explorer.execute_with_timeout(query, 2000000, 0.01))
with pytest.raises(OperationalError, match="syntax"):
asyncio.run(explorer.execute_with_timeout("SELECT FROM", 1, 1))
assert asyncio.run(explorer.execute(query.replace("2000000", "20000"), 20000))[
-1
] == {"x": 20000}
finally:
explorer._get_engine().dispose()
def test_legacy_explorer_reports_timeout_not_enforced():
class LegacyExplorer:
async def execute(self, sql, limit):
return [{"value": 1}]
from lang2sql.core.identity import Identity
from lang2sql.tenancy.tool_runtime import build_tool_context
from lang2sql.tools.run_sql import RunSQL
ctx = build_tool_context(
Identity(user_id="test"), store_path=":memory:", explorer=LegacyExplorer()
)
try:
result = asyncio.run(RunSQL().run({"sql": "SELECT 1"}, ctx))
assert not result.is_error
assert "query_timeout_enforced=false" in result.content
assert "query_timeout_scope=unsupported" in result.content
finally:
ctx.store.close()
# --- D1 explorer with mocked HTTP transport --------------------------------
def _d1_transport(sql, params):
"""Fake the D1 HTTP API: shape responses by the SQL it receives."""
s = sql.lower()
if "sqlite_master" in s:
results = [{"name": "orders"}, {"name": "users"}]
elif "pragma table_info" in s:
results = [
{
"cid": 0,
"name": "id",
"type": "INTEGER",
"notnull": 1,
"dflt_value": None,
"pk": 1,
},
{
"cid": 1,
"name": "amount",
"type": "REAL",
"notnull": 0,
"dflt_value": None,
"pk": 0,
},
]
elif "pragma foreign_key_list" in s:
results = []
else:
results = [{"id": 1, "amount": 9.5}]
return {
"success": True,
"result": [{"results": results, "success": True}],
"errors": [],
}
def test_d1_list_describe_and_fail_closed_execute():
exp = D1Explorer("acct", "db", token="t", transport=_d1_transport)
tables = asyncio.run(exp.list_tables())
assert {t.name for t in tables} == {"orders", "users"}
desc = asyncio.run(exp.describe_table("orders"))
cols = {c.name: c for c in desc.columns}
assert cols["id"].nullable is False and cols["amount"].nullable is True
with pytest.raises(QueryTimeoutUnsupportedError, match="statement cancellation"):
asyncio.run(exp.execute("SELECT * FROM orders", timeout_seconds=1))
metadata = asyncio.run(exp.catalog_metadata())
assert metadata["tables"]["orders"]["primary_key"] == ["id"]
def test_d1_raises_on_api_error():
def failing(sql, params):
return {"success": False, "errors": [{"message": "bad token"}], "result": []}
exp = D1Explorer("acct", "db", token="t", transport=failing)
with pytest.raises(RuntimeError, match="D1 query failed"):
asyncio.run(exp.list_tables())
def test_d1_rejects_unsafe_identifier():
exp = D1Explorer("acct", "db", token="t", transport=_d1_transport)
with pytest.raises(ValueError, match="unsafe table identifier"):
asyncio.run(exp.describe_table("users; DROP TABLE x"))
@pytest.mark.asyncio
async def test_view_discovery_and_qualified_columns(tmp_path):
from sqlalchemy import create_engine, text
db = tmp_path / "views.db"
engine = create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(text("CREATE TABLE orders (amount INTEGER)"))
conn.execute(text("CREATE VIEW net_sales AS SELECT amount FROM orders"))
exp = SqlAlchemyExplorer(f"sqlite:///{db}", schema="main")
objects = {t.name: t for t in await exp.list_tables()}
assert objects["orders"].kind == "table"
assert objects["net_sales"].kind == "view"
view = await exp.describe_table("main.net_sales")
assert view.kind == "view" and [c.name for c in view.columns] == ["amount"]
@pytest.mark.asyncio
async def test_composite_keys_reach_schema_tool_without_guessing(tmp_path):
from sqlalchemy import create_engine, text
from lang2sql.core.identity import Identity
from lang2sql.tenancy.concierge import ContextConcierge
from lang2sql.tools.explore_schema import ExploreSchema
db = tmp_path / "keys.db"
engine = create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(
text(
"CREATE TABLE parent (tenant TEXT, id INTEGER, PRIMARY KEY (tenant, id))"
)
)
conn.execute(
text(
"CREATE TABLE child (tenant TEXT, parent_id INTEGER, FOREIGN KEY (tenant, parent_id) REFERENCES parent (tenant, id))"
)
)
conn.execute(text("CREATE VIEW child_view AS SELECT * FROM child"))
exp = SqlAlchemyExplorer(f"sqlite:///{db}")
assert (await exp.describe_table("parent")).primary_key == ["tenant", "id"]
child = await exp.describe_table("child")
assert child.foreign_keys[0].columns == ["tenant", "parent_id"]
assert child.foreign_keys[0].referred_columns == ["tenant", "id"]
assert (await exp.describe_table("child_view")).foreign_keys == []
concierge = ContextConcierge(explorer=exp)
try:
ctx = await concierge.build_context(Identity(user_id="test"))
result = await ExploreSchema().run({"table": "child"}, ctx)
assert (
"FOREIGN KEY (tenant, parent_id) REFERENCES parent (tenant, id)"
in result.content
)
result = await ExploreSchema().run({"table": "parent"}, ctx)
assert "PRIMARY KEY (tenant, id)" in result.content
finally:
concierge.store.close()
engine.dispose()
exp._engine.dispose()