introspect.py
16.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
"""内省:把物理 schema 抓回来,落成语义模型草稿。
写成生成器 yield 进度事件,交给 `jobs/queue.py` 跑 —— 一个几百张表的库
连采样能跑好几分钟,不能挂在 HTTP 请求的生命周期上。
两个关键设计:
1. **重复内省不能冲掉人工编辑。** 按物理表名/列名匹配已有记录,
只更新类型、注释这些「物理事实」,description / synonyms / enabled 这些
人改过的字段一律保留。不这么做的话,用户辛苦填的描述会在下次点「重新内省」时消失。
2. **值采样默认只对新列做。** 采样要对业务库发查询,几百列就是几百条 SQL。
已经采过的列除非明确要求,否则跳过。
"""
from __future__ import annotations
import fnmatch
import json
import re
import logging
import datetime as dt
from typing import Iterator
from sqlalchemy import delete, or_, select
from sqlalchemy.orm import Session
from ..core import db as core_db
from ..core.db import get_engine
from . import semantic
from .connectors.base import ConnectionFailed
from .models import SmColumn, SmModel, SmRelation
log = logging.getLogger(__name__)
# 一次内省最多处理多少张表。超过就截断并警告 —— 几千张表的库不该整库建模,
# 应该先在建模页里挑出真正要查的那些。
MAX_TABLES = 600
# 表数不超过它时,内省会自动推导并启用表间关系(每条候选要对业务库发两条抽样 SQL)
AUTO_RELATION_MAX_TABLES = 40
def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
"""生成器:yield 给 jobs/queue 的进度事件。"""
cfg = core_db.get_all_config()
sample_n = int(cfg.get("SQL_SAMPLE_VALUES") or "8")
max_distinct = int(cfg.get("SQL_SAMPLE_MAX_DISTINCT") or "50")
yield {"stage": "connect", "progress": 2, "message": "正在连接数据源…"}
try:
conn = semantic.connector_for(ds_id)
info = conn.test()
except ConnectionFailed as e:
semantic.mark_datasource(ds_id, "error", str(e))
yield {"stage": "error", "error": f"连接失败:{e}"}
return
except Exception as e: # noqa: BLE001
semantic.mark_datasource(ds_id, "error", str(e))
yield {"stage": "error", "error": str(e)[:500]}
return
if info.get("account_writable"):
# 不拦,但要说清楚。生成的 SQL 有 guard 兜底,可真正的隔离应该在账号层。
yield {"stage": "warn", "progress": 4,
"message": "注意:这个账号有写权限。建议改用只读账号连接业务库。"}
yield {"stage": "tables", "progress": 6, "message": "正在读取表结构…"}
try:
intro = conn.introspect()
except Exception as e: # noqa: BLE001
semantic.mark_datasource(ds_id, "error", str(e))
yield {"stage": "error", "error": f"读取表结构失败:{str(e)[:400]}"}
return
# 表范围:业务库往往有几百张表,只内省用户在数据源里勾选的那些。
# 接入范围就是「参与问数」的范围:读进来的表一律启用,不再逐张勾选。
scope = table_scope(semantic.get_datasource(ds_id) or {})
# 数据源指向元数据库所在的库时,系统自己的表(用户、会话、审计…)不当业务表内省
deny = semantic.system_tables()
tables = [t for t in intro.tables if in_scope(t.name, scope) and t.name.lower() not in deny]
if scope:
intro.foreign_keys = [fk for fk in intro.foreign_keys
if in_scope(fk.from_table, scope) and in_scope(fk.to_table, scope)]
yield {"stage": "tables", "progress": 7,
"message": f"表范围 {'、'.join(scope)}:命中 {len(tables)}/{len(intro.tables)} 张表"}
truncated = False
if len(tables) > MAX_TABLES:
tables = tables[:MAX_TABLES]
truncated = True
# ---------- 落库:模型与列 ----------
stats = {"new_models": 0, "kept_models": 0, "new_columns": 0, "dropped_columns": 0}
model_id_by_table: dict[str, int] = {}
total = max(len(tables), 1)
for i, t in enumerate(tables, 1):
with Session(get_engine()) as s:
m = s.scalars(select(SmModel).where(
SmModel.ds_id == ds_id, SmModel.physical_table == t.name)).first()
if m is None:
m = SmModel(
ds_id=ds_id, name=t.name, physical_table=t.name,
kind=t.kind, description=t.comment or "", db_comment=t.comment or "",
primary_key=",".join(t.primary_key),
row_count_est=t.row_count_est, enabled=1)
s.add(m)
stats["new_models"] += 1
else:
# 只覆盖物理事实,描述这类人工内容保持不动
m.kind = t.kind
m.enabled = 1
m.row_count_est = t.row_count_est
m.primary_key = ",".join(t.primary_key)
m.db_comment = t.comment or ""
if t.comment and not (m.description or "").strip():
m.description = t.comment
stats["kept_models"] += 1
s.commit()
model_id = m.id
model_id_by_table[t.name] = model_id
existing = {c.physical_column: c for c in s.scalars(
select(SmColumn).where(SmColumn.model_id == model_id)).all()}
live = {c.name for c in t.columns}
for order, c in enumerate(t.columns):
row = existing.get(c.name)
if row is None:
s.add(SmColumn(
model_id=model_id, name=c.name, physical_column=c.name,
data_type=c.data_type, description=c.comment or "", db_comment=c.comment or "",
nullable=1 if c.nullable else 0, sort_order=order,
is_measure=1 if _looks_numeric(c.data_type) else 0,
is_dimension=0 if _looks_numeric(c.data_type) else 1))
stats["new_columns"] += 1
else:
row.data_type = c.data_type
row.db_comment = c.comment or ""
row.nullable = 1 if c.nullable else 0
row.sort_order = order
if c.comment and not (row.description or "").strip():
row.description = c.comment
# 物理上已经删掉的列要跟着下线,否则会一直出现在提示词里诱导模型写错
for name, row in existing.items():
if name not in live:
s.delete(row)
stats["dropped_columns"] += 1
s.commit()
if i % 5 == 0 or i == len(tables):
yield {"stage": "tables", "progress": 6 + int(i / total * 44),
"i": i, "total": len(tables),
"message": f"表结构 {i}/{len(tables)}:{t.name}"}
# ---------- 移出范围 / 库里已删掉的表 ----------
# 数据源里取消勾选、或者业务库里删掉的表,连同它的列和关联一起下线,否则还会被拿去生成 SQL
if not truncated:
stats["dropped_models"] = _drop_models_except(ds_id, {t.name for t in tables})
# ---------- 值采样 ----------
# 这一步是整个内省里最值钱的:模型得看见 brand_name 里存的是中文品牌名,
# 才知道「某品牌的网点」该翻译成什么过滤条件。
if sample_n > 0:
todo = _columns_to_sample(ds_id, resample)
stotal = max(len(todo), 1)
sampled = 0
for i, (table, col_id, col_name) in enumerate(todo, 1):
values, distinct = conn.sample_values(table, col_name, sample_n, max_distinct)
with Session(get_engine()) as s:
row = s.get(SmColumn, col_id)
if row is not None:
row.sample_values_json = json.dumps(values, ensure_ascii=False)
row.distinct_count = distinct
s.commit()
if values:
sampled += 1
if i % 10 == 0 or i == len(todo):
yield {"stage": "sample", "progress": 50 + int(i / stotal * 35),
"i": i, "total": len(todo),
"message": f"列值采样 {i}/{len(todo)},已采到 {sampled} 个枚举列"}
stats["sampled_columns"] = sampled
else:
stats["sampled_columns"] = 0
# ---------- 空值画像 ----------
# 整列全空的列必须停用。实测这个库里 dws_order_detail_wide.car_brand 就是全 NULL,
# 留着它模型问「某品牌的订单」会去 filter 这列,查出 0 行还以为是没数据 ——
# 这类「看起来能用、实际永远查不出东西」的列是准确率的隐形杀手。
yield {"stage": "profile", "progress": 86, "message": "正在统计列的空值比例…"}
disabled_empty = _profile_nulls(ds_id, tables, conn)
stats["disabled_empty_columns"] = disabled_empty
# ---------- 外键 → 关系 ----------
yield {"stage": "relations", "progress": 90, "message": "正在推导表间关系…"}
stats["new_relations"] = _sync_relations(ds_id, intro.foreign_keys, model_id_by_table)
# 业务库大多不建外键:表不多时顺手按「列名像键 + 目标唯一 + 取值重叠」推关系并启用,
# 否则建模时对象之间连不起来,影响分析、多跳查询都用不了。
if not intro.foreign_keys and len(tables) <= AUTO_RELATION_MAX_TABLES:
stats["new_relations"] += _sync_recommended(ds_id)
semantic.update_datasource(ds_id, status="ok", last_error="",
last_introspect_at=dt.datetime.now())
msg = (f"内省完成:{stats['new_models']} 张新表 / {stats['kept_models']} 张已有表,"
f"新增 {stats['new_columns']} 列,采到 {stats['sampled_columns']} 个枚举列,"
f"推导出 {stats['new_relations']} 条关系。")
if stats.get("disabled_empty_columns"):
msg += f" 另有 {stats['disabled_empty_columns']} 个整列全空的列已自动停用。"
if stats.get("dropped_models"):
msg += f" 移除了 {stats['dropped_models']} 张不在接入范围内的表。"
if truncated:
msg += f" 注意:表数超过 {MAX_TABLES},只处理了前 {MAX_TABLES} 张。"
yield {"stage": "done", "progress": 100, "message": msg, "stats": stats}
def _drop_models_except(ds_id: int, keep: set[str]) -> int:
with Session(get_engine()) as s:
gone = [m.id for m in s.scalars(select(SmModel).where(SmModel.ds_id == ds_id)).all()
if m.physical_table not in keep]
if gone:
s.execute(delete(SmRelation).where(SmRelation.ds_id == ds_id, or_(
SmRelation.from_model_id.in_(gone), SmRelation.to_model_id.in_(gone))))
s.execute(delete(SmColumn).where(SmColumn.model_id.in_(gone)))
s.execute(delete(SmModel).where(SmModel.id.in_(gone)))
s.commit()
return len(gone)
def table_scope(ds: dict) -> list[str]:
"""数据源的表范围:extra.tables,逗号或换行分隔的通配符(如 otlg_dm_*)。空 = 全部表。"""
raw = str((ds.get("extra") or {}).get("tables") or "")
return [p.strip() for p in re.split(r"[,,\s]+", raw) if p.strip()]
def in_scope(table: str, scope: list[str]) -> bool:
return not scope or any(fnmatch.fnmatch(table.lower(), p.lower()) for p in scope)
# ---------------- 内部 ----------------
def _looks_numeric(data_type: str) -> bool:
low = (data_type or "").lower()
return any(k in low for k in ("int", "decimal", "numeric", "float", "double", "bit"))
def _samplable(data_type: str) -> bool:
"""只对可能是枚举的类型采样。数值和时间列的取值分布没有提示价值,反而占 token。"""
low = (data_type or "").lower()
if any(k in low for k in ("char", "text", "enum", "set")):
return True
# 小整数常用来做状态码,值得采
return low.startswith(("tinyint", "smallint")) or low.startswith("int(1)")
def _columns_to_sample(ds_id: int, resample: bool) -> list[tuple[str, int, str]]:
out: list[tuple[str, int, str]] = []
with Session(get_engine()) as s:
models = s.scalars(select(SmModel).where(SmModel.ds_id == ds_id)).all()
by_id = {m.id: m for m in models}
if not by_id:
return out
cols = s.scalars(select(SmColumn).where(SmColumn.model_id.in_(list(by_id)))).all()
for c in cols:
if not _samplable(c.data_type):
continue
# 已经采过的(不管采到没采到)默认跳过,避免每次内省都对业务库打几百条查询
if not resample and c.distinct_count:
continue
m = by_id.get(c.model_id)
if m is None or m.kind == "saved_view":
continue
out.append((m.physical_table or m.name, c.id, c.physical_column or c.name))
return out
def _profile_nulls(ds_id: int, tables, conn) -> int:
"""统计空值比例并把整列全空的列停用。返回停用的列数。
视图不做;空表 null_ratios 会返回空结果(不会把每列都判成「全空」)。
不能按 row_count_est 过滤:InnoDB 对刚灌进去的小表估算常常是 0,会让整张表的空值都没统计。
"""
live = {t.name for t in tables if t.kind != "view"}
if not live:
return 0
disabled = 0
with Session(get_engine()) as s:
models = s.scalars(select(SmModel).where(SmModel.ds_id == ds_id)).all()
for m in models:
table = m.physical_table or m.name
if table not in live:
continue
cols = s.scalars(select(SmColumn).where(SmColumn.model_id == m.id)).all()
if not cols:
continue
names = [c.physical_column or c.name for c in cols]
ratios = conn.null_ratios(table, names, 50000)
if not ratios:
continue
for c in cols:
r = ratios.get(c.physical_column or c.name)
if r is None:
continue
c.null_ratio = round(float(r), 4)
# 只在「全空」时停用。半空的列仍然有用,交给提示词里的空值比例提醒模型。
if r >= 0.9999 and c.enabled:
c.enabled = 0
disabled += 1
s.commit()
return disabled
def _sync_relations(ds_id: int, fks, model_id_by_table: dict[str, int]) -> int:
"""外键 → 关系。已存在的同路径关系不重复建,也不覆盖用户改过的描述。"""
if not fks:
return 0
existing = {(r["from_model_id"], r["from_column"], r["to_model_id"], r["to_column"])
for r in semantic.list_relations(ds_id, enabled_only=False)}
added = 0
with Session(get_engine()) as s:
for fk in fks:
fm = model_id_by_table.get(fk.from_table)
tm = model_id_by_table.get(fk.to_table)
if not fm or not tm:
continue
key = (fm, fk.from_column, tm, fk.to_column)
if key in existing:
continue
s.add(SmRelation(
ds_id=ds_id, name=fk.name or f"{fk.from_table}_{fk.to_table}",
from_model_id=fm, from_column=fk.from_column,
to_model_id=tm, to_column=fk.to_column,
join_type="inner", cardinality="N:1",
condition_sql=f"{fk.from_table}.{fk.from_column} = {fk.to_table}.{fk.to_column}",
description="由外键约束推导", enabled=1))
existing.add(key)
added += 1
s.commit()
return added
def _sync_recommended(ds_id: int) -> int:
"""没有外键时,把推荐出来的关联路径(已过唯一度与重叠率两道校验)直接建成关系。"""
added = 0
try:
recs = semantic.recommend_relations(ds_id)
except Exception as e: # noqa: BLE001
log.warning("推导表间关系失败:%s", str(e)[:200])
return 0
for r in recs:
semantic.upsert_relation(
ds_id, name=f"{r['from_table']}_{r['to_table']}", from_model_id=r["from_model_id"],
from_column=r["from_column"], to_model_id=r["to_model_id"], to_column=r["to_column"],
join_type="inner", cardinality="N:1",
condition_sql=f"{r['from_table']}.{r['from_column']} = {r['to_table']}.{r['to_column']}",
description=f"按列名与取值推导(重叠率 {r['overlap']:.0%})", enabled=1)
added += 1
return added