text2sql.py
10.8 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
"""数据连接接口:数据源 / 表结构 / 关联 / 手改 SQL 执行。"""
from __future__ import annotations
import logging
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from ..core import db, identity
from ..jobs.queue import runner
from ..schemas import (
ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest,
EnableModelsRequest, ModelUpdate, RelationUpsert, RunSqlRequest,
)
from ..text2sql import crypto, describe, executor, introspect, library, semantic
from ..text2sql.connectors import registry
from ..text2sql.connectors.base import ConnectionFailed
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 _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)
@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)
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.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.post("/datasources/{ds_id}/models/enable")
async def enable_models(ds_id: int, payload: EnableModelsRequest):
_need_ds(ds_id)
n = semantic.set_models_enabled(ds_id, payload.ids, payload.enabled)
return {"ok": True, "changed": n}
@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}/mdl")
async def export_mdl(ds_id: int):
_need_ds(ds_id)
return semantic.export_mdl(ds_id)
@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"])
if not outcome.ok:
run_id = executor.log_run(
payload.ds_id, payload.question, payload.sql, payload.sql,
"invalid" if outcome.error_kind == "guard" else "error",
thread_id=payload.thread_id, error=outcome.error)
raise HTTPException(400, detail=outcome.error)
r = outcome.result
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)
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]}