executor.py
12.1 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
"""校验 + 执行 + 审计。
管线和「用户手改 SQL 后重跑」两条路都走这里,保证任何一条到达业务库的 SQL
都过了同一套闸 —— 只要有第二条不走 guard 的执行路径,前面的防护就白做了。
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Any, Callable, Optional
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from ..core import db as core_db
from ..core.db import get_engine
from . import guard, semantic
from .connectors.base import ConnectionFailed, QueryFailed, QueryResult
from .models import SqlRun
log = logging.getLogger(__name__)
@dataclass
class ExecOutcome:
ok: bool
guard: guard.GuardResult
result: Optional[QueryResult] = None
error: str = ""
error_kind: str = "" # guard / connect / query
def limits() -> tuple[int, int]:
cfg = core_db.get_all_config()
return (int(cfg.get("SQL_ROW_LIMIT") or "1000"),
int(cfg.get("SQL_TIMEOUT_MS") or "30000"))
# 校验策略:
# - catalog:确定性编译出来的 SQL(指标、对象读取、数据同步、建模试跑)。表和列对照内省目录,不查关联白名单;
# - ask :模型写的或人手改的 SQL。只能碰本空间已发布绑定覆盖到的表、列和关联,范围为空就拒绝。
# - debug :数据连接里的 SQL 调试台(只有建模的人能用)。在 ask 范围之外,再加上「表与字段」里启用的表
# 和登记的关联 —— 本体还没建好时,实施人员也要能先把取数调通。
POLICIES = ("catalog", "ask", "debug")
# ask 策略的范围提供者:(ds_id) -> (表, {表: 列}, JOIN 键)。默认取本体已发布绑定;测试里可以换掉。
scope_provider: Optional[Callable[[int], tuple[set[str], dict[str, set[str]], set[str]]]] = None
def ask_scope(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
if scope_provider is not None:
return scope_provider(ds_id)
from ..kernel import grounding
return grounding.ask_scope(ds_id)
def debug_scope(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
"""调试台的可查范围 = 本体已发布绑定的范围 ∪ 「表与字段」启用的表(及登记的关联)。"""
tables, columns, joins = ask_scope(ds_id)
tables, columns, joins = set(tables), dict(columns), set(joins)
_, cat_cols = semantic.catalog_context(ds_id, usable_columns_only=True)
deny = semantic.system_tables()
by_id: dict[int, str] = {}
for m in semantic.list_models(ds_id, enabled_only=True):
t = (m["physical_table"] or m["name"]).lower()
if t in deny:
continue
by_id[m["id"]] = t
tables.add(t)
if t in cat_cols:
columns[t] = cat_cols[t]
pairs = [(f"{by_id[r['from_model_id']]}.{r['from_column'].lower()}", f"{by_id[r['to_model_id']]}.{r['to_column'].lower()}")
for r in semantic.list_relations(ds_id, enabled_only=True)
if r["from_model_id"] in by_id and r["to_model_id"] in by_id]
joins |= semantic.conformed_joins(pairs)
return tables, columns, joins
def scope_for(ds_id: int, policy: str = "ask") -> tuple[set[str], dict[str, set[str]], set[str]]:
return debug_scope(ds_id) if policy == "debug" else ask_scope(ds_id)
def validate(ds_id: int, sql: str, dialect: str = "mysql", policy: str = "ask") -> guard.GuardResult:
row_limit, _ = limits()
if policy == "catalog":
tables, columns = semantic.catalog_context(ds_id)
# 还没内省过的数据源不拿空集合去卡(那会把所有 SQL 都判成越权);关联不查 —— SQL 是系统自己编的
res = guard.check(
sql, dialect=dialect,
allowed_tables=tables or None,
columns_by_table=columns or None,
allowed_joins=None,
row_limit=row_limit)
joins: set[str] = set()
else:
tables, columns, joins = scope_for(ds_id, policy)
if not tables:
return guard.GuardResult(False, (sql or "").strip(), [guard.Issue(
"error", "empty_scope", *EMPTY_SCOPE[policy])])
res = guard.check(
sql, dialect=dialect,
allowed_tables=tables,
columns_by_table=columns or None,
allowed_joins=joins,
row_limit=row_limit)
_enrich_join_hints(res, joins)
_deny_system_tables(res, _system_readable(ds_id) if policy == "catalog" else set())
_enrich_column_hints(res, columns)
return res
def _system_readable(ds_id: int) -> set[str]:
"""本体存储数据源上,系统编译出来的 SQL 可以读系统对象的表(预警事件 / 动作记录 / 流程运行)——
它们是本体里的系统对象,编译时已经按本体空间过滤;模型写的 SQL(ask / debug)照样不许碰。"""
try:
from ..kernel import storage, sysobjects
return sysobjects.table_names() if storage.is_storage(ds_id) else set()
except Exception: # noqa: BLE001
return set()
EMPTY_SCOPE = {
"ask": ("这个数据源在当前本体空间里还没有任何已发布的对象或指标绑定,不能直接写 SQL 查询。",
"先把对象类型绑定到数据表(指标绑定取数表达式)并发布,再来提问。"),
"debug": ("这个数据源还没有可查的表。", "到「表与字段」勾选要查的表(或在「数据源」里点「选表」),再来调试。"),
}
def _deny_system_tables(res: guard.GuardResult, allow: set[str] | None = None) -> None:
"""任何策略下都不许碰元数据库自己的表(数据源指向元数据库所在的库时才会遇到)。allow:例外放行的表。"""
hit = sorted(set(res.tables) & (semantic.system_tables() - {t.lower() for t in allow or set()}))
if hit:
res.issues.append(guard.Issue(
"error", "system_table", f"不能查询系统表:{'、'.join(hit)}。", "只查业务表。"))
res.ok = False
def _enrich_column_hints(res: guard.GuardResult, columns: dict[str, set[str]]) -> None:
"""列不存在时,把那张表**真实有的列**列出来。
只说「请改用真实存在的列名」不解决问题 —— 自愈重试拿不到候选,
就会换个同样不存在的列再试一遍(实测用满 2 轮都在同一个坑里打转)。
"""
for issue in res.issues:
if issue.code != "unknown_column":
continue
# guard 把坏列拼成了 "表.列",从消息里把涉及的表捞回来
involved = [t for t in res.tables if t in columns and f"{t}." in issue.msg]
if not involved:
continue
parts = []
for t in involved[:3]:
cols = sorted(columns[t])
shown = "、".join(cols[:40]) + ("…" if len(cols) > 40 else "")
parts.append(f"{t} 可用的列:{shown}")
issue.fix = (";".join(parts)
+ "。如果需要的字段这里没有,说明数据里就没有,"
"请去掉它并在结论中说明,不要换个名字硬猜。")
def _enrich_join_hints(res: guard.GuardResult, joins: set[str]) -> None:
"""JOIN 被拒时,把这几张表之间**实际可用**的关联路径写进 fix。
只说「你这么连不行」没用 —— 自愈重试拿不到可选项,就会继续瞎试别的写法
(实测连试两轮都在同一个地方打转)。要么给出可用路径让它改,
要么明说两表之间没有路径、别关联。
"""
if res.ok or len(res.tables) < 2:
return
involved = set(res.tables)
usable: list[str] = []
for key in joins:
left, right = key.split("=", 1)
lt, rt = left.split(".")[0], right.split(".")[0]
if lt in involved and rt in involved and lt != rt:
usable.append(f"{left} = {right}")
usable.sort()
for issue in res.issues:
if issue.code not in ("undeclared_join", "opaque_join", "cross_join"):
continue
if usable:
issue.fix = ("这些表之间只有以下关联路径可用,请改用其中之一:"
+ ";".join(usable[:8]))
else:
issue.fix = (f"{'、'.join(sorted(involved))} 这几张表之间没有任何已声明的关联路径。"
"请不要关联它们 —— 改成只查其中一张表,"
"拿不到的字段就在结论里说明数据中没有。")
def execute(ds_id: int, sql: str, dialect: str = "mysql", policy: str = "ask") -> ExecOutcome:
g = validate(ds_id, sql, dialect, policy)
if not g.ok:
return ExecOutcome(False, g, None,
";".join(i.msg for i in g.errors), "guard")
# 数据范围:受限对象的表换成带范围条件的子查询(对指标路和自由 SQL 路一视同仁)
from ..kernel import grounding
try:
final_sql = grounding.scope_sql(ds_id, g.sql, dialect)
except ValueError as e:
return ExecOutcome(False, g, None, str(e), "guard")
row_limit, timeout_ms = limits()
try:
conn = semantic.connector_for(ds_id)
result = conn.run_sql(final_sql, row_limit=row_limit, timeout_ms=timeout_ms)
except ConnectionFailed as e:
return ExecOutcome(False, g, None, str(e), "connect")
except QueryFailed as e:
# 这条消息会原样喂给自愈重试,别包装 —— 模型需要看见数据库的原话
return ExecOutcome(False, g, None, str(e), "query")
except Exception as e: # noqa: BLE001
log.exception("执行 SQL 时出现未预期异常 ds=%s", ds_id)
return ExecOutcome(False, g, None, str(e)[:500], "query")
return ExecOutcome(True, g, result)
# ---------------- 审计 ----------------
def log_run(ds_id: int, question: str, sql_text: str, sql_final: str, status: str,
thread_id: str = "", plan: dict | None = None, error: str = "",
row_count: int = 0, duration_ms: int = 0, retry_count: int = 0,
trace: list | None = None) -> int:
with Session(get_engine()) as s:
run = SqlRun(
ds_id=ds_id, thread_id=thread_id or "", question=(question or "")[:60000],
plan_json=json.dumps(plan or {}, ensure_ascii=False)[:60000],
sql_text=(sql_text or "")[:3_000_000],
sql_final=(sql_final or "")[:3_000_000],
status=status, error=(error or "")[:60000],
row_count=row_count, duration_ms=duration_ms, retry_count=retry_count,
trace_json=json.dumps(trace or [], ensure_ascii=False)[:3_000_000])
s.add(run)
s.commit()
return run.id
def rate_run(run_id: int, rating: int) -> None:
with Session(get_engine()) as s:
s.execute(update(SqlRun).where(SqlRun.id == run_id).values(rating=int(rating)))
s.commit()
def _run_dict(r: SqlRun, full: bool = False) -> dict:
out = {"id": r.id, "ds_id": r.ds_id, "thread_id": r.thread_id or "",
"question": r.question or "", "status": r.status,
"row_count": r.row_count, "duration_ms": r.duration_ms,
"retry_count": r.retry_count, "rating": r.rating,
"error": (r.error or "")[:400],
"sql_preview": (r.sql_final or r.sql_text or "")[:300],
"created_at": r.created_at.isoformat() if r.created_at else None}
if full:
def _j(v: str, d: Any) -> Any:
try:
return json.loads(v) if v else d
except Exception: # noqa: BLE001
return d
out.update(sql_text=r.sql_text or "", sql_final=r.sql_final or "",
plan=_j(r.plan_json, {}), trace=_j(r.trace_json, []))
return out
def list_runs(ds_id: int | None = None, limit: int = 30) -> list[dict]:
with Session(get_engine()) as s:
q = select(SqlRun).order_by(SqlRun.id.desc()).limit(limit)
if ds_id:
q = q.where(SqlRun.ds_id == ds_id)
return [_run_dict(r) for r in s.scalars(q).all()]
def get_run(run_id: int) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.get(SqlRun, run_id)
return _run_dict(r, full=True) if r else None