sources.py 6.36 KB
"""后备数据源:把对象绑定里写的「数据从哪来」编译成可以放在 FROM 后面的 SQL。

对象读取(objects._plan)、数据管道、指标都只认 `effective(ref)` 给出的这份「有效绑定」:
    {from: FROM 片段, key_column, label_column, columns: {属性: 有效列名}, table: 写入的表, kind, writable}
这样下游不用关心对象到底是一张表、几张表拼起来的、一张表里的一部分,还是本系统自己存的。

- table     单表:FROM 表本身;
- view      多表组合:主表 t LEFT JOIN 若干张表,别的表的列在有效绑定里叫「别名__列」;只能写主表的列;
- filtered  表的一部分:(SELECT * FROM 表 WHERE 条件),条件用规则语法写在列上;写回原表;
- union     多源合并:几张同构的表 UNION ALL,主键带各自的前缀(全局唯一),只读;
- sql       SQL 视图:一条受控的 SELECT,只读;
- managed   本体自建:系统在「本体存储」里建的表 otlg_mo_<对象id>,可写;
- system    系统对象:预警事件 / 动作记录 / 流程运行,按本体空间过滤,只读。
"""
from __future__ import annotations

from fastapi import HTTPException

from . import rules
from .sqlutil import ident, lit


def _cond(where: str, col) -> str:
    try:
        return rules.to_sql(where, col, lambda o, a: f"{ident(o)}.{ident(a)}")
    except rules.RuleError as e:
        raise HTTPException(422, f"数据来源的筛选条件算不出来:{e}") from e


def effective(ref: dict, workspace: str = "") -> dict:
    """绑定 → 有效绑定。ref 是 schema.normalize_binding('table') 规整过的样子。"""
    kind = ref.get("kind") or "table"
    cols = dict(ref.get("columns") or {})
    out = {"kind": kind, "key_column": ref.get("key_column") or "", "label_column": ref.get("label_column") or "",
           "table": ref.get("table") or "", "columns": cols, "writable": kind in ("table", "filtered", "managed", "view"),
           "raw": ref}
    if kind in ("table", "managed"):
        out["from"] = ident(ref["table"])
    elif kind == "filtered":
        out["from"] = f"(SELECT * FROM {ident(ref['table'])} WHERE {_cond(ref['where'], ident)})"
    elif kind == "sql":
        out["from"] = f"({ref['sql']})"
        out["table"] = ""
    elif kind == "view":
        # 主表在子查询里叫 v(外层读取方案还会把整个子查询叫 t,两个 t 会让校验器认错表)
        sel = ["v.*"]
        joins = []
        eff: dict[str, str] = {}
        for j in ref.get("joins") or []:
            left = j["from_column"]
            left_sql = f"{ident(left.split('.')[0])}.{ident(left.split('.')[1])}" if "." in left else f"v.{ident(left)}"
            joins.append(f"LEFT JOIN {ident(j['table'])} AS {ident(j['alias'])} ON {left_sql} = "
                         f"{ident(j['alias'])}.{ident(j['to_column'])}")
        for prop, col in cols.items():
            if "." in col:
                alias, c = col.split(".", 1)
                name = f"{alias}__{c}"
                sel.append(f"{ident(alias)}.{ident(c)} AS {ident(name)}")
                eff[prop] = name
            else:
                eff[prop] = col
        lab = out["label_column"]
        if "." in lab:
            alias, c = lab.split(".", 1)
            out["label_column"] = f"{alias}__{c}"
            if f"{ident(alias)}.{ident(c)} AS {ident(out['label_column'])}" not in sel:
                sel.append(f"{ident(alias)}.{ident(c)} AS {ident(out['label_column'])}")
        out["columns"] = eff
        out["main_columns"] = {p: c for p, c in cols.items() if "." not in c}
        out["from"] = f"(SELECT {', '.join(sel)} FROM {ident(ref['table'])} AS v {' '.join(joins)})"
    elif kind == "union":
        parts = []
        props = list(cols)
        for b in ref.get("branches") or []:
            sel = [f"CONCAT({lit(b['prefix'])}, {ident(b['key_column'])}) AS {ident('__key')}"]
            if out["label_column"]:
                sel.append(f"{ident(b['label_column'] or b['key_column'])} AS {ident('__label')}")
            for p in props:
                c = (b.get("columns") or {}).get(p)
                sel.append(f"{ident(c) if c else 'NULL'} AS {ident(p)}")
            sql = f"SELECT {', '.join(sel)} FROM {ident(b['table'])}"
            if b.get("where"):
                sql += f" WHERE {_cond(b['where'], ident)}"
            parts.append(sql)
        out["from"] = "(" + " UNION ALL ".join(parts) + ")"
        out["table"] = ""
        out["writable"] = False
    elif kind == "system":
        from . import sysobjects
        out["from"] = sysobjects.from_sql(ref["system"], workspace)
        out["writable"] = False
    else:
        raise HTTPException(422, f"不认识的数据来源「{kind}」")
    if kind in ("sql", "union"):
        out["writable"] = False
    return out


def write_column(eff: dict, prop: str) -> str | None:
    """这个属性写回业务库时落在哪一列;不能写(只读来源、组合里别的表的列)返回 None。"""
    if not eff.get("writable"):
        return None
    if eff["kind"] == "view":
        return (eff.get("main_columns") or {}).get(prop)
    return (eff.get("columns") or {}).get(prop)


def describe(ref: dict) -> str:
    """给人看的一句话:这个对象的数据从哪来。"""
    kind = ref.get("kind") or "table"
    if kind == "table":
        return f"表 {ref.get('table')}"
    if kind == "view":
        return f"表 {ref.get('table')} 关联 " + "、".join(j["table"] for j in ref.get("joins") or [])
    if kind == "filtered":
        return f"表 {ref.get('table')} 中满足 {ref.get('where')} 的行"
    if kind == "union":
        return "合并 " + "、".join(f"{b['table']}({b['prefix']})" for b in ref.get("branches") or [])
    if kind == "sql":
        return "SQL 视图"
    if kind == "managed":
        return "本体自建(本系统保存)"
    if kind == "system":
        return "系统对象"
    return kind


def physical_tables(ref: dict) -> list[str]:
    """这个数据来源读到的业务表(体检、问数的表范围用)。"""
    kind = ref.get("kind") or "table"
    if kind == "union":
        return [b["table"] for b in ref.get("branches") or []]
    if kind == "view":
        return [ref["table"], *[j["table"] for j in ref.get("joins") or []]]
    if kind in ("table", "filtered", "managed"):
        return [ref["table"]] if ref.get("table") else []
    return []