objects.py 46.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
"""对象实例:按 ObjectType 的数据绑定从业务库读,叠加写回层。

写有两种模式,按数据源的「写回业务库」开关(extra.writeback)决定:
- 关(默认):Action 的修改只写 `otlg_object_edit`,读取时按属性覆盖,业务库不动;
- 开:审批通过的 Action 直接 UPDATE / INSERT 业务表(只限绑定过的表与列),
  `otlg_object_edit` 只留痕(mode=db / create),撤销时写回原值或删掉新建的行。
读取的 SQL 都经 text2sql.executor(同一套 guard + 行数上限 + 超时),不另开执行通道。
"""
from __future__ import annotations

import logging
import re
import threading
from typing import Any

from fastapi import HTTPException
from sqlalchemy import select

from ..core import identity
from ..core import reqcache
from ..core.dbx import iso, jdump, jload, session
from ..governance import audit
from . import rules, service
from .models import InstanceCache, ObjectEdit
from .sqlutil import ident, jsonable, lit, to_dialect

log = logging.getLogger(__name__)


def object_type(ref: str) -> dict:
    c = service.rt_find(ref, "object_type")
    if c is None:
        raise HTTPException(404, f"找不到已发布的对象类型「{ref}」")
    return c


def table_binding(ot: dict) -> dict:
    b = service.rt_binding(ot, "table")
    if b is None:
        raise HTTPException(422, f"对象类型「{ot['name']}」还没有绑定数据表")
    return b


@reqcache.per_request
def _run(ds_id: int, sql: str) -> tuple[list[str], list[list[Any]]]:
    from ..text2sql import executor, semantic
    ds = semantic.get_datasource(ds_id)
    if ds is None:
        raise HTTPException(422, f"数据源 {ds_id} 不存在")
    out = executor.execute(ds_id, to_dialect(sql, ds["ds_type"]), ds["ds_type"], policy="catalog")
    if not out.ok or out.result is None:
        raise HTTPException(422, f"查询失败:{out.error}")
    return out.result.columns, [[jsonable(v) for v in row] for row in out.result.rows]


def _same(ref: Any, ot: dict) -> bool:
    """关系两端存的可能是对象的 id,也可能是名称(AI 建模、模板导入存名称):两种都认。"""
    return bool(ref) and ref in (ot["id"], ot["name"], ot.get("display_name") or None)


# ---------------- 读取方案:列、算出来的属性、指向的对象 ----------------
def parents(ot: dict) -> list[dict]:
    """这类对象「指向」的对象:沿关系走过去,对方只有一个(对方那头的关联列是它的主键)。

    采购单 → 商品、库存 → 仓库都是这种。有了它,界面上的外键可以显示成对方的名称并点过去,
    公式里也能写「商品.进货价」。关系的方向不限 —— 只看哪一头是主键。
    """
    my = service.rt_binding(ot, "table")
    out: list[dict] = []
    if not my:
        return out
    for lt in service.rt_by_kind("link_type"):
        spec = lt.get("spec") or {}
        jb = service.rt_binding(lt, "join")
        if not jb:
            continue
        j = jb["ref"]
        sides = []
        if _same(spec.get("from_type"), ot):
            sides.append((spec.get("to_type"), j["from_column"], j["to_column"]))
        if _same(spec.get("to_type"), ot):
            sides.append((spec.get("from_type"), j["to_column"], j["from_column"]))
        for other_id, my_col, other_col in sides:
            other = service.rt_find(other_id, "object_type") if other_id else None
            ob = service.rt_binding(other, "table") if other else None
            if not ob or ob["ds_id"] != my["ds_id"] or ob["ref"].get("key_column") != other_col:
                continue
            if other["id"] == ot["id"] and my_col == other_col:
                continue
            out.append({"link": lt["name"], "link_id": lt["id"], "other": other, "other_ref": ob["ref"],
                        "my_col": my_col, "other_col": other_col, "alias": f"r{len(out)}"})
    return out


def _plan(ot: dict, ref: dict) -> dict:
    """读这一类对象要用的 SQL 片段。

    exprs:算出来的属性 → SQL;refs:哪个属性指向哪个对象;公式或名称用到的关联表才会被连上。
    """
    spec = ot.get("spec") or {}
    cols = dict(ref.get("columns") or {})
    props = {p["name"]: p for p in spec.get("properties") or []}
    ps = parents(ot)
    names: dict[str, list[dict]] = {}
    for p in ps:
        for n in {p["link"], p["other"]["name"], p["other"].get("display_name") or ""}:
            if n:
                names.setdefault(n, []).append(p)
    used: set[str] = set()
    exprs: dict[str, str] = {}
    errors: dict[str, str] = {}

    def col_sql(name: str, stack: tuple[str, ...]) -> str:
        if name in props and props[name].get("expression"):
            if name in stack:
                raise rules.RuleError(f"公式互相引用:{' → '.join(stack + (name,))}")
            return derive(name, stack)
        if name in cols:
            return f"t.{ident(cols[name])}"
        if name == spec.get("key_property"):
            return f"t.{ident(ref['key_column'])}"
        for p in spec.get("properties") or []:
            if name == p.get("display_name") and p["name"] != name:
                return col_sql(p["name"], stack)
        raise rules.RuleError(f"没有属性「{name}」")

    def attr_sql(obj: str, attr: str) -> str:
        hit = names.get(obj) or []
        if len(hit) != 1:
            raise rules.RuleError(f"「{obj}」不是这类对象指向的对象" if not hit
                                  else f"有多条关系指向「{obj}」,请写关系的名称")
        p = hit[0]
        ocols = p["other_ref"].get("columns") or {}
        ospec = p["other"].get("spec") or {}
        name = attr
        if name not in ocols:
            for op in ospec.get("properties") or []:
                if attr == op.get("display_name"):
                    name = op["name"]
                    break
        if name in ocols:
            col = ocols[name]
        elif name == ospec.get("key_property"):
            col = p["other_ref"]["key_column"]
        else:
            raise rules.RuleError(f"{p['other']['name']} 没有属性「{attr}」")
        used.add(p["alias"])
        return f"{p['alias']}.{ident(col)}"

    def derive(name: str, stack: tuple[str, ...] = ()) -> str:
        if name not in exprs:
            exprs[name] = rules.to_sql(props[name]["expression"],
                                       lambda n: col_sql(n, stack + (name,)), attr_sql)
        return exprs[name]

    for name, p in props.items():
        if p.get("expression"):
            try:
                derive(name)
            except (rules.RuleError, schema_error()) as e:
                exprs.pop(name, None)
                errors[name] = str(e)
    col2prop = {v: k for k, v in cols.items()}
    refs: dict[str, dict] = {}
    for p in ps:
        prop = col2prop.get(p["my_col"]) or (spec.get("key_property") if p["my_col"] == ref["key_column"] else "") \
            or p["my_col"]
        if prop in refs:
            continue
        refs[prop] = p
        if p["other_ref"].get("label_column"):
            used.add(p["alias"])
    joins = [f"LEFT JOIN {ident(p['other_ref']['table'])} AS {p['alias']} "
             f"ON t.{ident(p['my_col'])} = {p['alias']}.{ident(p['other_col'])}" for p in ps if p["alias"] in used]
    sel = ["t.*"] + [f"{sql} AS {ident(n)}" for n, sql in exprs.items()]
    for p in refs.values():
        if p["other_ref"].get("label_column") and p["alias"] in used:
            sel.append(f"{p['alias']}.{ident(p['other_ref']['label_column'])} AS {ident('ref__' + p['alias'])}")
    def out_sql(name: str) -> str:
        """筛选、排序时引用一个属性(外层查询里的列)。"""
        if name in exprs:
            return f"q.{ident(name)}"
        if name in cols:
            return f"q.{ident(cols[name])}"
        if name == spec.get("key_property"):
            return f"q.{ident(ref['key_column'])}"
        for p in spec.get("properties") or []:
            if name == p.get("display_name") and p["name"] != name:
                return out_sql(p["name"])
        raise rules.RuleError(f"没有属性「{name}」")

    return {"select": ", ".join(sel), "from": (f"{ident(ref['table'])} AS t " + " ".join(joins)).strip(),
            "exprs": exprs, "refs": refs, "errors": errors, "col_sql": out_sql}


def schema_error():
    from .schema import SpecError
    return SpecError


def source_sql(ot: dict) -> tuple[int, str]:
    """把这类对象当成一张表来查(含算出来的属性):指标建在对象上时用它当基表。返回 (数据源, 子查询)。"""
    b = table_binding(ot)
    plan = _plan(ot, b["ref"])
    where = _scope_where(ot, b["ref"])
    tail = (" WHERE " + " AND ".join(where)) if where else ""
    return b["ds_id"], f"(SELECT {plan['select']} FROM {plan['from']}{tail})"


def _scope_where(ot: dict, ref: dict) -> list[str]:
    """把当前用户的数据范围翻译成 WHERE 条件(只对能映射到列的属性生效)。"""
    scope = (identity.current().scope or {}).get(ot["id"]) or {}
    conds = []
    for prop, vals in scope.items():
        col = (ref.get("columns") or {}).get(prop)
        if prop == (ot.get("spec") or {}).get("key_property"):
            col = col or ref["key_column"]
        if col and vals:
            conds.append(f"t.{ident(col)} IN ({', '.join(lit(v) for v in vals)})")
    return conds


_TPL = re.compile(r"\{([^{}]+)\}")


def _to_obj(ot: dict, ref: dict, cols: list[str], row: list[Any], plan: dict | None = None) -> dict:
    raw = dict(zip(cols, row))
    col2prop = {v: k for k, v in (ref.get("columns") or {}).items()}
    props = {col2prop.get(k, k): v for k, v in raw.items() if not k.startswith("ref__")}
    key = raw.get(ref["key_column"])
    refs: dict[str, dict] = {}
    for prop, p in ((plan or {}).get("refs") or {}).items():
        v = props.get(prop)
        if v in (None, ""):
            continue
        lbl = raw.get("ref__" + p["alias"])
        refs[prop] = {"type_id": p["other"]["id"], "type_name": p["other"]["name"], "key": str(v),
                      "label": str(lbl) if lbl not in (None, "") else str(v)}
    spec = ot.get("spec") or {}
    label: Any = None
    tpl = spec.get("title_template") or ""
    if tpl:
        byname = {p.get("display_name") or p["name"]: p["name"] for p in spec.get("properties") or []}

        def fill(m: re.Match) -> str:
            n = m.group(1).strip()
            n = n if n in props else byname.get(n, n)
            if n in refs:
                return refs[n]["label"]
            v = props.get(n)
            if isinstance(v, float) and v.is_integer():
                v = int(v)
            return "" if v is None else str(v)
        label = _TPL.sub(fill, tpl).strip() or None
    elif ref.get("label_column"):
        label = raw.get(ref["label_column"])
    elif refs:
        # 没有名称列:用它指向的对象的名称拼一个,比光秃秃的主键好认
        label = " · ".join(r["label"] for r in list(refs.values())[:3])
    out = {"type_id": ot["id"], "type_name": ot["name"], "key": "" if key is None else str(key),
           "label": str(label) if label not in (None, "") else str(key), "properties": props}
    if refs:
        out["refs"] = refs
    return out


def columns(ot: dict) -> list[dict]:
    """这类对象的属性怎么显示:名称、类型、格式、单位、状态颜色、指向哪个对象。对象表格和详情页按它画。"""
    b = service.rt_binding(ot, "table")
    try:
        plan = _plan(ot, b["ref"]) if b else {"refs": {}, "errors": {}}
    except Exception:  # noqa: BLE001  绑定不完整时照样把列给出来
        plan = {"refs": {}, "errors": {}}
    out = []
    for p in (ot.get("spec") or {}).get("properties") or []:
        r = plan["refs"].get(p["name"])
        out.append({"name": p["name"], "label": p.get("display_name") or p["name"],
                    "data_type": p.get("data_type") or "string", "format": p.get("format") or "",
                    "unit": p.get("unit") or "", "tones": p.get("tones") or {},
                    "enum": p.get("enum_values") or [], "is_key": bool(p.get("is_key")),
                    "derived": bool(p.get("expression")), "description": p.get("description") or "",
                    "error": plan["errors"].get(p["name"], ""),
                    "ref": {"type_id": r["other"]["id"], "type_name": r["other"]["name"]} if r else None})
    return out


def _writeback(ds_id: int) -> bool:
    from ..text2sql import semantic
    ds = semantic.get_datasource(ds_id) or {}
    return bool((ds.get("extra") or {}).get("writeback"))


def _connector(ds_id: int):
    from ..text2sql import semantic
    return semantic.connector_for(ds_id)


def _overlay(obj: dict) -> dict:
    edits = active_edits(obj["type_id"], obj["key"])
    if edits:
        obj["properties"] = {**obj["properties"], **{e["property"]: e["value"] for e in edits}}
        obj["overridden"] = sorted({e["property"] for e in edits})
    return obj


def _fetch(ot: dict, where: list[str], order: str = "", limit: int = 1, offset: int = 0,
           count: bool = False) -> tuple[list[dict], int]:
    b = table_binding(ot)
    ref = b["ref"]
    plan = _plan(ot, ref)
    # 两层:里层算出每一行(含算出来的属性、占比这类要看全表的量),外层再筛选排序
    scope = _scope_where(ot, ref)
    inner = f"SELECT {plan['select']} FROM {plan['from']}" + ((" WHERE " + " AND ".join(scope)) if scope else "")
    tail = (" WHERE " + " AND ".join(where)) if where else ""
    sql = f"SELECT q.* FROM ({inner}) AS q{tail}"
    if order:
        sql += f" ORDER BY {order}"
    sql += f" LIMIT {int(limit)}" + (f" OFFSET {int(offset)}" if offset else "")
    cols, rows = _run(b["ds_id"], sql)
    total = len(rows)
    if count:
        _, cnt = _run(b["ds_id"], f"SELECT COUNT(*) AS n FROM ({inner}) AS q{tail}")
        total = int(cnt[0][0]) if cnt else len(rows)
    items = [_to_obj(ot, ref, cols, r, plan) for r in rows]
    _retitle_refs(items, plan)
    return items, total


_depth = threading.local()


def _retitle_refs(items: list[dict], plan: dict) -> None:
    """指向的对象如果是按标题模板起名的(如「工单号 车牌」),名称列带不出来:按主键再取一次它的标题。
    只做一层,避免对象之间互相指来指去时没完没了。"""
    if getattr(_depth, "n", 0) > 0 or not items:
        return
    _depth.n = 1
    try:
        for prop, p in (plan.get("refs") or {}).items():
            other = p["other"]
            if not (other.get("spec") or {}).get("title_template") and p["other_ref"].get("label_column"):
                continue
            keys = [o["refs"][prop]["key"] for o in items if (o.get("refs") or {}).get(prop)]
            if not keys:
                continue
            names = labels(other["id"], keys)
            for o in items:
                r = (o.get("refs") or {}).get(prop)
                if r and names.get(r["key"]):
                    r["label"] = names[r["key"]]
    finally:
        _depth.n = 0


def get(type_ref: str, key: str) -> dict:
    ot = object_type(type_ref)
    ref = table_binding(ot)["ref"]
    items, _ = _fetch(ot, [f"q.{ident(ref['key_column'])} = {lit(key)}"])
    if not items:
        raise HTTPException(404, f"{ot['name']}「{key}」不存在或不在你的数据范围内")
    return _overlay(items[0])


def _q_where(ref: dict, q: str) -> str:
    col = ref.get("label_column") or ref["key_column"]
    like = q.replace("\\", "").replace("%", "").replace("_", "")
    return f"(q.{ident(col)} LIKE {lit('%' + like + '%')} OR q.{ident(ref['key_column'])} = {lit(q)})"


def search(type_ref: str, q: str = "", limit: int = 20, offset: int = 0) -> list[dict]:
    ot = object_type(type_ref)
    ref = table_binding(ot)["ref"]
    where = [_q_where(ref, q)] if q else []
    items, _ = _fetch(ot, where, limit=int(max(1, min(limit, 200))), offset=int(max(0, offset)))
    return [_overlay(o) for o in items]


# 筛选条件支持的比较方式
QUERY_OPS: dict[str, str] = {
    "eq": "等于", "ne": "不等于", "gt": "大于", "ge": "大于等于", "lt": "小于", "le": "小于等于",
    "contains": "包含", "not_contains": "不包含", "startswith": "开头是", "in": "属于", "not_in": "不属于",
    "empty": "为空", "not_empty": "不为空",
}
_CMP = {"eq": "=", "ne": "<>", "gt": ">", "ge": ">=", "lt": "<", "le": "<="}


def _prop_sql(ot: dict, ref: dict, prop: Any, plan: dict | None = None) -> str:
    """属性名(或显示名)→ 可以写进 WHERE / ORDER BY 的 SQL。算出来的属性展开成它的公式。"""
    try:
        return (plan or _plan(ot, ref))["col_sql"](str(prop or "").strip())
    except rules.RuleError:
        names = [p.get("display_name") or p["name"] for p in (ot.get("spec") or {}).get("properties") or []]
        raise HTTPException(422, f"「{ot['name']}」没有可查询的属性「{prop}」,"
                                 f"可用:{'、'.join(names) or '无'}") from None


def _filter_sql(c: str, op: str, value: Any) -> str:
    if op == "empty":
        return f"({c} IS NULL OR {c} = '')"
    if op == "not_empty":
        return f"({c} IS NOT NULL AND {c} <> '')"
    if op in ("in", "not_in"):
        vals = value if isinstance(value, (list, tuple)) else [v.strip() for v in str(value).replace(",", ",").split(",")
                                                               if v.strip()]
        if not vals:
            raise HTTPException(422, "「属于」需要至少一个取值")
        return f"{c} {'NOT IN' if op == 'not_in' else 'IN'} ({', '.join(lit(v) for v in vals)})"
    if op in ("contains", "not_contains", "startswith"):
        like = str(value).replace("\\", "").replace("%", "").replace("_", "")
        pat = like + "%" if op == "startswith" else "%" + like + "%"
        return f"{c} {'NOT LIKE' if op == 'not_contains' else 'LIKE'} {lit(pat)}"
    if op in _CMP:
        if isinstance(value, bool):
            value = 1 if value else 0
        return f"{c} {_CMP[op]} {lit(value)}"
    raise HTTPException(422, f"不支持的比较方式「{op}」,可用:{'、'.join(QUERY_OPS)}")


def query(type_ref: str, filters: list[dict] | None = None, sort: list[dict] | None = None,
          q: str = "", limit: int = 50, offset: int = 0) -> dict:
    """按属性筛选 / 排序 / 分页地查一类对象:对象表格、流程卡「查对象」步骤、提问的对象快车道都走这里。

    filters: [{property, op, value}],条件之间是「并且」;sort: [{property, dir: asc|desc}]。
    返回 {items, total, limit, offset, columns};total 是满足条件的总数(不受分页影响)。
    """
    ot = object_type(type_ref)
    ref = table_binding(ot)["ref"]
    plan = _plan(ot, ref)
    where: list[str] = []
    for f in filters or []:
        op = str(f.get("op") or "eq")
        if op not in ("empty", "not_empty") and f.get("value") in (None, "", []):
            continue                                   # 没填值的条件当作没写
        where.append(_filter_sql(_prop_sql(ot, ref, f.get("property"), plan), op, f.get("value")))
    if q:
        where.append(_q_where(ref, q))
    order = [f"{_prop_sql(ot, ref, s.get('property'), plan)} "
             f"{'DESC' if str(s.get('dir') or '').lower() == 'desc' else 'ASC'}"
             for s in sort or [] if s.get("property")]
    order.append(f"q.{ident(ref['key_column'])} ASC")      # 末位按主键排,翻页才稳定
    limit, offset = int(max(1, min(limit, 500))), int(max(0, offset))
    items, total = _fetch(ot, where, ", ".join(order), limit, offset, count=True)
    return {"type_id": ot["id"], "type_name": ot["name"], "items": [_overlay(o) for o in items],
            "total": total, "limit": limit, "offset": offset, "fields": columns(ot)}


def labels(type_ref: str, keys: list[Any]) -> dict[str, str]:
    """一批主键 → 显示名(一条 SQL)。没绑表或查不到时返回空,调用方照原样显示主键。"""
    ot = service.rt_find(type_ref, "object_type")
    if not ot or not keys:
        return {}
    b = service.rt_binding(ot, "table")
    ref = (b or {}).get("ref") or {}
    if not ref.get("key_column"):
        return {}
    ks = list(dict.fromkeys(str(k) for k in keys if k not in (None, "")))[:200]
    if not ks:
        return {}
    try:
        items, _ = _fetch(ot, [f"q.{ident(ref['key_column'])} IN ({', '.join(lit(k) for k in ks)})"],
                          limit=len(ks))
    except HTTPException:
        return {}
    return {o["key"]: o["label"] for o in items if o["label"] and o["label"] != o["key"]}


def instances(workspace: str) -> list[dict]:
    with session() as s:
        return [{"concept_id": r.concept_id, "key": r.obj_key, "label": r.label}
                for r in s.scalars(select(InstanceCache).where(
                    InstanceCache.workspace == workspace)).all()]


# ---------------- 写回层 ----------------
def _edit_dict(e: ObjectEdit) -> dict:
    return {"id": e.id, "object_type": e.object_type, "object_key": e.object_key,
            "property": e.property, "value": jload(e.value_json, None),
            "prev": jload(e.prev_json, None), "action_run_id": e.action_run_id, "mode": e.mode or "overlay",
            "active": bool(e.active), "created_by": e.created_by, "created_at": iso(e.created_at)}


def active_edits(type_id: str, key: str) -> list[dict]:
    with session() as s:
        rows = s.scalars(select(ObjectEdit).where(
            ObjectEdit.workspace == identity.current().workspace,
            ObjectEdit.object_type == type_id, ObjectEdit.object_key == str(key),
            ObjectEdit.active == 1, ObjectEdit.mode == "overlay").order_by(ObjectEdit.id)).all()
        latest: dict[str, dict] = {}
        for e in rows:
            latest[e.property] = _edit_dict(e)
        return list(latest.values())


def edit_history(type_id: str, key: str) -> list[dict]:
    with session() as s:
        return [_edit_dict(e) for e in s.scalars(select(ObjectEdit).where(
            ObjectEdit.object_type == type_id, ObjectEdit.object_key == str(key))
            .order_by(ObjectEdit.id.desc()).limit(100)).all()]


def current_value(type_id: str, key: str, prop: str) -> Any:
    for e in active_edits(type_id, key):
        if e["property"] == prop:
            return e["value"]
    try:
        return get(type_id, key)["properties"].get(prop)
    except HTTPException:
        return None


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


# ---------------- 写入:一组操作,同一个数据源一个事务 ----------------
WRITE_OPS = {"create": "新建", "update": "修改", "create_rows": "按行新建"}
_OPS_REF = re.compile(r"\$ops\.([A-Za-z_一-鿿][\w.一-鿿]*)")


class _DryRun(Exception):
    """试写:执行到底再回滚。"""


def _ops_lookup(path: str, ctx: dict) -> Any:
    cur: Any = ctx
    for part in path.split("."):
        cur = cur.get(part) if isinstance(cur, dict) else None
    return cur


def _resolve_ops(v: Any, ctx: dict) -> Any:
    """值里引用前面操作的结果(`$ops.po.key`、`=ops.po.key + '-1'`):执行到这一步时才知道。"""
    if isinstance(v, str):
        if v.startswith("="):
            try:
                if "ops" in rules.free_names(v[1:]):
                    return rules.evaluate(v[1:], {"ops": ctx})
            except rules.RuleError as e:
                raise HTTPException(422, f"公式「{v}」算不出来:{e}") from e
            return v
        m = _OPS_REF.fullmatch(v.strip())
        if m:
            return _ops_lookup(m.group(1), ctx)
        return _OPS_REF.sub(lambda mm: str(_ops_lookup(mm.group(1), ctx) or ""), v)
    if isinstance(v, dict):
        return {k: _resolve_ops(x, ctx) for k, x in v.items()}
    if isinstance(v, list):
        return [_resolve_ops(x, ctx) for x in v]
    return v


def _check_values(ot: dict, values: dict[str, Any], creating: bool) -> dict[str, dict]:
    """属性名(或显示名)→ 属性定义;不存在、算出来的、没开放修改的、超出可选值的都拒绝。"""
    props = {p["name"]: p for p in (ot.get("spec") or {}).get("properties") or []}
    byname = {p.get("display_name"): p for p in props.values() if p.get("display_name")}
    cols = (table_binding(ot)["ref"].get("columns") or {})
    out: dict[str, dict] = {}
    for k in values:
        p = props.get(k) or byname.get(k)
        if p is None:
            if creating and k in cols:
                out[k] = {"name": k}
                continue
            raise HTTPException(422, f"{ot['name']} 没有属性「{k}」")
        name = p.get("display_name") or p["name"]
        if p.get("expression"):
            raise HTTPException(422, f"「{name}」是算出来的,不能直接写")
        if not creating and not p.get("is_writable"):
            raise HTTPException(422, f"「{ot['name']}」的「{name}」没有开放修改(在对象的属性里勾上「可修改」)")
        enum = p.get("enum_values") or []
        v = values[k]
        if enum and v not in (None, "") and not (isinstance(v, str) and v.startswith(("$ops.", "="))) \
                and v not in enum:
            raise HTTPException(422, f"「{name}」只能取 {'/'.join(enum)}")
        out[k] = p
    return out


def _expand(ops: list[dict]) -> list[dict]:
    """create_rows 摊成一条条 create(as 名下收集成列表)。"""
    out = []
    for i, op in enumerate(ops or []):
        kind = str(op.get("op") or "")
        if kind not in WRITE_OPS:
            raise HTTPException(422, f"第 {i + 1} 条写入的类型「{kind}」不认识,只能是 {'/'.join(WRITE_OPS)}")
        if kind == "create_rows":
            rows = op.get("rows") or []
            if not isinstance(rows, list):
                raise HTTPException(422, f"第 {i + 1} 条写入(按行新建)的数据来源不是多行数据")
            for j, values in enumerate(rows):
                out.append({**op, "op": "create", "values": values or {}, "_many": True, "_row": j + 1})
        else:
            out.append(op)
    return out


def plan_ops(ops: list[dict]) -> dict:
    """写入前的检查与预览:每条操作落到哪张表、改什么。不碰数据库的写。
    返回 {ds_id, writeback, changes[]};跨数据源、没开写回却要新建的,直接报错。"""
    flat = _expand(ops)
    if not flat:
        raise HTTPException(422, "没有要写入的内容(按行新建的数据来源可能是空的)")
    ds_ids: set[int] = set()
    changes: list[dict] = []
    for op in flat:
        ot = object_type(str(op.get("object_type") or ""))
        b = table_binding(ot)
        ds_ids.add(int(b["ds_id"]))
        values = op.get("values") or {}
        if not isinstance(values, dict) or not values:
            raise HTTPException(422, f"写入「{ot['name']}」还没填要写的字段")
        pmap = _check_values(ot, values, op["op"] == "create")
        if op["op"] == "update" and op.get("key") in (None, ""):
            raise HTTPException(422, f"修改「{ot['name']}」要指定改哪一个(主键)")
        for k, v in values.items():
            p = pmap.get(k) or {}
            prev = None
            if op["op"] == "update" and not (isinstance(op.get("key"), str) and "$ops." in op["key"]):
                prev = current_value(ot["id"], str(op["key"]), p.get("name") or k)
            changes.append({"kind": op["op"], "object_type": ot["name"], "type_id": ot["id"],
                            "key": "" if op["op"] == "create" else str(op.get("key")),
                            "object": "" if op["op"] == "create" else str(op.get("key")),
                            "as": str(op.get("as") or ""), "row": op.get("_row") or 0,
                            "property": p.get("display_name") or k, "from": prev,
                            "to": "(保存后生成)" if isinstance(v, str) and "$ops." in v else v,
                            "format": p.get("format") or "", "unit": p.get("unit") or ""})
    if len(ds_ids) > 1:
        raise HTTPException(422, "一次写入只能写同一个数据源里的表(跨库无法放进一个事务);请拆成两个写数据步骤")
    ds_id = ds_ids.pop()
    wb = _writeback(ds_id)
    if wb:
        # 写回业务库:每个要写的属性都得对上一列(只在本系统里有的属性写不进业务表)
        for op in flat:
            ot = object_type(op["object_type"])
            ref = table_binding(ot)["ref"]
            cols = ref.get("columns") or {}
            key_prop = (ot.get("spec") or {}).get("key_property")
            byname = {p.get("display_name"): p["name"] for p in (ot.get("spec") or {}).get("properties") or [] if p.get("display_name")}
            for k in (op.get("values") or {}):
                prop = byname.get(k, k)
                if prop not in cols and prop != key_prop and k not in cols:
                    raise HTTPException(422, f"「{ot['name']}」的「{k}」没有对应业务表里的列,写不进业务库(在对象的数据来源里把它绑定到一列)")
    if not wb and any(op["op"] == "create" for op in flat):
        raise HTTPException(422, "要新建数据,数据源必须开启「允许写回业务库」(在数据连接里编辑数据源,打开这个开关)")
    return {"ds_id": ds_id, "writeback": wb, "changes": changes}


def apply_ops(ops: list[dict], action_run_id: str = "", dry: bool = False) -> dict:
    """按顺序执行一组写入,同一个数据源一个事务:任何一条失败,前面写进去的全部回滚。

    ops: [{op: create|update|create_rows, object_type, as?, key?(update), values?, rows?(create_rows)}]
    值里可以引用前面操作的结果:`$ops.<as>.key`(新建出来的主键,含自增主键)。
    dry=True:在事务里真的执行一遍再回滚 —— 主键冲突、非空约束这类问题试运行时就能暴露。
    返回 {created: {as: 主键 | [主键…]}, edit_ids, changes, summary}。"""
    flat = _expand(ops)
    plan = plan_ops(ops)
    ctx: dict[str, Any] = {}
    created: dict[str, Any] = {}
    pending: list[dict] = []              # 要记进写回层的留痕(业务库提交后再记)
    connector = _connector(plan["ds_id"]) if plan["writeback"] else None
    actor = identity.current()

    def run(conn: Any) -> None:
        for op in flat:
            ot = object_type(op["object_type"])
            ref = table_binding(ot)["ref"]
            cols = ref.get("columns") or {}
            values = _resolve_ops(op.get("values") or {}, ctx)
            pmap = _check_values(ot, values, op["op"] == "create")
            name = str(op.get("as") or "")
            if op["op"] == "create":
                row = {}
                for k, v in values.items():
                    if v is None:
                        continue
                    prop = pmap[k].get("name", k)
                    col = cols.get(prop) or (ref["key_column"] if prop == (ot.get("spec") or {}).get("key_property")
                                             else prop)
                    row[col] = v
                key = connector.insert_row(ref["table"], row, ref["key_column"], conn=conn)
                key = "" if key is None else str(key)
                pending.append({"type_id": ot["id"], "key": key, "property": "*", "value": values,
                                "prev": None, "mode": "create", "label": f"新建{ot['name']}「{key}」"})
                res = {"key": key, **values}
                if name:
                    if op.get("_many"):
                        ctx.setdefault(name, []).append(res)
                        created.setdefault(name, []).append(key)
                    else:
                        ctx[name] = res
                        created[name] = key
                continue
            key = str(_resolve_ops(op.get("key"), ctx))
            changed = {}
            for k, v in values.items():
                prop = pmap[k]["name"]
                prev = current_value(ot["id"], key, prop)
                changed[prop] = v
                pending.append({"type_id": ot["id"], "key": key, "property": prop, "value": v, "prev": prev,
                                "mode": "db" if conn is not None else "overlay",
                                "label": f"{ot['name']}「{key}」的{pmap[k].get('display_name') or prop}:"
                                         f"{_brief(prev)} → {_brief(v)}"})
            if conn is not None:
                row = {cols.get(p, p): v for p, v in changed.items()}
                n = connector.write_row(ref["table"], row, ref["key_column"], key, conn=conn)
                if not n and not _exists(ot, key):
                    raise HTTPException(404, f"{ot['name']}「{key}」在业务库里不存在,未写入")
            if name:
                ctx[name] = {"key": key, **changed}
                created[name] = key
        if dry:
            raise _DryRun

    try:
        if connector is not None:
            with connector.transaction() as conn:
                run(conn)
        else:
            run(None)
    except _DryRun:
        pass
    except HTTPException:
        raise
    except Exception as e:  # noqa: BLE001  数据库约束错误等:事务已整体回滚
        log.warning("写入失败,已回滚:%s", e)
        raise HTTPException(422, f"写入业务库失败,已全部回滚:{_db_error(e)}") from e
    reqcache.clear()
    news = [p["label"] for p in pending if p["mode"] == "create"]
    summary = ";".join(news[:6]) + (f" 等 {len(news)} 条" if len(news) > 6 else "")
    upd = [p for p in pending if p["mode"] != "create"]
    if upd:
        summary = ";".join(x for x in (summary, f"修改 {len(upd)} 处" if len(upd) > 3
                                        else ";".join(p["label"] for p in upd)) if x)
    if dry:
        return {"created": created, "edit_ids": [], "changes": plan["changes"], "dry": True,
                "summary": f"试写通过(已回滚):{summary}"}
    ids = []
    with session() as s:
        for p in pending:
            e = ObjectEdit(workspace=actor.workspace, object_type=p["type_id"], object_key=p["key"],
                           property=p["property"], value_json=jdump(p["value"]), prev_json=jdump(p["prev"]),
                           action_run_id=action_run_id, created_by=actor.id, mode=p["mode"])
            s.add(e)
            s.flush()
            ids.append(e.id)
        s.commit()
    for p in pending:
        audit.record("object.create" if p["mode"] == "create" else "object.write", "object",
                     f"{p['type_id']}:{p['key']}", p["label"],
                     before=None if p["mode"] == "create" else {p["property"]: p["prev"]},
                     after=p["value"] if p["mode"] == "create" else {p["property"]: p["value"]})
    return {"created": created, "edit_ids": ids, "changes": plan["changes"], "summary": summary}


def _brief(v: Any) -> str:
    if v is None or v == "":
        return "空"
    if isinstance(v, float) and v.is_integer():
        return str(int(v))
    return str(v)


def _exists(ot: dict, key: str) -> bool:
    try:
        get(ot["id"], key)
        return True
    except HTTPException:
        return False


def _db_error(e: Exception) -> str:
    msg = str(getattr(e, "orig", None) or e)
    return msg.splitlines()[0][:300]


def revert_edits(edit_ids: list[int]) -> list[dict]:
    """撤销一组写入(倒序):删掉新建的行、把改过的列写回原值。同一个数据源的放进一个事务。"""
    with session() as s:
        rows = [s.get(ObjectEdit, int(i)) for i in edit_ids]
        info = [(e.id, e.mode or "overlay", e.object_type, e.object_key, e.property, jload(e.prev_json, None))
                for e in rows if e is not None and e.active]
    by_ds: dict[int, list] = {}
    for x in info:
        if x[1] in ("db", "create"):
            by_ds.setdefault(int(table_binding(object_type(x[2]))["ds_id"]), []).append(x)
    for ds_id, items in by_ds.items():
        conn_obj = _connector(ds_id)
        with conn_obj.transaction() as conn:
            for _, mode, type_id, key, prop, prev in reversed(items):
                ref = table_binding(object_type(type_id))["ref"]
                if mode == "create":
                    conn_obj.delete_row(ref["table"], ref["key_column"], key, conn=conn)
                else:
                    col = (ref.get("columns") or {}).get(prop) or prop
                    conn_obj.write_row(ref["table"], {col: prev}, ref["key_column"], key, conn=conn)
    if by_ds:
        reqcache.clear()
    out = []
    with session() as s:
        for eid, *_ in info:
            e = s.get(ObjectEdit, eid)
            e.active = 0
            out.append(_edit_dict(e))
        s.commit()
    for o in out:
        audit.record("object.revert", "object", f"{o['object_type']}:{o['object_key']}",
                     f"撤销写回 {o['property']}(恢复为 {o['prev']!r})", before=o)
    return out




# ---------------- 关联对象 ----------------
def link_sides(ot: dict) -> list[dict]:
    """这类对象能沿哪些关系走到别的对象:[{link, link_id, direction, other, my_col, other_col, single}]。
    single:对方那头的关联列是对方的主键(一对一 / 多对一),走过去只会有一个。"""
    out = []
    for lt in service.rt_by_kind("link_type"):
        spec = lt.get("spec") or {}
        jb = service.rt_binding(lt, "join")
        if not jb:
            continue
        j = jb["ref"]
        sides = []
        if _same(spec.get("from_type"), ot):
            sides.append((spec.get("to_type"), j["from_column"], j["to_column"], "out"))
        if _same(spec.get("to_type"), ot):
            sides.append((spec.get("from_type"), j["to_column"], j["from_column"], "in"))
        for other_ref, my_col, other_col, direction in sides:
            other = service.rt_find(other_ref, "object_type") if other_ref else None
            ob = service.rt_binding(other, "table") if other else None
            if not ob:
                continue
            out.append({"link": lt["name"], "link_id": lt["id"], "direction": direction, "other": other,
                        "my_col": my_col, "other_col": other_col,
                        "label": (lt.get("display_name") or lt["name"]) if direction == "out"
                        else ((spec.get("inverse_name") or "") or (other.get("display_name") or other["name"])),
                        "single": ob["ref"].get("key_column") == other_col})
    return out


def _raw_value(ot: dict, obj: dict, col: str) -> Any:
    """一个对象在某一列上的原始值(列名 → 属性名;主键列就是 key)。"""
    ref = table_binding(ot)["ref"]
    if col == ref["key_column"]:
        return obj.get("key")
    col2prop = {v: k for k, v in (ref.get("columns") or {}).items()}
    props = obj.get("properties") if isinstance(obj.get("properties"), dict) else obj
    return props.get(col2prop.get(col, col))


def linked(type_ref: str, key: str, limit: int = 20) -> list[dict]:
    ot = object_type(type_ref)
    me = get(ot["id"], key)
    out = []
    for side in link_sides(ot):
        val = _raw_value(ot, me, side["my_col"])
        if val is None:
            continue
        other = side["other"]
        try:
            items, total = _fetch(other, [f"q.{ident(side['other_col'])} = {lit(val)}"], limit=int(limit), count=True)
        except HTTPException as e:
            log.debug("关联对象查询失败:%s", e.detail)
            continue
        out.append({"link_type": side["link"], "link_id": side["link_id"], "direction": side["direction"],
                    "object_type": other["name"], "object_type_id": other["id"], "single": side["single"],
                    "items": items, "total": total, "fields": columns(other)})
    return out


# ---------------- 查数据:条件组 + 沿关系带出关联对象 ----------------
FETCH_DEPTH = 3
FETCH_MAX_ROWS = 2000           # 一次查数据(含各层关联)最多取回的行数
AGG_FNS = {"count": "条数", "sum": "合计", "avg": "平均", "min": "最小", "max": "最大"}


def cond_sql(ot: dict, ref: dict, plan: dict, cond: Any) -> str:
    """条件组 → WHERE 片段。cond = {mode: all|any, items: [{left: 属性, op, right} | 子条件组]};
    右边的值调用方已经算好(引用的变量已替换)。没填值的条件当作没写。"""
    if not isinstance(cond, dict):
        return ""
    parts = []
    for it in cond.get("items") or []:
        if not isinstance(it, dict):
            continue
        if "items" in it:
            sub = cond_sql(ot, ref, plan, it)
            if sub:
                parts.append(f"({sub})")
            continue
        prop, op, val = it.get("left"), str(it.get("op") or "eq"), it.get("right")
        if not prop:
            continue
        if op not in ("empty", "not_empty") and val in (None, "", []):
            continue
        parts.append(_filter_sql(_prop_sql(ot, ref, str(prop).lstrip("$").removeprefix("item."), plan), op, val))
    joiner = " OR " if cond.get("mode") == "any" else " AND "
    return joiner.join(parts)


def _flat(o: dict, fields: list[str] | None) -> dict:
    """对象 → 流程里好引用的扁平字典:{key, label, 属性…}。fields 不空时只留这些属性。"""
    props = o.get("properties") or {}
    if fields:
        props = {k: v for k, v in props.items() if k in fields}
    out = {"key": o.get("key"), "label": o.get("label"), **props}
    for prop, r in (o.get("refs") or {}).items():
        if not fields or prop in fields:
            out.setdefault(f"{prop}__名称", r.get("label"))
    return out


def _order(ot: dict, ref: dict, plan: dict, sort: list[dict] | None) -> str:
    order = [f"{_prop_sql(ot, ref, s.get('property'), plan)} {'DESC' if str(s.get('dir') or '').lower() == 'desc' else 'ASC'}"
             for s in sort or [] if s.get("property")]
    order.append(f"q.{ident(ref['key_column'])} ASC")
    return ", ".join(order)


def _find_side(ot: dict, link: str) -> dict:
    sides = link_sides(ot)
    hit = [x for x in sides if link in (x["link"], x["link_id"], x["label"], x["other"]["name"], x["other"]["id"])]
    if not hit:
        names = "、".join(dict.fromkeys(f"{x['label']}({x['other']['name']})" for x in sides)) or "无"
        raise HTTPException(422, f"「{ot['name']}」没有叫「{link}」的关系,可用:{names}")
    return hit[0]


def _attach(ot: dict, parents: list[dict], raw: list[dict], inc: dict, depth: int, budget: list[int]) -> None:
    """给一批父对象挂上一种关联对象(一条 SQL:IN 父对象的关联值),再递归下一层。"""
    side = _find_side(ot, str(inc.get("link") or ""))
    other = side["other"]
    oref = table_binding(other)["ref"]
    oplan = _plan(other, oref)
    vals = list(dict.fromkeys(v for v in (_raw_value(ot, r, side["my_col"]) for r in raw) if v not in (None, "")))
    name = str(inc.get("as") or side["label"])
    many = str(inc.get("mode") or ("one" if side["single"] else "list")) == "list"
    per = max(1, min(int(inc.get("limit") or 50), 500))
    groups: dict[str, list[dict]] = {}
    child_raw: dict[str, list[dict]] = {}
    if vals and budget[0] > 0:
        where = [f"q.{ident(side['other_col'])} IN ({', '.join(lit(v) for v in vals)})"]
        extra = cond_sql(other, oref, oplan, inc.get("where"))
        if extra:
            where.append(f"({extra})")
        items, _ = _fetch(other, where, _order(other, oref, oplan, inc.get("sort")), limit=budget[0])
        budget[0] -= len(items)
        items = [_overlay(o) for o in items]
        for o in items:
            k = str(_raw_value(other, o, side["other_col"]))
            child_raw.setdefault(k, []).append(o)
    fields = [str(f) for f in inc.get("fields") or [] if f]
    if inc.get("include") and depth < FETCH_DEPTH:
        all_children = [o for lst in child_raw.values() for o in lst]
        flat_children = [_flat(o, fields) for o in all_children]
        for sub in inc.get("include") or []:
            _attach(other, flat_children, all_children, sub, depth + 1, budget)
        by_id = {id(o): f for o, f in zip(all_children, flat_children)}
        for k, lst in child_raw.items():
            groups[k] = [by_id[id(o)] for o in lst]
    else:
        groups = {k: [_flat(o, fields) for o in lst] for k, lst in child_raw.items()}
    for p, r in zip(parents, raw):
        mine = groups.get(str(_raw_value(ot, r, side["my_col"])), [])[:per]
        p[name] = mine if many else (mine[0] if mine else None)
        for a in inc.get("aggs") or []:
            fn = str(a.get("fn") or "count")
            field = str(a.get("field") or "")
            label = str(a.get("as") or f"{name}{AGG_FNS.get(fn, fn)}")
            nums = [float(x) for x in (rules._num(m.get(field)) for m in mine) if isinstance(x, (int, float))]
            p[label] = (len(mine) if fn == "count" else sum(nums) if fn == "sum"
                        else (sum(nums) / len(nums) if nums else None) if fn == "avg"
                        else (min(nums) if nums else None) if fn == "min" else (max(nums) if nums else None))


def fetch(object_type_ref: str, where: Any = None, fields: list[str] | None = None,
          include: list[dict] | None = None, sort: list[dict] | None = None, limit: int = 50,
          mode: str = "list") -> dict:
    """一次查出一个对象(或一批)连同它的关联对象,返回嵌套好的数据 —— 流程卡「查数据」节点、
    函数 object.fetch 走这里。每一层关联对象只发一条 SQL(IN 父对象的关联值),不会随行数变多。

    include: [{link: 关系名或对方对象名, as: 放在哪个字段, mode: one|list, where: 条件组, fields, sort, limit,
               aggs: [{fn: count|sum|avg|min|max, field, as}], include: [...下一层]}]
    mode=one:只要第一条,返回 {item, found};list:返回 {items, total}。"""
    ot = object_type(object_type_ref)
    ref = table_binding(ot)["ref"]
    plan = _plan(ot, ref)
    w = cond_sql(ot, ref, plan, where)
    one = mode == "one"
    n = 1 if one else max(1, min(int(limit or 50), 500))
    items, total = _fetch(ot, [w] if w else [], _order(ot, ref, plan, sort), limit=n, count=not one)
    items = [_overlay(o) for o in items]
    flds = [str(f) for f in fields or [] if f]
    flat = [_flat(o, flds) for o in items]
    budget = [FETCH_MAX_ROWS]
    for inc in include or []:
        _attach(ot, flat, items, inc, 1, budget)
    if one:
        hit = flat[0] if flat else None
        return {"item": hit, "found": hit is not None, "type_name": ot["name"],
                "summary": f"{ot['name']}「{hit['label']}」" if hit else f"没有找到满足条件的{ot['name']}"}
    return {"items": flat, "total": total, "type_name": ot["name"],
            "summary": f"{ot['name']} 共 {total} 个" + (f",取了前 {len(flat)} 个" if len(flat) < total else "")}