autobind.py 10.3 KB
"""把元素落到数据上的两件省事活:从一张数据表直接建成对象;一键补全还没绑的关系和属性。

都是确定性的(按表结构和列名对),不调模型:结果可以预期,也能当场解释「为什么选这一列」。
补全先给建议(suggest),人看过再落(apply);落下去的都是草稿,要发布才生效。
"""
from __future__ import annotations

import re
from typing import Any

from fastapi import HTTPException
from sqlalchemy import select

from ..core import identity
from ..core.dbx import jload, session
from ..text2sql import semantic
from . import service
from .models import Binding, Concept

MAX_PROPS = 60
_NUM = re.compile(r"int|dec|double|float|real|numeric|number", re.I)
_DATE = re.compile(r"date|time", re.I)
_LABEL = re.compile(r"(^|_)(name|title|label)$|名称$|名字$|标题$", re.I)


def _norm(s: Any) -> str:
    return re.sub(r"[\s_\-]+", "", str(s or "")).lower()


def _tables(ds_id: int) -> dict[str, dict]:
    """数据源的表目录:物理表名(小写)→ {table, description, primary_key, columns:[...]}。"""
    out = {}
    for m in semantic.models_with_columns(ds_id, enabled_only=False):
        t = m.get("physical_table") or m["name"]
        out[t.lower()] = {"table": t, "name": m["name"], "description": m.get("description") or "",
                          "primary_key": m.get("primary_key") or "",
                          "columns": [{"name": c["name"], "column": c.get("physical_column") or c["name"],
                                       "data_type": c.get("data_type") or "", "description": c.get("description") or "",
                                       "is_measure": bool(c.get("is_measure")), "is_dimension": bool(c.get("is_dimension"))}
                                      for c in m.get("columns") or []]}
    return out


def _data_type(c: dict) -> str:
    if c["is_measure"] or _NUM.search(c["data_type"]):
        return "number"
    return "date" if _DATE.search(c["data_type"]) else "string"


# ---------------------------------------------------------------- 表 → 对象
def object_from_table(ds_id: int, table: str, name: str = "") -> dict:
    """从一张表建一个对象类型草稿:列成属性,并绑定到这张表。数据连接页和对象列表页都走这里。"""
    t = _tables(ds_id).get(str(table or "").lower())
    if t is None:
        raise HTTPException(404, f"数据源里没有表「{table}」,先到数据连接页同步一下表结构")
    for hit in mapped_tables(ds_id).get(t["table"], []):
        raise HTTPException(409, f"这张表已经建成对象「{hit['name']}」了,直接去改它就行")
    cols = t["columns"][:MAX_PROPS]
    if not cols:
        raise HTTPException(422, f"表「{t['table']}」没有可用的列")
    by_name = {c["name"]: c for c in cols}
    key = t["primary_key"] if t["primary_key"] in by_name else next(
        (c["name"] for c in cols if c["name"].lower() == "id"), cols[0]["name"])
    label = next((c["name"] for c in cols if _LABEL.search(c["name"]) or c["description"].endswith("名称")), "")
    name = (name or re.split(r"[,。,((]", t["description"])[0].strip()[:30] or t["name"]).strip()
    if service.find(name, "object_type"):
        name = f"{name}({t['table']})"
    props = [{"name": c["name"], "display_name": c["description"][:40], "description": c["description"],
              "data_type": _data_type(c), "is_key": c["name"] == key, "is_dimension": c["is_dimension"]} for c in cols]
    c = service.create_concept("object_type", name, description=t["description"],
                               synonyms=[t["name"]] if t["name"] != name else [],
                               spec={"properties": props, "label_property": label})
    service.set_binding(c["id"], ds_id, "table", {
        "table": t["table"], "key_column": by_name[key]["column"],
        "label_column": by_name[label]["column"] if label else "",
        "columns": {x["name"]: x["column"] for x in cols}})
    return service.get_concept(c["id"])


def mapped_tables(ds_id: int) -> dict[str, list[dict]]:
    """某个数据源的每张表建成了哪个对象。"""
    out: dict[str, list[dict]] = {}
    with session() as s:
        rows = s.execute(select(Binding, Concept).join(Concept, Concept.id == Binding.concept_id).where(
            Binding.workspace == identity.current().workspace, Binding.ds_id == ds_id,
            Binding.target_kind == "table", Concept.status != "deprecated")).all()
        for b, c in rows:
            t = (jload(b.ref_json, {}) or {}).get("table") or ""
            out.setdefault(t, []).append({"concept_id": c.id, "name": c.name, "status": c.status})
    return out


# ---------------------------------------------------------------- 一键补全
def _objects() -> dict[str, dict]:
    """有表绑定的对象类型:id → {concept, ds_id, ref}。名字也能查到。"""
    out: dict[str, dict] = {}
    for c in service.list_full("object_type"):
        b = next((x for x in c.get("bindings") or [] if x["target_kind"] == "table"), None)
        rec = {"concept": c, "ds_id": b["ds_id"] if b else 0, "ref": (b or {}).get("ref") or {}}
        out[c["id"]] = rec
        out.setdefault("name:" + c["name"], rec)
    return out


def _obj(objs: dict[str, dict], ref: str) -> dict | None:
    return objs.get(ref) or objs.get("name:" + str(ref))


def _fk_column(src_cols: list[str], target: dict) -> tuple[str, str]:
    """在 src 表的列里找指向 target 对象的那一列:返回 (列名, 理由)。找不到返回 ("", "")。"""
    tref = target["ref"]
    key, table = tref.get("key_column") or "", tref.get("table") or ""
    if not key:
        return "", ""
    names = {_norm(c): c for c in src_cols}
    base = re.sub(r"^(dim|dwd|dws|ods|fact|t)_", "", table.lower())
    base = re.sub(r"^.*_dm_", "", base)
    cands = [(_norm(key), f"和「{target['concept']['name']}」的主键同名")]
    for stem in dict.fromkeys([base, base.rstrip("s"), _norm(target["concept"]["name"])]):
        if stem:
            cands += [(_norm(stem + "id"), f"列名是「{target['concept']['name']}」+ id"),
                      (_norm(stem + "code"), f"列名是「{target['concept']['name']}」+ code"),
                      (_norm(stem + key), "列名是表名 + 主键名")]
    for cand, why in cands:
        if cand in names and cand not in ("id",):
            return names[cand], why
    return "", ""


def suggest() -> dict:
    """看一遍工作副本,给出能自动补的绑定。每条带理由;拿不准的不给(留在 skipped 里说明为什么)。"""
    objs = _objects()
    catalog: dict[int, dict[str, dict]] = {}

    def cols_of(ds_id: int, table: str) -> list[str]:
        if ds_id not in catalog:
            catalog[ds_id] = _tables(ds_id)
        return [c["column"] for c in (catalog[ds_id].get(str(table).lower()) or {}).get("columns", [])]

    items: list[dict] = []
    skipped: list[dict] = []
    # 关系:两端对象都绑了表、在同一个数据源里,才对得上
    for c in service.list_full("link_type"):
        if any(x["target_kind"] == "join" for x in c["bindings"]):
            continue
        spec = c.get("spec") or {}
        a, b = _obj(objs, spec.get("from_type")), _obj(objs, spec.get("to_type"))

        def skip(why: str) -> None:
            skipped.append({"concept_id": c["id"], "name": c["name"], "kind": "link_type", "why": why})
        if not a or not b:
            skip("起点或终点对象不存在")
            continue
        if not a["ref"].get("table") or not b["ref"].get("table"):
            skip("起点或终点对象还没绑定数据表")
            continue
        if a["ds_id"] != b["ds_id"]:
            skip("两端对象不在同一个数据源里,没法直接关联")
            continue
        col, why = _fk_column(cols_of(a["ds_id"], a["ref"]["table"]), b)
        if col:
            ref = {"from_column": col, "to_column": b["ref"]["key_column"]}
        else:
            # 反过来:外键在终点表上(一对多)
            col, why = _fk_column(cols_of(b["ds_id"], b["ref"]["table"]), a)
            if not col:
                skip(f"在两张表里都没找到互相指向的列({a['ref']['table']} / {b['ref']['table']}),要手工选")
                continue
            ref = {"from_column": a["ref"]["key_column"], "to_column": col}
        items.append({"id": f"{c['id']}:join", "concept_id": c["id"], "name": c["name"], "kind": "link_type",
                      "ds_id": a["ds_id"], "target_kind": "join", "ref": ref,
                      "text": f"{a['ref']['table']}.{ref['from_column']} = {b['ref']['table']}.{ref['to_column']}",
                      "why": why})
    # 对象:属性还没对上列的,按同名列补
    seen: set[str] = set()
    for key, rec in objs.items():
        c = rec["concept"]
        if c["id"] in seen or not rec["ref"].get("table"):
            continue
        seen.add(c["id"])
        mapped = dict(rec["ref"].get("columns") or {})
        by_norm = {_norm(x): x for x in cols_of(rec["ds_id"], rec["ref"]["table"])}
        add = {}
        for p in (c.get("spec") or {}).get("properties") or []:
            if p["name"] in mapped:
                continue
            hit = by_norm.get(_norm(p["name"]))
            if hit:
                add[p["name"]] = hit
        if add:
            items.append({"id": f"{c['id']}:table", "concept_id": c["id"], "name": c["name"], "kind": "object_type",
                          "ds_id": rec["ds_id"], "target_kind": "table",
                          "ref": {**rec["ref"], "columns": {**mapped, **add}},
                          "text": "、".join(f"{k} → {v}" for k, v in list(add.items())[:6])
                                  + (f" 等 {len(add)} 个属性" if len(add) > 6 else ""),
                          "why": "属性和列同名"})
    return {"items": items, "skipped": skipped}


def apply(ids: list[str] | None = None) -> dict:
    """把建议落成草稿绑定。ids 不给就全部落。落之前重新算一遍,不信任前端带回来的内容。"""
    done = []
    for it in suggest()["items"]:
        if ids is not None and it["id"] not in ids:
            continue
        service.set_binding(it["concept_id"], it["ds_id"], it["target_kind"], it["ref"])
        done.append({"concept_id": it["concept_id"], "name": it["name"], "text": it["text"]})
    return {"applied": done, "count": len(done)}