executor.py
7.43 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
"""校验 + 执行 + 审计。
管线和「用户手改 SQL 后重跑」两条路都走这里,保证任何一条到达业务库的 SQL
都过了同一套闸 —— 只要有第二条不走 guard 的执行路径,前面的防护就白做了。
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Any, Optional
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from ..core import db as core_db
from ..core.db import 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"))
def validate(ds_id: int, sql: str, dialect: str = "mysql") -> guard.GuardResult:
row_limit, _ = limits()
tables, columns, joins = semantic.guard_context(ds_id)
# 一张表都没启用时不拿空集合去卡 —— 那会把所有 SQL 都判成越权,
# 用户会以为是系统坏了。让它过 guard 的其余检查,由建模页去提示先启用表。
res = guard.check(
sql, dialect=dialect,
allowed_tables=tables or None,
columns_by_table=columns or None,
allowed_joins=joins if tables else None,
row_limit=row_limit)
_enrich_join_hints(res, joins)
_enrich_column_hints(res, columns)
return res
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") -> ExecOutcome:
g = validate(ds_id, sql, dialect)
if not g.ok:
return ExecOutcome(False, g, None,
";".join(i.msg for i in g.errors), "guard")
row_limit, timeout_ms = limits()
try:
conn = semantic.connector_for(ds_id)
result = conn.run_sql(g.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(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(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(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(engine) as s:
r = s.get(SqlRun, run_id)
return _run_dict(r, full=True) if r else None