metrics.py 7.11 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


def metric(ref: str) -> dict:
    m = service.rt_find(ref, "metric")
    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'。按指标关联的日历解析期。"""
    if not time:
        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_find(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] = ref.get("dimensions") or {}

    def dim_col(name: str) -> str:
        if name in dim_map:
            return dim_map[name]
        c = service.rt_find(name, "dimension")
        if c and c["name"] in dim_map:
            return dim_map[c["name"]]
        for k in dim_map:           # 同义词:维度概念的别名
            dc = service.rt_find(k, "dimension")
            if dc and name in [dc["name"], *(dc.get("synonyms") or [])]:
                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 = (m.get("spec") or {}).get("object_type")
    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 {ident(ref['base_table'])}"
    if where:
        sql += " WHERE " + " AND ".join(f"({w})" for w in where)
    if dims:
        sql += " GROUP BY " + ", ".join(ident(dim_col(d)) for d in dims)
        sql += f" ORDER BY `value` {'ASC' if order == 'asc' else 'DESC'}"
    sql += f" LIMIT {int(max(1, min(limit, 5000)))}"
    return {"sql": sql, "ds_id": b["ds_id"], "period": period, "dimensions": dims}


def query(ref: str, *, 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:
    from ..text2sql import executor, semantic
    m = 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"], compiled["sql"], ds["ds_type"])
    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}")
    calibre = None
    cr = (m.get("spec") or {}).get("calibre_rule")
    if cr:
        rc = service.rt_find(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": out.result.columns if out.result else [], "rows": rows,
            "value": value, "period": compiled["period"], "calibre": calibre,
            "truncated": bool(out.result and out.result.truncated)}