mysql.py
11.4 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
"""MySQL 连接器。
安全上有三层,这里负责最外和最内两层:
- 连接层:连接串里带 `autocommit`,不开事务,减少长事务风险;
- 执行层:`MAX_EXECUTION_TIME` 会话变量 + optimizer hint 双保险,再加 fetchmany 行数硬截断。
中间那层(SQL 只读性)在 guard.py,跟连接器无关。
行数截断刻意用 `fetchmany` 而不是信任 SQL 里的 LIMIT —— guard 会补 LIMIT,
但用户可以手改 SQL,最后一道闸必须落在游标上。
"""
from __future__ import annotations
import logging
import time
from typing import Any
from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from .base import (
ColumnInfo, ConnectionFailed, Connector, ForeignKeyInfo, Introspection,
QueryFailed, QueryResult, TableInfo,
)
log = logging.getLogger(__name__)
# 内省时跳过的系统库。用户填的 db_name 正常不会是这些,但视图/外键可能指过去。
_SYSTEM_SCHEMAS = {"information_schema", "performance_schema", "mysql", "sys"}
# 不做值采样的列:列名命中这些片段就跳过,避免把手机号、身份证之类的抓进提示词。
_PII_HINTS = ("phone", "mobile", "tel", "idcard", "id_card", "email", "mail",
"passwd", "password", "token", "secret", "addr", "address",
"name_cn", "realname", "real_name", "身份证", "手机", "邮箱", "地址")
class MySQLConnector(Connector):
dialect = "mysql"
def __init__(self, ds: dict, password: str):
super().__init__(ds, password)
self._engine: Engine | None = None
# ---------- 连接 ----------
@property
def engine(self) -> Engine:
if self._engine is None:
from urllib.parse import quote_plus
url = (f"mysql+pymysql://{quote_plus(self.ds['username'])}:{quote_plus(self.password)}"
f"@{self.ds['host']}:{int(self.ds['port'])}/{self.ds['db_name']}?charset=utf8mb4")
self._engine = create_engine(
url, pool_pre_ping=True, pool_recycle=1800, pool_size=3, max_overflow=2,
future=True, connect_args={"connect_timeout": 10})
return self._engine
def dispose(self) -> None:
if self._engine is not None:
self._engine.dispose()
self._engine = None
def test(self) -> dict:
try:
with self.engine.connect() as c:
version = c.execute(sa_text("SELECT VERSION()")).scalar_one()
current_db = c.execute(sa_text("SELECT DATABASE()")).scalar_one()
tables = c.execute(sa_text(
"SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()"
)).scalar_one()
# 探一下这个账号是不是真的只有读权限。拿不到就算了,不影响连接可用。
writable = None
try:
grants = [r[0] for r in c.execute(sa_text("SHOW GRANTS")).fetchall()]
joined = " ".join(grants).upper()
writable = any(k in joined for k in
("ALL PRIVILEGES", "INSERT", "UPDATE", "DELETE", "DROP", "ALTER"))
except SQLAlchemyError:
pass
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return {"version": str(version), "database": str(current_db),
"table_count": int(tables), "account_writable": writable}
# ---------- 内省 ----------
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables: dict[str, TableInfo] = {}
for name, ttype, comment, rows in c.execute(sa_text(
"SELECT TABLE_NAME, TABLE_TYPE, TABLE_COMMENT, TABLE_ROWS "
"FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() "
"ORDER BY TABLE_NAME"
)).fetchall():
tables[name] = TableInfo(
name=name,
kind="view" if str(ttype).upper().endswith("VIEW") else "table",
comment=(comment or ""), row_count_est=int(rows or 0))
for (tname, cname, dtype, nullable, comment, default, key) in c.execute(sa_text(
"SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, "
" COLUMN_COMMENT, COLUMN_DEFAULT, COLUMN_KEY "
"FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() "
"ORDER BY TABLE_NAME, ORDINAL_POSITION"
)).fetchall():
t = tables.get(tname)
if t is None:
continue
t.columns.append(ColumnInfo(
name=cname, data_type=str(dtype or ""),
nullable=(str(nullable).upper() == "YES"),
comment=(comment or ""), default=("" if default is None else str(default))))
if str(key or "").upper() == "PRI":
t.primary_key.append(cname)
fks: list[ForeignKeyInfo] = []
for (cname, tname, col, ref_schema, ref_t, ref_c) in c.execute(sa_text(
"SELECT CONSTRAINT_NAME, TABLE_NAME, COLUMN_NAME, "
" REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME "
"FROM information_schema.KEY_COLUMN_USAGE "
"WHERE TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME IS NOT NULL"
)).fetchall():
if ref_schema in _SYSTEM_SCHEMAS:
continue
fks.append(ForeignKeyInfo(from_table=tname, from_column=col,
to_table=ref_t, to_column=ref_c, name=cname or ""))
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return Introspection(tables=list(tables.values()), foreign_keys=fks)
# ---------- 值采样 ----------
def sample_values(self, table: str, column: str, limit: int,
max_distinct: int) -> tuple[list[str], int]:
"""枚举列的真实取值。这一步看着不起眼,但它决定了模型会不会写对 WHERE 条件。"""
if limit <= 0 or _is_pii(column):
return [], 0
q_tab, q_col = _quote(table), _quote(column)
try:
with self.engine.connect() as c:
c.execute(sa_text("SET SESSION MAX_EXECUTION_TIME=5000"))
# 先数 distinct:超过阈值说明不是枚举列,没必要也不该把取值塞进提示词。
# 套一层子查询限制扫描量,避免在大表上把 COUNT(DISTINCT) 跑爆。
total = c.execute(sa_text(
f"SELECT COUNT(*) FROM (SELECT DISTINCT {q_col} FROM {q_tab} "
f"WHERE {q_col} IS NOT NULL LIMIT :cap) t"
), {"cap": max_distinct + 1}).scalar_one()
total = int(total or 0)
if total == 0 or total > max_distinct:
return [], total
rows = c.execute(sa_text(
f"SELECT {q_col}, COUNT(*) AS c FROM {q_tab} WHERE {q_col} IS NOT NULL "
f"GROUP BY {q_col} ORDER BY c DESC LIMIT :lim"
), {"lim": limit}).fetchall()
except SQLAlchemyError as e:
# 采样失败不该拖垮整个内省,降级成「这列没样例值」就行
log.debug("采样 %s.%s 失败:%s", table, column, _clean(e)[:120])
return [], 0
return [_short(r[0]) for r in rows], total
# ---------- 空值画像 ----------
def null_ratios(self, table: str, columns: list[str], sample: int = 50000) -> dict[str, float]:
"""一张表一次扫描算完所有列,别一列一条 SQL —— 41 列就是 41 次全表扫。
外面套一层 LIMIT 子查询把扫描量框住:百万行的表上精确统计不值得,
我们只是要认出「整列全空」,抽样足够。
"""
if not columns:
return {}
parts = ", ".join(
f"SUM(CASE WHEN {_quote(c)} IS NULL THEN 1 ELSE 0 END) AS n{i}"
for i, c in enumerate(columns))
sql = (f"SELECT COUNT(*) AS total, {parts} FROM "
f"(SELECT * FROM {_quote(table)} LIMIT {int(sample)}) t")
try:
with self.engine.connect() as c:
c.execute(sa_text("SET SESSION MAX_EXECUTION_TIME=30000"))
row = c.execute(sa_text(sql)).fetchone()
except SQLAlchemyError as e:
log.debug("空值画像失败 %s:%s", table, _clean(e)[:150])
return {}
if row is None:
return {}
total = int(row[0] or 0)
if total == 0:
return {}
return {col: float(row[i + 1] or 0) / total for i, col in enumerate(columns)}
# ---------- 执行 ----------
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
started = time.time()
try:
with self.engine.connect() as c:
try:
c.execute(sa_text(f"SET SESSION MAX_EXECUTION_TIME={int(timeout_ms)}"))
except SQLAlchemyError:
pass # 老版本没这个变量,下面还有 fetchmany 兜底
cur = c.execute(sa_text(sql))
cols = list(cur.keys())
rows = cur.fetchmany(row_limit + 1) # 多取一条用来判断是否被截断
truncated = len(rows) > row_limit
if truncated:
rows = rows[:row_limit]
cur.close()
except SQLAlchemyError as e:
raise QueryFailed(_clean(e)) from e
return QueryResult(
columns=cols,
rows=[[_jsonable(v) for v in r] for r in rows],
row_count=len(rows),
duration_ms=int((time.time() - started) * 1000),
truncated=truncated)
# ---------- 小工具 ----------
def _quote(ident: str) -> str:
"""反引号包标识符。内省来的表/列名理论上可信,但仍然挡一下反引号注入。"""
return "`" + str(ident).replace("`", "``") + "`"
def _is_pii(column: str) -> bool:
low = str(column).lower()
return any(h in low for h in _PII_HINTS)
def _short(v: Any, limit: int = 60) -> str:
s = "" if v is None else str(v)
return s if len(s) <= limit else s[:limit] + "…"
def _jsonable(v: Any) -> Any:
"""把 Decimal / date / bytes 之类转成能 json.dumps 的东西。"""
import datetime as _dt
import decimal
if v is None or isinstance(v, (str, int, float, bool)):
return v
if isinstance(v, decimal.Decimal):
return float(v)
if isinstance(v, (_dt.datetime, _dt.date, _dt.time)):
return v.isoformat()
if isinstance(v, _dt.timedelta):
return str(v)
if isinstance(v, (bytes, bytearray)):
return v.decode("utf-8", errors="replace")
return str(v)
def _clean(e: Exception) -> str:
"""SQLAlchemy 的异常串里带完整连接串和 SQL,直接抛给前端会泄口令。只留数据库自己的报错。"""
msg = str(getattr(e, "orig", e))
for cut in ("\n[SQL:", "\n(Background on this error"):
i = msg.find(cut)
if i != -1:
msg = msg[:i]
return msg.strip()[:800]