text2sql.py
19.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
"""数据连接接口:数据源 / 表结构 / 关联 / SQL 调试台(问答 SSE、校验、执行、解释)/ 运行记录 / 沉淀库。"""
from __future__ import annotations
import logging
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
from sse_starlette.sse import EventSourceResponse
from ..core import db, identity, llm
from ..jobs.queue import runner
from ..schemas import (
AskRequest, ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest,
ExplainRequest, ModelUpdate, PairUpsert, ProbeRequest,
RelationUpsert, RunSqlRequest, SummarizeRequest, ThreadUpsert,
)
from ..text2sql import crypto, describe, executor, introspect, library, prompts, semantic, threads
from ..text2sql.connectors import registry
from ..text2sql.connectors.base import ConnectionFailed
from ..text2sql.pipeline import run_ask
from . import deps
log = logging.getLogger(__name__)
# 数据源按本体空间归属:每个请求都要先解析身份(带出 X-Workspace)
router = APIRouter(prefix="/api/sql", tags=["text2sql"], dependencies=[Depends(identity.resolve)])
def _need_ds(ds_id: int) -> dict:
ds = semantic.get_datasource(ds_id)
if ds is None:
raise HTTPException(404, "数据源不存在")
return ds
def _policy(scope: str) -> str:
"""调试台的范围更宽(含「表与字段」里启用的表),只给建模的人用。"""
if scope == "debug":
if not identity.current().can("build"):
raise HTTPException(403, "SQL 调试台只有建模的人可以用")
return "debug"
return "ask"
def _need_crypto() -> None:
if not crypto.available():
raise HTTPException(400, "未配置 SECRET_KEY,无法安全保存数据源口令。"
"请在 .env 里设置一个足够长的随机串后重启服务。")
# ---------------- 元信息 ----------------
@router.get("/meta")
async def meta():
return {"supported_types": registry.supported_types(),
"crypto_ready": crypto.available(),
"row_limit": executor.limits()[0],
"timeout_ms": executor.limits()[1]}
# ---------------- 数据源 ----------------
@router.get("/datasources")
async def list_datasources():
return semantic.list_datasources()
@router.post("/datasources")
async def create_datasource(payload: DataSourceCreate):
_need_crypto()
ds_id = semantic.create_datasource(**payload.model_dump())
return semantic.get_datasource(ds_id)
_CONN_HINTS = (("access denied", "用户名或口令不对"), ("password authentication failed", "用户名或口令不对"),
("unknown database", "数据库不存在"), ("does not exist", "数据库不存在"),
("can't connect", "连不上主机或端口"), ("could not connect", "连不上主机或端口"),
("timed out", "连接超时,检查主机、端口和网络"), ("name or service not known", "主机名解析不了"))
def _conn_error(e: Exception) -> str:
"""连接失败的原因先说人话,原始报错留在后面方便实施人员查。"""
raw = str(e)[:500]
hint = next((h for k, h in _CONN_HINTS if k in raw.lower()), "")
return f"连接失败:{hint}({raw})" if hint else f"连接失败:{raw}"
def _table_rows(tables) -> list[dict]:
deny = semantic.system_tables()
return [{"name": t.name, "kind": t.kind, "comment": t.comment, "row_count_est": t.row_count_est}
for t in tables if t.name.lower() not in deny]
@router.post("/datasources/probe")
async def probe_datasource(payload: ProbeRequest):
"""测试连接 + 列出表,不保存。新建时先测通、再勾选要接入的表。"""
fields = payload.model_dump()
ds_id = fields.pop("ds_id")
password = fields.pop("password")
if not password and ds_id:
old = semantic.get_datasource(ds_id, with_secret=True)
if old is None:
raise HTTPException(404, "数据源不存在")
password = old.get("password", "")
conn = registry.build({"id": ds_id, **fields}, password)
try:
info = conn.test()
tables = _table_rows(conn.list_tables())
except Exception as e: # noqa: BLE001
raise HTTPException(400, _conn_error(e)) from e
finally:
conn.dispose()
if info.get("account_writable"):
info["warning"] = "这个账号有写权限。生成的 SQL 有只读校验兜底,但仍建议改用只读账号。"
return {**info, "tables": tables}
@router.post("/datasources/file")
async def create_file_datasource(name: str = Form(...), ds_id: int = Form(0),
files: list[UploadFile] = File(...)):
"""本地文件数据源:CSV / Excel / JSON 导入成一个只读 SQLite 库。传 ds_id 表示往已有的文件数据源里追加。"""
from ..core.config import get_settings
from ..text2sql.connectors import sqlite_file
ups = [(f.filename or "data.csv", await f.read()) for f in files]
bad = [n for n, _ in ups if not n.lower().endswith(sqlite_file.FILE_TYPES)]
if bad:
raise HTTPException(422, f"不支持的文件:{'、'.join(bad)}(支持 {'、'.join(sqlite_file.FILE_TYPES)})")
if ds_id:
ds = _need_ds(ds_id)
if ds["ds_type"] != "sqlite":
raise HTTPException(422, "只能往本地文件数据源里追加文件")
path = ds["db_name"]
else:
ds_id = semantic.create_datasource(name=name[:128], ds_type="sqlite", host="local", port=0,
db_name="", username="")
path = str(get_settings().data_path / "files" / f"ds_{ds_id}.sqlite")
semantic.update_datasource(ds_id, db_name=path)
from pathlib import Path
try:
tables = sqlite_file.import_files(Path(path), ups)
except (ValueError, KeyError) as e:
if not semantic.list_models(ds_id):
semantic.delete_datasource(ds_id)
raise HTTPException(422, f"文件导入失败:{e}") from e
registry.evict(ds_id)
semantic.mark_datasource(ds_id, "ok", "")
return {**semantic.get_datasource(ds_id), "imported": tables}
@router.get("/datasources/{ds_id}")
async def get_datasource(ds_id: int):
return _need_ds(ds_id)
@router.put("/datasources/{ds_id}")
async def update_datasource(ds_id: int, payload: DataSourceUpdate):
_need_ds(ds_id)
fields = payload.model_dump(exclude_unset=True)
if "password" in fields:
_need_crypto()
semantic.update_datasource(ds_id, **fields)
return semantic.get_datasource(ds_id)
@router.delete("/datasources/{ds_id}")
async def delete_datasource(ds_id: int):
_need_ds(ds_id)
semantic.delete_datasource(ds_id)
from ..memory import service as memory
memory.drop_sql_hints_of(ds_id)
return {"ok": True}
@router.post("/datasources/{ds_id}/test")
async def test_datasource(ds_id: int):
_need_ds(ds_id)
try:
# 用 fresh 连接器:坏配置不该进连接池缓存
info = semantic.connector_for(ds_id, fresh=True).test()
except ConnectionFailed as e:
semantic.mark_datasource(ds_id, "error", str(e))
raise HTTPException(400, f"连接失败:{e}") from e
except Exception as e: # noqa: BLE001
semantic.mark_datasource(ds_id, "error", str(e))
raise HTTPException(400, str(e)[:500]) from e
semantic.mark_datasource(ds_id, "ok", "")
if info.get("account_writable"):
info["warning"] = "这个账号有写权限。生成的 SQL 有只读校验兜底,但仍建议改用只读账号。"
return info
@router.get("/datasources/{ds_id}/tables")
async def datasource_tables(ds_id: int):
"""已保存数据源的全部表(不受表范围限制),「选表」用。"""
_need_ds(ds_id)
try:
return _table_rows(semantic.connector_for(ds_id).list_tables())
except ConnectionFailed as e:
raise HTTPException(400, _conn_error(e)) from e
@router.post("/datasources/{ds_id}/introspect")
async def start_introspect(ds_id: int, resample: bool = False):
_need_ds(ds_id)
job_id = db.create_job(0, job_type="introspect")
ok = runner.submit(job_id, lambda: introspect.run_introspection(ds_id, resample))
return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}
# ---------------- 建模 ----------------
@router.get("/datasources/{ds_id}/models")
async def list_models(ds_id: int, enabled_only: bool = False):
_need_ds(ds_id)
return semantic.models_with_columns(ds_id, enabled_only=enabled_only)
@router.put("/models/{model_id}")
async def update_model(model_id: int, payload: ModelUpdate):
fields = payload.model_dump(exclude_unset=True)
if "enabled" in fields:
fields["enabled"] = 1 if fields["enabled"] else 0
semantic.update_model(model_id, **fields)
return {"ok": True}
@router.put("/columns/{column_id}")
async def update_column(column_id: int, payload: ColumnUpdate):
fields = payload.model_dump(exclude_unset=True)
for k in ("is_dimension", "is_measure", "enabled"):
if k in fields:
fields[k] = 1 if fields[k] else 0
semantic.update_column(column_id, **fields)
return {"ok": True}
@router.get("/datasources/{ds_id}/relations")
async def list_relations(ds_id: int):
_need_ds(ds_id)
return semantic.list_relations(ds_id)
@router.post("/datasources/{ds_id}/relations")
async def upsert_relation(ds_id: int, payload: RelationUpsert):
_need_ds(ds_id)
fields = payload.model_dump()
fields["enabled"] = 1 if fields.pop("enabled", True) else 0
models = {m["id"]: m for m in semantic.list_models(ds_id)}
fm, tm = models.get(fields["from_model_id"]), models.get(fields["to_model_id"])
if not fm or not tm:
raise HTTPException(400, "关系两端必须是这个数据源下已存在的表")
ft = fm["physical_table"] or fm["name"]
tt = tm["physical_table"] or tm["name"]
fields["condition_sql"] = f"{ft}.{fields['from_column']} = {tt}.{fields['to_column']}"
if not fields.get("name"):
fields["name"] = f"{ft}_{tt}"
rel_id = semantic.upsert_relation(ds_id, **fields)
return {"ok": True, "id": rel_id}
@router.delete("/relations/{rel_id}")
async def delete_relation(rel_id: int):
semantic.delete_relation(rel_id)
return {"ok": True}
@router.post("/datasources/{ds_id}/describe")
async def start_describe(ds_id: int, payload: DescribeRequest):
"""让大模型给已启用的表批量补描述与同义词(后台任务)。
同义词是召回能不能命中的关键:物理列叫 sum_ax_package,
业务同事说的是「会员服务卖了多少」,中间这层映射得补上。
"""
_need_ds(ds_id)
job_id = db.create_job(0, job_type="describe")
ok = runner.submit(job_id, lambda: describe.run_describe(
ds_id, overwrite=payload.overwrite, model_ids=payload.model_ids or None))
return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}
@router.get("/datasources/{ds_id}/relations/recommend")
async def recommend_relations(ds_id: int):
"""这个库没有外键,靠列名 + 真实取值重叠率推关联路径。"""
_need_ds(ds_id)
return semantic.recommend_relations(ds_id)
# ---------------- 指标(只读:来自本体里绑定到这个数据源的聚合函数) ----------------
@router.get("/datasources/{ds_id}/metrics")
async def list_metrics(ds_id: int, enabled_only: bool = False):
_need_ds(ds_id)
return semantic.list_metrics(ds_id, enabled_only=enabled_only)
@router.get("/datasources/{ds_id}/metrics/issues")
async def metric_issues(ds_id: int):
"""指标自检:表达式引用的列是不是都还可用。有问题的指标不会进提示词。"""
_need_ds(ds_id)
return semantic.metric_issues(ds_id)
# ---------------- SQL 调试台 ----------------
@router.post("/ask")
async def ask(payload: AskRequest, request: Request):
"""问一句 → 召回 → 计划 → 生成 SQL → 校验/自愈 → 执行 → 结论,全过程按事件推给前端。"""
_need_ds(payload.ds_id)
question = payload.question.strip()
gen = run_ask(payload.ds_id, question, history=payload.history,
overrides=payload.overrides, thread_id=payload.thread_id, policy=_policy(payload.scope))
if payload.thread_id and payload.scope == "debug":
threads.check(payload.thread_id)
gen = threads.record(gen, payload.ds_id, question, payload.thread_id)
return EventSourceResponse(deps.sse(gen, request))
@router.post("/validate")
async def validate_sql(payload: RunSqlRequest):
"""只校验不执行。SQL 编辑器里边打边给反馈用。"""
ds = _need_ds(payload.ds_id)
return executor.validate(payload.ds_id, payload.sql, ds["ds_type"], _policy(payload.scope)).as_dict()
@router.post("/run")
async def run_sql(payload: RunSqlRequest):
"""执行用户手改过的 SQL。和管线走同一套 guard —— 不能有第二条绕过校验的路径。
提问页答案卡的「改 SQL 重跑」带的是 run_id:在那次取数的基础上改。"""
if payload.run_id:
base = executor.get_run(payload.run_id)
if base is None:
raise HTTPException(404, "找不到这次取数记录")
payload.ds_id = payload.ds_id or int(base["ds_id"])
payload.question = payload.question or str(base.get("question") or "")
payload.origin_sql = payload.origin_sql or str(base.get("sql_final") or base.get("sql_text") or "")
if not payload.ds_id:
raise HTTPException(422, "要指定数据源")
ds = _need_ds(payload.ds_id)
outcome = executor.execute(payload.ds_id, payload.sql, ds["ds_type"], _policy(payload.scope))
if payload.thread_id:
threads.check(payload.thread_id)
if not outcome.ok:
# 失败的重跑不进会话:会话里那一轮保持原样,报错只在界面上提示
executor.log_run(
payload.ds_id, payload.question, payload.sql, payload.sql,
"invalid" if outcome.error_kind == "guard" else "error", error=outcome.error)
raise HTTPException(400, detail=outcome.error)
r = outcome.result
snap = None
if payload.thread_id:
snap = threads.snapshot(outcome="ok", columns=r.columns, rows=r.rows, truncated=r.truncated,
issues=[i.as_dict() for i in outcome.guard.issues], summary="",
replaces=payload.replaces, manual=not payload.question.strip())
run_id = executor.log_run(
payload.ds_id, payload.question, payload.origin_sql or payload.sql,
outcome.guard.sql, "ok", thread_id=payload.thread_id,
row_count=r.row_count, duration_ms=r.duration_ms, trace=snap)
if payload.thread_id:
threads.touch(payload.thread_id, payload.question)
pair_id = 0
if payload.question.strip():
# 用户改过 SQL 再跑通,是最值钱的信号:它直接标出了模型的系统性偏差。
edited = bool(payload.origin_sql and payload.origin_sql.strip() != payload.sql.strip())
try:
pair_id = library.capture(
payload.ds_id, payload.question, outcome.guard.sql,
source="user_edited" if edited else "auto", run_id=run_id,
models_used=outcome.guard.tables,
sql_before=payload.origin_sql if edited else "")
except Exception: # noqa: BLE001
log.exception("沉淀问答对失败")
return {"ok": True, "run_id": run_id, "pair_id": pair_id,
"columns": r.columns, "rows": r.rows, "row_count": r.row_count,
"duration_ms": r.duration_ms, "truncated": r.truncated,
"sql": outcome.guard.sql, "limited": outcome.guard.limited,
"issues": [i.as_dict() for i in outcome.guard.issues]}
@router.post("/explain")
async def explain(payload: ExplainRequest):
"""用业务语言解释一条 SQL。界面上默认折叠,展开了才生成。"""
_need_ds(payload.ds_id)
text = llm.chat(prompts.build_explain_messages(payload.question, payload.sql), temperature=0.3)
return {"ok": True, "text": text}
@router.post("/summarize")
async def summarize(payload: SummarizeRequest):
"""手改 SQL 重跑后,对新结果重新出结论 —— 旧结论挂在新表格上比没有结论更糟。"""
_need_ds(payload.ds_id)
text = llm.chat(prompts.build_summary_messages(
payload.question, payload.columns, payload.rows,
payload.row_count or len(payload.rows)), temperature=0.3)
if payload.run_id:
threads.patch_snapshot(payload.run_id, summary=text)
return {"ok": True, "text": text}
# ---------------- 调试台会话 ----------------
@router.get("/threads")
async def list_threads(ds_id: int):
_need_ds(ds_id)
return threads.list_threads(ds_id)
@router.post("/threads")
async def create_thread(payload: ThreadUpsert):
_need_ds(payload.ds_id)
_policy("debug")
return threads.create(payload.ds_id, payload.title)
@router.get("/threads/{thread_id}")
async def get_thread(thread_id: str):
return threads.get(thread_id)
@router.put("/threads/{thread_id}")
async def rename_thread(thread_id: str, payload: ThreadUpsert):
return threads.rename(thread_id, payload.title)
@router.delete("/threads/{thread_id}")
async def delete_thread(thread_id: str):
threads.delete(thread_id)
return {"ok": True}
# ---------------- 运行记录 ----------------
@router.get("/runs")
async def list_runs(ds_id: int | None = None, limit: int = 30):
return executor.list_runs(ds_id, limit)
@router.get("/runs/{run_id}")
async def get_run(run_id: int):
r = executor.get_run(run_id)
if not r:
raise HTTPException(404, "记录不存在")
return r
@router.post("/runs/{run_id}/rate")
async def rate_run(run_id: int, rating: int = 0):
if not executor.get_run(run_id):
raise HTTPException(404, "记录不存在")
executor.rate_run(run_id, max(-1, min(1, rating)))
return {"ok": True}
# ---------------- 沉淀库(问题 ↔ SQL,采纳过的进 few-shot) ----------------
@router.get("/pairs")
async def list_pairs(ds_id: int | None = None, status: str | None = None,
keyword: str = "", limit: int = 100):
return library.list_pairs(ds_id, status, keyword, limit)
@router.post("/pairs")
async def create_pair(payload: PairUpsert):
if not payload.ds_id or not payload.question or not payload.sql:
raise HTTPException(400, "数据源、问题、SQL 都不能为空")
_need_ds(payload.ds_id)
pair_id = library.capture(payload.ds_id, payload.question, payload.sql,
source="user_saved", status=payload.status or "verified")
if payload.status:
library.set_status(pair_id, payload.status)
if payload.note:
library.update_pair(pair_id, note=payload.note)
return {"ok": True, "id": pair_id}
@router.put("/pairs/{pair_id}")
async def update_pair(pair_id: int, payload: PairUpsert):
if not library.get_pair(pair_id):
raise HTTPException(404, "记录不存在")
fields = payload.model_dump(exclude_unset=True, exclude_none=True)
fields.pop("ds_id", None)
status = fields.pop("status", None)
if fields:
library.update_pair(pair_id, **fields)
if status:
library.set_status(pair_id, status)
return library.get_pair(pair_id)
@router.post("/pairs/{pair_id}/adopt")
async def adopt_pair(pair_id: int):
"""把草稿升成已采纳。只有采纳过的才会进 few-shot。"""
if not library.get_pair(pair_id):
raise HTTPException(404, "记录不存在")
library.set_status(pair_id, "verified")
return library.get_pair(pair_id)
@router.delete("/pairs/{pair_id}")
async def delete_pair(pair_id: int):
library.delete_pair(pair_id)
return {"ok": True}