introspect.py 12.8 KB
"""内省:把物理 schema 抓回来,落成语义模型草稿。

写成生成器 yield 进度事件,交给 `jobs/queue.py` 跑 —— 一个几百张表的库
连采样能跑好几分钟,不能挂在 HTTP 请求的生命周期上。

两个关键设计:
1. **重复内省不能冲掉人工编辑。** 按物理表名/列名匹配已有记录,
   只更新类型、注释这些「物理事实」,description / synonyms / enabled 这些
   人改过的字段一律保留。不这么做的话,用户辛苦填的描述会在下次点「重新内省」时消失。
2. **值采样默认只对新列做。** 采样要对业务库发查询,几百列就是几百条 SQL。
   已经采过的列除非明确要求,否则跳过。
"""
from __future__ import annotations
import json
import logging
import datetime as dt
from typing import Iterator

from sqlalchemy import select
from sqlalchemy.orm import Session

from ..core import db as core_db
from ..core.db import engine
from . import semantic
from .connectors.base import ConnectionFailed
from .models import SmColumn, SmModel, SmRelation

log = logging.getLogger(__name__)

# 一次内省最多处理多少张表。超过就截断并警告 —— 几千张表的库不该整库建模,
# 应该先在建模页里挑出真正要查的那些。
MAX_TABLES = 600


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

    tables = 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(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 "",
                    primary_key=",".join(t.primary_key),
                    row_count_est=t.row_count_est,
                    # 新表默认不启用:几百张表全打开会把提示词撑爆,
                    # 也让「启用 = 授权可查」这个语义站不住。让用户显式挑。
                    enabled=0)
                s.add(m)
                stats["new_models"] += 1
            else:
                # 只覆盖物理事实,描述这类人工内容保持不动
                m.kind = t.kind
                m.row_count_est = t.row_count_est
                m.primary_key = ",".join(t.primary_key)
                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 "",
                        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.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}"}

    # ---------- 值采样 ----------
    # 这一步是整个内省里最值钱的:模型得看见 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(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)

    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["new_models"]:
        msg += " 新表默认是停用的,请在建模页里挑出要查的表并启用。"
    if truncated:
        msg += f" 注意:表数超过 {MAX_TABLES},只处理了前 {MAX_TABLES} 张。"
    yield {"stage": "done", "progress": 100, "message": msg, "stats": stats}


# ---------------- 内部 ----------------
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(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:
    """统计空值比例并把整列全空的列停用。返回停用的列数。

    只对有数据的表做(空表的每一列当然都是「全空」,那是假阳性)。
    """
    live = {t.name for t in tables if (t.row_count_est or 0) > 0 and t.kind != "view"}
    if not live:
        return 0
    disabled = 0
    with Session(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(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