metrics.py 14.9 KB
"""指标取数:把「指标 + 维度 + 过滤 + 时间」**确定性地**编译成 SQL。

已发布的指标不让 LLM 写 SQL —— 口径由绑定定义,每次问都是同一条逻辑,
数字才可信、可复现、可审计。LLM 只负责从问题里挑出指标、维度和时间(编排层做)。
编译出的 SQL 仍走 executor(guard + 行数上限 + 超时),并落 SqlRun 作为数据引用。
"""
from __future__ import annotations

from typing import Any

from fastapi import HTTPException

from ..core import identity
from . import calendar as cal
from . import service
from .sqlutil import ident, jsonable, lit, to_dialect


def metric(ref: str) -> dict:
    m = service.rt_fn(ref, "aggregate")
    if m is None:
        raise HTTPException(404, f"找不到已发布的聚合函数(指标)「{ref}」")
    return m


def resolve_time(m: dict, time: Any, calendar_ref: str = "") -> dict | None:
    """time 可以是 {start,end} / {ref} / 'last' / '2026-08'。按指标关联的日历解析期。

    'none' / '' 表示显式不按时间过滤 —— 像「库存缺口」这种快照指标本来就没有时间列,
    强行塞一个 'current' 会让它取不了数。
    """
    if not time or (isinstance(time, str) and time.strip().lower() in ("none", "不限")):
        return None
    if isinstance(time, dict) and str(time.get("ref") or "").strip().lower() in ("none", "不限"):
        return None
    if isinstance(time, str):
        time = {"ref": time}
    if time.get("start") and time.get("end"):
        return {"start": str(time["start"])[:10], "end": str(time["end"])[:10],
                "period": time.get("period") or "", "calendar": ""}
    cal_concept = None
    cref = calendar_ref or (m.get("spec") or {}).get("calendar") or ""
    if cref:
        cal_concept = service.rt_fn(cref, "calendar")
    spec = (cal_concept or {}).get("spec") or cal.NATURAL_MONTH
    out = cal.resolve(spec, str(time.get("ref") or "current"))
    out["calendar"] = cal_concept["name"] if cal_concept else "自然月"
    return out


def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict | None = None,
                time: Any = None, object_key: str = "", calendar_ref: str = "",
                order: str = "desc", limit: int = 200) -> dict:
    b = service.rt_binding(m, "metric_expr")
    if b is None:
        raise HTTPException(422, f"指标「{m['name']}」还没有绑定取数表达式")
    ref = b["ref"]
    dim_map: dict[str, str] = dict(ref.get("dimensions") or {})
    ds_id = b["ds_id"]
    source = ident(ref["base_table"]) if ref.get("base_table") else ""
    base_ot = None
    if ref.get("base_object"):
        # 指标建在对象上:把对象(含算出来的属性)当成一张表来聚合,对象的每个属性都能当维度
        from . import objects
        base_ot = service.rt_find(ref["base_object"], "object_type")
        if base_ot is None:
            raise HTTPException(422, f"指标「{m['name']}」统计的对象「{ref['base_object']}」还没有发布")
        ds_id, sub = objects.source_sql(base_ot)
        source = f"{sub} AS t"
        tcols = (objects.table_binding(base_ot)["ref"].get("columns") or {})
        for p in (base_ot.get("spec") or {}).get("properties") or []:
            dim_map.setdefault(p["name"], p["name"] if p.get("expression") else tcols.get(p["name"], p["name"]))
    if not source:
        raise HTTPException(422, f"指标「{m['name']}」还没有选统计哪张表或哪个对象")

    # 维度就是对象的属性:属性的显示名也能用来拆分(「按大区」→ 属性「区域」显示名「大区」)
    alias: dict[str, str] = {}
    ot = base_ot or service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
    for p in (ot.get("spec") or {}).get("properties") or []:
        if p.get("display_name"):
            alias[p["display_name"]] = p["name"]

    def dim_col(name: str) -> str:
        if name in dim_map:
            return dim_map[name]
        if alias.get(name) in dim_map:
            return dim_map[alias[name]]
        low = name.lower()
        for k in dim_map:
            if k.lower() == low:
                return dim_map[k]
        raise HTTPException(422, f"指标「{m['name']}」不支持按「{name}」拆分,"
                                 f"可用维度:{'、'.join(dim_map) or '无'}")

    dims = [d for d in (dimensions or []) if d]
    select_parts = [f"{ident(dim_col(d))} AS {ident(d)}" for d in dims]
    select_parts.append(f"{ref['expression']} AS `value`")
    where = list(ref.get("filters") or [])
    for name, val in (filters or {}).items():
        if val in (None, "", []):
            continue
        col = ident(dim_col(name))
        if isinstance(val, (list, tuple)):
            where.append(f"{col} IN ({', '.join(lit(v) for v in val)})")
        else:
            where.append(f"{col} = {lit(val)}")
    if object_key:
        if not ref.get("object_key_column"):
            raise HTTPException(422, f"指标「{m['name']}」没有配置对象键列,不能按单个对象取数")
        where.append(f"{ident(ref['object_key_column'])} = {lit(object_key)}")
    period = resolve_time(m, time, calendar_ref)
    if period:
        if not ref.get("time_column"):
            raise HTTPException(422, f"指标「{m['name']}」没有配置时间列,不能按时间过滤")
        tc = ident(ref["time_column"])
        where.append(f"{tc} >= {lit(period['start'])} AND {tc} < "
                     f"DATE_ADD({lit(period['end'])}, INTERVAL 1 DAY)")
    # 数据范围:对象键列 / 同名维度上的限制(建在对象上的指标,范围已经在对象那一层过滤了)
    ot_id = ot.get("id") if ot and not base_ot else None
    scope = (identity.current().scope or {}).get(ot_id) if ot_id else None
    for prop, vals in (scope or {}).items():
        col = dim_map.get(prop)
        if not col and ref.get("object_key_column"):
            ot = service.rt_get(ot_id) or {}
            if prop == (ot.get("spec") or {}).get("key_property"):
                col = ref["object_key_column"]
        if col and vals:
            where.append(f"{ident(col)} IN ({', '.join(lit(v) for v in vals)})")
    sql = f"SELECT {', '.join(select_parts)} FROM {source}"
    if where:
        sql += " WHERE " + " AND ".join(f"({w})" for w in where)
    direction = "ASC" if order == "asc" else "DESC"
    cap = int(max(1, min(limit, 5000)))
    named: dict[str, str] = {}          # 维度 → 名称列的列名(SQL 里已经带出来的)
    types: dict[str, dict] = {}         # 维度 → 它是哪类对象
    dim_types: dict[str, dict] = {}
    if base_ot:
        from . import objects
        b_ref = objects.table_binding(base_ot)["ref"]
        c2p = {v: k for k, v in (b_ref.get("columns") or {}).items()}
        for par in objects.parents(base_ot):
            prop = c2p.get(par["my_col"], par["my_col"])
            dim_types[prop] = par["other"]
            dim_types.setdefault(prop_label(base_ot, prop), par["other"])
    unnamed: dict[str, str] = {}        # 维度 → 对象类型名(是对象,但名称要查完再补)
    if dims:
        sql += " GROUP BY " + ", ".join(ident(dim_col(d)) for d in dims)
        joins, outer = [], []
        for i, d in enumerate(dims):
            outer.append(f"m.{ident(d)}")
            ot_d = dim_types.get(d) or dim_object_type(ref, d)
            if not ot_d:
                continue
            types[d] = {"type_id": ot_d["id"], "type_name": ot_d["name"]}
            tb = service.rt_binding(ot_d, "table") or {}
            tref = tb.get("ref") or {}
            if tb.get("ds_id") == ds_id and tref.get("label_column") and tref.get("key_column"):
                # 维度本身是对象(仓库、商品):同一个数据源里直接关联对象表带出名称,
                # 「查看 SQL」拿去重跑能得到一模一样的结果
                named[d] = f"{d}名称"
                outer.append(f"d{i}.{ident(tref['label_column'])} AS {ident(named[d])}")
                joins.append(f"LEFT JOIN {ident(tref['table'])} AS d{i} "
                             f"ON m.{ident(d)} = d{i}.{ident(tref['key_column'])}")
            else:
                unnamed[d] = ot_d["name"]
        if joins:
            sql = (f"SELECT {', '.join(outer)}, m.`value` FROM ({sql}) AS m {' '.join(joins)} "
                   f"ORDER BY m.`value` {direction}")
        else:
            sql += f" ORDER BY `value` {direction}"
    sql += f" LIMIT {cap}"
    return {"sql": sql, "ds_id": ds_id, "period": period, "dimensions": dims,
            "named": named, "unnamed": unnamed, "types": types}


def prop_label(ot: dict, prop: str) -> str:
    for p in (ot.get("spec") or {}).get("properties") or []:
        if p["name"] == prop:
            return p.get("display_name") or prop
    return prop


def value_label(m: dict) -> str:
    unit = (m.get("spec") or {}).get("unit") or ""
    name = m.get("display_name") or m["name"]
    return f"{name}({unit})" if unit and unit not in name else name


def col_meta(m: dict, compiled: dict, columns: list[str]) -> list[dict]:
    """结果的每一列怎么显示:数值列叫指标的名字;对象维度的编号列和名称列合成一列。"""
    ot = service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
    spec = m.get("spec") or {}
    out = []
    for c in columns:
        if c == "value":
            out.append({"name": c, "label": value_label(m), "role": "value", "unit": spec.get("unit") or "",
                        "format": spec.get("format") or ""})
            continue
        base = c[:-2] if c.endswith("名称") and c[:-2] in compiled["dimensions"] else ""
        if base:
            out.append({"name": c, "label": prop_label(ot, base) if ot else base, "role": "name", "of": base})
            continue
        meta = {"name": c, "label": prop_label(ot, c) if ot else c, "role": "dim"}
        if c in (compiled.get("types") or {}):
            meta.update(compiled["types"][c])
            meta["name_col"] = f"{c}名称" if f"{c}名称" in columns else ""
        out.append(meta)
    return out


def dim_object_type(ref: dict, dim: str) -> dict | None:
    """这个维度对应哪个对象类型(已发布)。绑定里声明了 dimension_types 就按声明,
    没声明时按「维度名就是对象类型名」认(「按仓库拆分」的仓库通常就是对象「仓库」)。"""
    declared = str((ref.get("dimension_types") or {}).get(dim) or "")
    if declared:
        return service.rt_get(declared) or service.rt_find(declared, "object_type")
    return service.rt_find(dim, "object_type")


def _fill_names(compiled: dict, columns: list[str], rows: list[list[Any]]) -> list[str]:
    """SQL 里带不出名称的对象维度(对象表在别的数据源),查完按主键补一列名称。返回补不上的维度。"""
    from . import objects
    missing = []
    for dim, type_name in (compiled.get("unnamed") or {}).items():
        if dim not in columns:
            continue
        i = columns.index(dim)
        names = objects.labels(type_name, [r[i] for r in rows])
        if not names:
            missing.append(dim)
            continue
        columns.insert(i + 1, f"{dim}名称")
        for r in rows:
            r.insert(i + 1, names.get(str(r[i]), ""))
    return missing


def query(ref: str | dict, *, dimensions: list[str] | None = None, filters: dict | None = None,
          time: Any = None, object_key: str = "", calendar_ref: str = "", order: str = "desc",
          limit: int = 200, question: str = "") -> dict:
    """ref 是名称 / id(取已发布定义),或直接给一份函数定义 dict(试跑工作副本用)。"""
    from ..text2sql import executor, semantic
    m = ref if isinstance(ref, dict) else metric(ref)
    compiled = compile_sql(m, dimensions=dimensions, filters=filters, time=time,
                           object_key=object_key, calendar_ref=calendar_ref, order=order,
                           limit=limit)
    ds = semantic.get_datasource(compiled["ds_id"])
    if ds is None:
        raise HTTPException(422, f"数据源 {compiled['ds_id']} 不存在")
    out = executor.execute(compiled["ds_id"], to_dialect(compiled["sql"], ds["ds_type"]), ds["ds_type"],
                           policy="catalog")
    status = "ok" if out.ok else "failed"
    rows = [[jsonable(v) for v in r] for r in (out.result.rows if out.result else [])]
    run_id = executor.log_run(
        compiled["ds_id"], question or f"[指标] {m['name']}", compiled["sql"],
        out.guard.sql if out.guard and out.guard.sql else compiled["sql"], status,
        plan={"metric": m["name"], "dimensions": compiled["dimensions"], "filters": filters,
              "time": compiled["period"], "object_key": object_key},
        error=out.error, row_count=len(rows),
        duration_ms=out.result.duration_ms if out.result else 0)
    if not out.ok:
        raise HTTPException(422, f"指标取数失败:{out.error}")
    columns = list(out.result.columns) if out.result else []
    notes = [f"「{d}」是对象,但取不到它的名称(对象没有名称列或查不到),结果里只有编号"
             for d in _fill_names(compiled, columns, rows)]
    calibre = None
    cr = (m.get("spec") or {}).get("calibre_rule")
    if cr:
        rc = service.rt_fn(cr, "rule")
        if rc:
            calibre = {"id": rc["id"], "name": rc["name"],
                       "text": (rc.get("spec") or {}).get("text") or rc.get("description", "")}
    value = rows[0][-1] if rows and not compiled["dimensions"] else None
    return {"metric": {"id": m["id"], "name": m["name"], "unit": (m.get("spec") or {}).get("unit", ""),
                       "direction": (m.get("spec") or {}).get("direction", "neutral")},
            "sql": out.guard.sql or compiled["sql"], "run_id": run_id,
            "columns": columns, "rows": rows, "col_meta": col_meta(m, compiled, columns),
            "value_label": value_label(m), "value": value, "period": compiled["period"], "calibre": calibre, "notes": notes,
            "truncated": bool(out.result and out.result.truncated)}


def query_many(calls: list[dict], workers: int = 6) -> list[dict | Exception]:
    """几个指标一起取(工作台的关键数字、对象页上这个对象的各项指标):并行发出去,按原顺序返回。
    每一项是 query() 的参数;某一项失败不影响别的,对应位置放的是那个异常。"""
    import contextvars
    from concurrent.futures import ThreadPoolExecutor
    if not calls:
        return []

    def one(kw: dict):
        try:
            return query(**kw)
        except Exception as e:  # noqa: BLE001
            return e
    if len(calls) == 1:
        return [one(calls[0])]
    with ThreadPoolExecutor(max_workers=min(workers, len(calls))) as pool:
        # 每个线程带上当前请求的身份 / 环境 / 预演状态
        futs = [pool.submit(contextvars.copy_context().run, one, kw) for kw in calls]
        return [f.result() for f in futs]