objects.py 80.1 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 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
"""对象实例:按对象类型的后备数据源读,叠加写回层;写入放在同一个事务里,留下变化记录。

读:数据从哪来由绑定决定(kernel/sources.py:单表 / 多表组合 / 表的一部分 / 多源合并 / SQL / 本体自建 / 系统对象),
这里只认它编译出来的「有效绑定」。接口(abstract 对象)的有效绑定是所有实现它的对象合并起来的,主键带类型前缀。

写有两种模式,按数据源的「写回业务库」开关(extra.writeback)决定:
- 关(默认):修改只写 `otlg_object_edit`,读取时按属性覆盖,业务库不动;
- 开:审批通过的动作直接 UPDATE / INSERT / DELETE 业务表(只限可写的数据来源与列),
  `otlg_object_edit` 留痕(mode=db / create / delete / link / unlink),撤销时恢复原样。
本体自建对象存在「本体存储」里,那个数据源永远开着写回。

每一次写入都做统一校验:属性存在且可写、值类型、可选值、状态机(状态只能经由动作的流转改变)、关系基数;
写完记进变化记录(otlg_object_change)并通知订阅者(预警规则的「变化即触发」靠它)。
读取的 SQL 都经 text2sql.executor(同一套 guard + 行数上限 + 超时),不另开执行通道。
"""
from __future__ import annotations

import contextlib
import contextvars
import logging
import re
import threading
from typing import Any, Callable

from fastapi import HTTPException
from sqlalchemy import select

from ..core import identity
from ..core import reqcache
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import rules, service, sources, valuetypes
from .models import ObjectChange, ObjectEdit, ObjectIndex
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 is_interface(ot: dict) -> bool:
    return bool((ot.get("spec") or {}).get("abstract"))


def binding(ot: dict | None) -> dict | None:
    """对象类型的有效绑定(见 kernel/sources.py);没有数据来源返回 None。"""
    if not ot:
        return None
    if is_interface(ot):
        try:
            return _interface_binding(ot)
        except HTTPException:
            return None
    b = service.rt_binding(ot, "table")
    if b is None:
        return None
    return {**b, "ref": sources.effective(b["ref"], identity.current().workspace)}


def table_binding(ot: dict) -> dict:
    if is_interface(ot):
        return _interface_binding(ot)
    b = binding(ot)
    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 implementations(iface: dict) -> list[tuple[dict, dict[str, str]]]:
    """实现这个接口的对象:[(对象类型, {接口属性: 我的属性})]。没写映射的属性按同名对上。"""
    out = []
    for c in service.rt_by_kind("object_type"):
        if is_interface(c):
            continue
        for imp in (c.get("spec") or {}).get("implements") or []:
            if _same(imp.get("interface"), iface):
                out.append((c, dict(imp.get("mapping") or {})))
                break
    return out


def _interface_binding(iface: dict) -> dict:
    impls = implementations(iface)
    if not impls:
        raise HTTPException(422, f"接口「{iface['name']}」还没有任何对象实现它")
    props = [p["name"] for p in (iface.get("spec") or {}).get("properties") or []]
    parts, ds = [], None
    for c, mapping in impls:
        b = binding(c)
        if b is None:
            continue
        if ds is None:
            ds = b["ds_id"]
        elif b["ds_id"] != ds:
            raise HTTPException(422, f"实现接口「{iface['name']}」的对象分布在不同的数据源里,不能合并查询")
        ref = b["ref"]
        plan = _plan(c, ref)
        scope = _scope_where(c, ref)
        inner = f"SELECT {plan['select']} FROM {plan['from']}" + ((" WHERE " + " AND ".join(scope)) if scope else "")
        sel = [f"CONCAT({lit(c['id'] + ':')}, q.{ident(ref['key_column'])}) AS {ident('__key')}",
               f"{lit(c['id'])} AS {ident('__type')}",
               f"q.{ident(ref['label_column'] or ref['key_column'])} AS {ident('__label')}"]
        for p in props:
            mine = mapping.get(p) or p
            try:
                sel.append(f"{plan['col_sql'](mine)} AS {ident(p)}")
            except rules.RuleError:
                sel.append(f"NULL AS {ident(p)}")
        parts.append(f"SELECT {', '.join(sel)} FROM ({inner}) AS q")
    if not parts:
        raise HTTPException(422, f"实现接口「{iface['name']}」的对象都还没有数据来源")
    ref = {"kind": "interface", "from": "(" + " UNION ALL ".join(parts) + ")", "table": "",
           "key_column": "__key", "label_column": "__label", "columns": {p: p for p in props}, "writable": False}
    return {"id": f"bd_{iface['id']}", "concept_id": iface["id"], "ds_id": ds, "target_kind": "table", "ref": ref}


def concrete(type_ref: str, key: Any) -> tuple[dict, str]:
    """接口上的对象(主键是「对象类型id:主键」)→ 具体的对象类型和它自己的主键。不是接口原样返回。"""
    ot = object_type(type_ref)
    key = "" if key is None else str(key)
    if not is_interface(ot):
        return ot, key
    impls = implementations(ot)
    if ":" in key:
        tid, k = key.split(":", 1)
        for c, _ in impls:
            if c["id"] == tid:
                return c, k
    for c, _ in impls:                         # 没带类型前缀:挨个实现找这个主键
        try:
            get(c["id"], key)
            return c, key
        except HTTPException:
            continue
    raise HTTPException(404, f"{ot['name']}「{key}」不存在")


def interface_mapping(iface: dict, impl: dict) -> dict[str, str]:
    for c, mapping in implementations(iface):
        if c["id"] == impl["id"]:
            return mapping
    return {}


# ---------------- 读取方案:列、算出来的属性、指向的对象 ----------------
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 or jb["ref"].get("via_table"):
            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 = binding(other) if other and not is_interface(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, alias: str = "t") -> dict:
    """读这一类对象要用的 SQL 片段。ref 是有效绑定(sources.effective)。

    exprs:算出来的属性 → SQL;refs:哪个属性指向哪个对象;公式或名称用到的关联表才会被连上。
    alias:主表的别名。汇总子查询里嵌着另一类对象的读取方案时换一个,免得和外层的 t 撞名。
    """
    A = alias
    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) if A == "t" else [{**p, "alias": f"{A}_{p['alias']}"} for p in 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"{A}.{ident(cols[name])}"
        if name == spec.get("key_property"):
            return f"{A}.{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 rollup_sql(fn: str, target: str, field: str, cond: str) -> str:
        """count_of(订单, 'is_overdue') 这类:沿关系找到「指向我的那些记录」,汇总成一个关联子查询。
        对方的计算属性也能用(对方按它自己的读取方案先算一遍)。中间表关系也行(经中间表找到对方)。"""
        kids = [s for s in link_sides(ot) if not s["single"] and target in {
            s["link"], s["label"], s["other"]["name"], s["other"].get("display_name") or "",
            *(s["other"].get("synonyms") or [])}]
        if len(kids) != 1:
            raise rules.RuleError(f"「{target}」不是指向这类对象的记录(要写关系名或对方对象名)" if not kids
                                  else f"有多条关系通向「{target}」,请写关系的名称")
        k = kids[0]
        other = k["other"]
        oref = table_binding(other)["ref"]
        stack_ids = getattr(_planning, "ids", ())
        if other["id"] in stack_ids:
            raise rules.RuleError(f"「{other['name']}」和「{ot['name']}」的计算属性互相汇总,算不出来")
        _planning.ids = stack_ids + (ot["id"],)
        inner, outer = f"{A}i", f"{A}c"
        try:
            cplan = _plan(other, oref, alias=inner)
        finally:
            _planning.ids = stack_ids

        def c(name: str) -> str:
            try:
                return f"{outer}." + cplan["col_sql"](name)[2:]
            except rules.RuleError:
                raise rules.RuleError(f"{other['name']} 没有属性「{name}」") from None
        agg = {"count_of": "COUNT(*)", "sum_of": f"COALESCE(SUM({c(field)}), 0)" if field else "",
               "avg_of": f"AVG({c(field)})" if field else "", "max_of": f"MAX({c(field)})" if field else "",
               "min_of": f"MIN({c(field)})" if field else ""}[fn]
        if k.get("via"):
            v = k["via"]
            where = (f"{outer}.{ident(k['other_col'])} IN (SELECT {ident(v['other'])} FROM {ident(v['table'])} "
                     f"WHERE {ident(v['mine'])} = {A}.{ident(k['my_col'])})")
        else:
            where = f"{outer}.{ident(k['other_col'])} = {A}.{ident(k['my_col'])}"
        if cond:
            where += f" AND COALESCE({c(cond)}, 0) <> 0"
        return f"(SELECT {agg} FROM (SELECT {cplan['select']} FROM {cplan['from']}) AS {outer} WHERE {where})"

    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, rollup_sql)
        return exprs[name]

    for name, p in props.items():
        if p.get("expression"):
            try:
                derive(name)
            except (rules.RuleError, schema_error(), HTTPException) as e:
                exprs.pop(name, None)
                errors[name] = str(getattr(e, "detail", 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 {p['other_ref']['from']} AS {p['alias']} "
             f"ON {A}.{ident(p['my_col'])} = {p['alias']}.{ident(p['other_col'])}" for p in ps if p["alias"] in used]
    sel = [f"{A}.*"] + [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"{ref['from']} AS {A} " + " ".join(joins)).strip(),
            "exprs": exprs, "refs": refs, "errors": errors, "col_sql": out_sql}


_planning = threading.local()          # 正在算读取方案的对象(汇总子查询互相引用时防止无限递归)


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


def stored_here(p: dict) -> bool:
    """本体自有属性:业务表里没有这一列,值存在本系统里(按对象主键挂着),读的时候叠上去。"""
    return (p or {}).get("storage") == "ontology"


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__") and k not in ("__type",)}
    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])
    props.pop("__key", None)
    props.pop("__label", None)
    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 "__type" in raw:                                   # 接口上的对象:带上它具体是哪一类
        impl = service.rt_get(str(raw["__type"])) or {}
        out["impl_type"] = {"id": raw["__type"], "name": impl.get("name") or raw["__type"]}
    if refs:
        out["refs"] = refs
    return out


def columns(ot: dict) -> list[dict]:
    """这类对象的属性怎么显示:名称、类型、格式、单位、状态颜色、状态机、指向哪个对象。对象表格和详情页按它画。"""
    b = binding(ot)
    try:
        plan = _plan(ot, b["ref"]) if b and not is_interface(ot) 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"])
        shown = valuetypes.display(p)
        item = {"name": p["name"], "label": p.get("display_name") or p["name"],
                "data_type": p.get("data_type") or "string", "format": shown["format"],
                "unit": shown["unit"], "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 "",
                "stored_here": stored_here(p), "value_type": p.get("value_type") or "",
                "track": bool(p.get("track")),
                "error": plan["errors"].get(p["name"], ""),
                "ref": {"type_id": r["other"]["id"], "type_name": r["other"]["name"]} if r else None}
        if p.get("lifecycle"):
            item["lifecycle"] = p["lifecycle"]
        out.append(item)
    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"]
    if is_interface(ot):
        inner = f"SELECT t.* FROM {ref['from']} AS t"
        plan = {"refs": {}}
    else:
        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


def _iface_plan(ot: dict, ref: dict) -> dict:
    """接口的「读取方案」:属性就是合并后的列。"""
    cols = ref.get("columns") or {}

    def out_sql(name: str) -> str:
        if name in cols:
            return f"q.{ident(cols[name])}"
        if name in ("key", "__key"):
            return f"q.{ident('__key')}"
        for p in (ot.get("spec") or {}).get("properties") or []:
            if name == p.get("display_name"):
                return f"q.{ident(p['name'])}"
        raise rules.RuleError(f"没有属性「{name}」")
    return {"refs": {}, "errors": {}, "exprs": {}, "col_sql": out_sql}


def read_plan(ot: dict, ref: dict) -> dict:
    return _iface_plan(ot, ref) if is_interface(ot) else _plan(ot, ref)


_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 and is_interface(ot) and ":" not in str(key):
        impl, k = concrete(ot["id"], key)
        items, _ = _fetch(ot, [f"q.{ident(ref['key_column'])} = {lit(impl['id'] + ':' + k)}"])
    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 read_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, set)) else [v.strip() for v in str(value).replace(",", ",").split(",")
                                                                    if v.strip()]
        if not vals:
            return "1 = 0" if op == "in" else "1 = 1"     # 属于一个空集合:谁都不是
        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, where: Any = None, keys: list[str] | None = None) -> dict:
    """按属性筛选 / 排序 / 分页地查一类对象:对象表格、流程卡「查数据」、对象集、提问的对象快车道都走这里。

    filters: [{property, op, value}],条件之间是「并且」;where:条件组(见 cond_sql);keys:只要这些主键;
    sort: [{property, dir: asc|desc}]。返回 {items, total, limit, offset, fields};total 是满足条件的总数。
    """
    ot = object_type(type_ref)
    ref = table_binding(ot)["ref"]
    plan = read_plan(ot, ref)
    conds: 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                                   # 没填值的条件当作没写
        conds.append(_filter_sql(_prop_sql(ot, ref, f.get("property"), plan), op, f.get("value")))
    w = cond_sql(ot, ref, plan, where)
    if w:
        conds.append(f"({w})")
    if keys is not None:
        conds.append(_filter_sql(f"q.{ident(ref['key_column'])}", "in", list(keys)))
    if q:
        conds.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, 5000))), int(max(0, offset))
    items, total = _fetch(ot, conds, ", ".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 = binding(ot)
    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(ObjectIndex).where(
                    ObjectIndex.workspace == workspace, ObjectIndex.gone == 0)).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


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


# ---------------- 变化:订阅与记录 ----------------
_change_listeners: list[Callable[[list[dict]], None]] = []


def on_change(fn: Callable[[list[dict]], None]) -> None:
    """订阅对象变化(动作写入、同步对比出来的都算):[{type_id, key, property, old, new, source, ref}]。"""
    _change_listeners.append(fn)


def record_changes(changes: list[dict]) -> None:
    """记进变化记录,并通知订阅者。订阅者出错不影响写入本身。"""
    if not changes:
        return
    ws = identity.current().workspace
    with session() as s:
        for c in changes:
            s.add(ObjectChange(workspace=ws, type_id=c["type_id"], obj_key=str(c["key"])[:255],
                               property=str(c.get("property") or "")[:128], old_json=jdump(c.get("old")),
                               new_json=jdump(c.get("new")), source=c.get("source") or "action",
                               ref=str(c.get("ref") or "")[:64], at=c.get("at") or now()))
        s.commit()
    for fn in _change_listeners:
        try:
            fn(changes)
        except Exception:  # noqa: BLE001
            log.exception("对象变化的订阅者处理失败")


def history(type_id: str, key: str, limit: int = 200) -> list[dict]:
    """一个对象的变化时间线(新的在前)。"""
    with session() as s:
        rows = s.scalars(select(ObjectChange).where(
            ObjectChange.workspace == identity.current().workspace, ObjectChange.type_id == type_id,
            ObjectChange.obj_key == str(key)).order_by(ObjectChange.id.desc()).limit(limit)).all()
        return [{"property": r.property, "old": jload(r.old_json, None), "new": jload(r.new_json, None),
                 "source": r.source, "ref": r.ref, "at": iso(r.at)} for r in rows]


# ---------------- 写入:一组操作,同一个数据源一个事务 ----------------
WRITE_OPS = {"create": "新建", "update": "修改", "create_rows": "按行新建", "delete": "删除",
             "link": "建立关系", "unlink": "解除关系", "transition": "状态流转"}
_OPS_REF = re.compile(r"\$ops\.([A-Za-z_一-鿿][\w.一-鿿]*)")

# 正在执行的动作:状态流转要核对「这条流转是不是由这个动作完成」
_acting: contextvars.ContextVar[dict | None] = contextvars.ContextVar("onto_acting", default=None)


@contextlib.contextmanager
def acting(action: dict):
    tok = _acting.set({"id": action.get("id") or "", "name": action.get("name") or "",
                       "display_name": action.get("display_name") or ""})
    try:
        yield
    finally:
        _acting.reset(tok)


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"]
        v = values[k]
        if p.get("expression"):
            raise HTTPException(422, f"「{name}」是算出来的,不能直接写")
        lc = p.get("lifecycle")
        if lc:
            if not creating:
                raise HTTPException(422, f"「{name}」由状态机管着,只能经由动作的状态流转改变(写入类型选「状态流转」)")
            if v not in (None, "") and not valuetypes._is_ref(v) and v != lc["initial"]:
                raise HTTPException(422, f"新建的{ot['name']}「{name}」只能是初始状态「{lc['initial']}」")
        elif not creating and not p.get("is_writable"):
            raise HTTPException(422, f"「{ot['name']}」的「{name}」没有开放修改(在对象的属性里勾上「可修改」)")
        enum = p.get("enum_values") or []
        if enum and v not in (None, "") and not valuetypes._is_ref(v) and v not in enum:
            raise HTTPException(422, f"「{name}」只能取 {'/'.join(enum)}")
        why = valuetypes.check(p, v)
        if why:
            raise HTTPException(422, why)
        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 _is_pending(v: Any) -> bool:
    return isinstance(v, str) and "$ops." in v


def _link_info(link_ref: str) -> dict:
    """关系 → 写入要用的信息:{lt, from, to, via?, join, ds_id, from_ref, to_ref}。"""
    lt = service.rt_find(link_ref, "link_type")
    if lt is None:
        raise HTTPException(404, f"找不到已发布的关系「{link_ref}」")
    jb = service.rt_binding(lt, "join")
    if jb is None:
        raise HTTPException(422, f"关系「{lt['name']}」还没有绑定关联列")
    spec = lt.get("spec") or {}
    f, t = object_type(spec.get("from_type") or ""), object_type(spec.get("to_type") or "")
    fb, tb = table_binding(f), table_binding(t)
    return {"lt": lt, "from": f, "to": t, "join": jb["ref"], "ds_id": int(jb["ds_id"] or fb["ds_id"]),
            "from_ref": fb["ref"], "to_ref": tb["ref"], "card": spec.get("cardinality") or "n:1",
            "via": bool(jb["ref"].get("via_table"))}


def _transition_ok(ot: dict, p: dict, current: Any, target: Any) -> str:
    """状态流转校验:返回不能流转的原因,空串表示可以。"""
    lc = p.get("lifecycle") or {}
    name = p.get("display_name") or p["name"]
    if target not in [s["value"] for s in lc.get("states") or []]:
        return f"「{name}」没有「{target}」这个状态"
    hits = [t for t in lc.get("transitions") or [] if t["to"] == target and str(current) in t["from"]]
    if not hits:
        return f"{ot['name']}的「{name}」不能从「{current}」流转到「{target}」"
    acting_now = _acting.get()
    named = [t for t in hits if t.get("action")]
    if named and len(named) == len(hits):
        names = {acting_now.get(k) for k in ("id", "name", "display_name")} if acting_now else set()
        if not any(t["action"] in names for t in named):
            return f"「{name}」从「{current}」到「{target}」要由动作「{named[0]['action']}」完成"
    return ""


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:
        kind = op["op"]
        if kind in ("link", "unlink"):
            info = _link_info(str(op.get("link") or ""))
            ds_ids.add(info["ds_id"])
            changes.append({"kind": kind, "object_type": info["lt"]["name"], "type_id": info["lt"]["id"],
                            "key": f"{op.get('from_key')} → {op.get('to_key')}", "object": "",
                            "as": str(op.get("as") or ""), "row": 0, "property": WRITE_OPS[kind],
                            "from": None, "to": op.get("values") or "", "format": "", "unit": ""})
            continue
        ot = object_type(str(op.get("object_type") or ""))
        if is_interface(ot) and kind != "create" and not _is_pending(op.get("key")):
            ot, _ = concrete(ot["id"], op.get("key"))
        if is_interface(ot):
            raise HTTPException(422, f"「{ot['name']}」是接口,新建要选具体是哪一类对象")
        b = table_binding(ot)
        ref = b["ref"]
        if not ref.get("writable"):
            raise HTTPException(422, f"「{ot['name']}」的数据来源({sources.describe(ref['raw'])})是只读的,不能写入")
        ds_ids.add(int(b["ds_id"]))
        if kind in ("update", "delete", "transition") and op.get("key") in (None, ""):
            raise HTTPException(422, f"{WRITE_OPS[kind]}「{ot['name']}」要指定是哪一个(主键)")
        if kind == "delete":
            changes.append({"kind": kind, "object_type": ot["name"], "type_id": ot["id"], "key": str(op.get("key")),
                            "object": str(op.get("key")), "as": str(op.get("as") or ""), "row": 0,
                            "property": "(整条)", "from": None, "to": None, "format": "", "unit": ""})
            continue
        if kind == "transition":
            p = _prop(ot, str(op.get("property") or ""))
            if p is None or not p.get("lifecycle"):
                raise HTTPException(422, f"「{ot['name']}」没有叫「{op.get('property')}」的状态机属性")
            prev = None
            if not _is_pending(op.get("key")):
                prev = current_value(ot["id"], str(op["key"]), p["name"])
                why = _transition_ok(ot, p, prev, op.get("to"))
                if why:
                    raise HTTPException(422, why)
            changes.append({"kind": kind, "object_type": ot["name"], "type_id": ot["id"], "key": str(op["key"]),
                            "object": str(op["key"]), "as": str(op.get("as") or ""), "row": 0,
                            "property": p.get("display_name") or p["name"], "from": prev, "to": op.get("to"),
                            "format": "status", "unit": ""})
            continue
        values = op.get("values") or {}
        if not isinstance(values, dict) or not values:
            if kind != "create":
                raise HTTPException(422, f"写入「{ot['name']}」还没填要写的字段")
            values = {}
        pmap = _check_values(ot, values, kind == "create")
        for k, v in values.items():
            p = pmap.get(k) or {}
            prev = None
            if kind == "update" and not _is_pending(op.get("key")):
                prev = current_value(ot["id"], str(op["key"]), p.get("name") or k)
            shown = valuetypes.display(p) if p.get("name") else {"format": "", "unit": ""}
            changes.append({"kind": kind, "object_type": ot["name"], "type_id": ot["id"],
                            "key": "" if kind == "create" else str(op.get("key")),
                            "object": "" if kind == "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 _is_pending(v) else v,
                            "format": shown["format"], "unit": shown["unit"]})
    if len(ds_ids) > 1:
        raise HTTPException(422, "一次写入只能写同一个数据源里的表(跨库无法放进一个事务);请拆成两个写数据步骤")
    ds_id = ds_ids.pop()
    wb = _writeback(ds_id)
    if wb:
        # 写回业务库:每个要写的属性都得对上一列(只在本系统里有的属性写不进业务表)
        for op in flat:
            if op["op"] not in ("create", "update"):
                continue
            ot = object_type(op["object_type"])
            if is_interface(ot):
                ot, _ = concrete(ot["id"], op.get("key"))
            ref = table_binding(ot)["ref"]
            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")}
            here = {p["name"] for p in (ot.get("spec") or {}).get("properties") or [] if stored_here(p)}
            for k in (op.get("values") or {}):
                prop = byname.get(k, k)
                if prop in here or prop == key_prop:
                    continue                      # 本体自有属性:存在本系统里,不进业务表
                if sources.write_column(ref, prop) is None and k not in (ref.get("columns") or {}).values():
                    raise HTTPException(422, f"「{ot['name']}」的「{k}」没有对应可写的列,写不进业务库"
                                             "(在对象的数据来源里把它绑定到主表的一列)")
    needs_db = [op["op"] for op in flat if op["op"] in ("create", "delete", "link", "unlink")]
    if not wb and needs_db:
        raise HTTPException(422, f"要{WRITE_OPS[needs_db[0]]}数据,数据源必须开启「允许写回业务库」(在数据连接里编辑数据源,打开这个开关)")
    return {"ds_id": ds_id, "writeback": wb, "changes": changes}


def _row_of(ref: dict, ds_id: int, key: str) -> dict | None:
    """主表里这一行的原始数据(删除前存下来,撤销时原样插回去)。"""
    try:
        cols, rows = _run(ds_id, f"SELECT * FROM {ident(ref['table'])} WHERE {ident(ref['key_column'])} = {lit(key)}")
    except HTTPException:
        return None
    return dict(zip(cols, rows[0])) if rows else None


def _via_rows(info: dict, conn: Any, fv: Any = None, tv: Any = None) -> list[dict]:
    from sqlalchemy import text as sa_text
    j = info["join"]
    conds, args = [], {}
    if fv is not None:
        conds.append(f"{ident(j['via_from'])} = :fv")
        args["fv"] = fv
    if tv is not None:
        conds.append(f"{ident(j['via_to'])} = :tv")
        args["tv"] = tv
    sql = f"SELECT * FROM {ident(j['via_table'])}" + (" WHERE " + " AND ".join(conds) if conds else "")
    return [dict(r._mapping) for r in conn.execute(sa_text(sql), args)]


def _side_value(ot: dict, ref: dict, col: str, key: str) -> Any:
    """关系一端用来对上的值:关联列是主键就是主键本身,否则读这个对象那一列的值。"""
    if not col or col == ref["key_column"]:
        return key
    obj = get(ot["id"], key)
    return _raw_value(ot, obj, col)


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

    ops: [{op: create|update|create_rows|delete|transition|link|unlink, object_type, as?, key?, values?, rows?,
           property?/to?(transition), link/from_key/to_key(link / unlink)}]
    值里可以引用前面操作的结果:`$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:
            kind = op["op"]
            if kind in ("link", "unlink"):
                _run_link(op, conn, ctx, pending, connector)
                continue
            ot = object_type(op["object_type"])
            key_in = _resolve_ops(op.get("key"), ctx) if op.get("key") not in (None, "") else None
            if is_interface(ot) and kind != "create":
                ot, key_in = concrete(ot["id"], key_in)
            ref = table_binding(ot)["ref"]
            spec = ot.get("spec") or {}
            name = str(op.get("as") or "")
            if kind == "delete":
                key = str(key_in)
                if conn is None:
                    raise HTTPException(422, "删除数据要求数据源开启写回")
                row = _row_of(ref, plan["ds_id"], key)
                if row is None:
                    raise HTTPException(404, f"{ot['name']}「{key}」在业务库里不存在,删不了")
                connector.delete_row(ref["table"], ref["key_column"], key, conn=conn)
                pending.append({"type_id": ot["id"], "key": key, "property": "*", "value": None, "prev": row,
                                "mode": "delete", "label": f"删除{ot['name']}「{key}」"})
                if name:
                    ctx[name] = {"key": key}
                    created[name] = key
                continue
            if kind == "transition":
                key = str(key_in)
                p = _prop(ot, str(op.get("property") or ""))
                prev = current_value(ot["id"], key, p["name"])
                why = _transition_ok(ot, p, prev, op.get("to"))
                if why:
                    raise HTTPException(422, why)
                values = {p["name"]: op.get("to")}
                here = stored_here(p)
                if conn is not None and not here:
                    col = sources.write_column(ref, p["name"])
                    n = connector.write_row(ref["table"], {col: op.get("to")}, ref["key_column"], key, conn=conn)
                    if not n and not _exists(ot, key):
                        raise HTTPException(404, f"{ot['name']}「{key}」在业务库里不存在,未写入")
                pending.append({"type_id": ot["id"], "key": key, "property": p["name"], "value": op.get("to"),
                                "prev": prev, "mode": "db" if conn is not None and not here else "overlay",
                                "label": f"{ot['name']}「{key}」的{p.get('display_name') or p['name']}:"
                                         f"{_brief(prev)} → {_brief(op.get('to'))}"})
                if name:
                    ctx[name] = {"key": key, **values}
                    created[name] = key
                continue
            values = _resolve_ops(op.get("values") or {}, ctx)
            pmap = _check_values(ot, values, kind == "create")
            if kind == "create":
                for p in spec.get("properties") or []:      # 状态机属性没给值:取初始状态
                    if p.get("lifecycle") and p["name"] not in values and not any(
                            (pmap.get(k) or {}).get("name") == p["name"] for k in values):
                        values[p["name"]] = p["lifecycle"]["initial"]
                        pmap[p["name"]] = p
                row, mine = {}, {}
                for k, v in values.items():
                    if v is None:
                        continue
                    prop = pmap[k].get("name", k)
                    if stored_here(pmap[k]):
                        mine[prop] = v
                        continue
                    col = (ref.get("columns") or {}).get(prop) or (ref["key_column"] if prop == spec.get("key_property")
                                                                  else prop)
                    row[col] = v
                if (ref.get("raw") or {}).get("kind") == "managed":
                    if ref["key_column"] not in row:
                        row[ref["key_column"]] = new_id("mo")
                    row["_created_at"] = row["_updated_at"] = now()
                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}」"})
                for prop, v in mine.items():
                    pending.append({"type_id": ot["id"], "key": key, "property": prop, "value": v, "prev": None,
                                    "mode": "overlay", "label": f"{ot['name']}「{key}」的{prop_label(ot, prop)}:{_brief(v)}"})
                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(key_in)
            changed = {}
            for k, v in values.items():
                prop = pmap[k]["name"]
                prev = current_value(ot["id"], key, prop)
                here = stored_here(pmap[k])
                if not here:
                    changed[prop] = v
                pending.append({"type_id": ot["id"], "key": key, "property": prop, "value": v, "prev": prev,
                                "mode": "db" if conn is not None and not here else "overlay",
                                "label": f"{ot['name']}「{key}」的{pmap[k].get('display_name') or prop}:"
                                         f"{_brief(prev)} → {_brief(v)}"})
            if conn is not None and changed:
                row = {sources.write_column(ref, p) or p: v for p, v in changed.items()}
                if (ref.get("raw") or {}).get("kind") == "managed":
                    row["_updated_at"] = now()
                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, **{pmap[k]["name"]: v for k, v in values.items() if stored_here(pmap[k])}}
                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({"create": "object.create", "delete": "object.delete", "link": "object.link",
                      "unlink": "object.unlink"}.get(p["mode"], "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"]})
    record_changes(_as_changes(pending, action_run_id))
    _touch_index(pending)
    return {"created": created, "edit_ids": ids, "changes": plan["changes"], "summary": summary}


def _as_changes(pending: list[dict], ref: str, source: str = "action") -> list[dict]:
    out = []
    for p in pending:
        prop = p["property"]
        if p["mode"] == "create":
            out.append({"type_id": p["type_id"], "key": p["key"], "property": "*", "old": None,
                        "new": "created", "source": source, "ref": ref})
        elif p["mode"] == "delete":
            out.append({"type_id": p["type_id"], "key": p["key"], "property": "*", "old": "existed",
                        "new": "removed", "source": source, "ref": ref})
        else:
            out.append({"type_id": p["type_id"], "key": p["key"], "property": prop, "old": p["prev"],
                        "new": p["value"], "source": source, "ref": ref})
    return out


def _touch_index(pending: list[dict]) -> None:
    """动作写完立刻把索引里的这几个对象改成新值:下一次同步就不会把同一个变化再记一遍。"""
    from . import pipeline
    try:
        pipeline.touch([p for p in pending if p["mode"] in ("db", "overlay", "create", "delete")])
    except Exception:  # noqa: BLE001  索引只是加速,跟不上就等下一次同步
        log.debug("更新对象索引失败", exc_info=True)


def _run_link(op: dict, conn: Any, ctx: dict, pending: list[dict], connector: Any) -> None:
    """建立 / 解除关系。中间表关系:插入 / 删除中间表的行(带关系属性);外键关系:改 from 对象的外键列。"""
    if conn is None:
        raise HTTPException(422, "建立 / 解除关系要求数据源开启写回")
    info = _link_info(str(op.get("link") or ""))
    lt, j = info["lt"], info["join"]
    fk_, tk_ = str(_resolve_ops(op.get("from_key"), ctx) or ""), str(_resolve_ops(op.get("to_key"), ctx) or "")
    if not fk_ or not tk_:
        raise HTTPException(422, f"关系「{lt['name']}」两端的对象都要指定")
    label = f"「{lt['name']}」{info['from']['name']}「{fk_}」→ {info['to']['name']}「{tk_}」"
    if info["via"]:
        fv = _side_value(info["from"], info["from_ref"], j.get("from_column") or "", fk_)
        tv = _side_value(info["to"], info["to_ref"], j.get("to_column") or "", tk_)
        if op["op"] == "link":
            if _via_rows(info, conn, fv, tv):
                return                                   # 已经有这条关系了
            card = info["card"]
            if card in ("n:1", "1:1") and _via_rows(info, conn, fv=fv):
                raise HTTPException(422, f"{label}:每个{info['from']['name']}只能有一个{info['to']['name']}(关系基数 {card})")
            if card in ("1:n", "1:1") and _via_rows(info, conn, tv=tv):
                raise HTTPException(422, f"{label}:每个{info['to']['name']}只能属于一个{info['from']['name']}(关系基数 {card})")
            row = {j["via_from"]: fv, j["via_to"]: tv}
            for prop, col in (j.get("props") or {}).items():
                v = (op.get("values") or {}).get(prop)
                if v is not None:
                    row[col] = _resolve_ops(v, ctx)
            connector.insert_row(j["via_table"], row, "", conn=conn)
            pending.append({"type_id": lt["id"], "key": f"{fk_}→{tk_}", "property": "@link", "value": row,
                            "prev": None, "mode": "link", "label": "建立关系" + label})
        else:
            rows = _via_rows(info, conn, fv, tv)
            if not rows:
                return
            from sqlalchemy import column, delete, table as sa_table
            t = sa_table(j["via_table"], column(j["via_from"]), column(j["via_to"]))
            conn.execute(delete(t).where(t.c[j["via_from"]] == fv, t.c[j["via_to"]] == tv))
            pending.append({"type_id": lt["id"], "key": f"{fk_}→{tk_}", "property": "@link", "value": None,
                            "prev": [{k: jsonable(v) for k, v in r.items()} for r in rows], "mode": "unlink",
                            "label": "解除关系" + label})
        return
    # 外键关系:外键在哪一头,就改哪一头
    ref_f, ref_t = info["from_ref"], info["to_ref"]
    if j["to_column"] == ref_t["key_column"]:
        holder, hold_key, col, target = info["from"], fk_, j["from_column"], tk_
        hold_ref = ref_f
    elif j["from_column"] == ref_f["key_column"]:
        holder, hold_key, col, target = info["to"], tk_, j["to_column"], fk_
        hold_ref = ref_t
    else:
        raise HTTPException(422, f"关系「{lt['name']}」两头都不是主键,不能直接建立或解除")
    prev = _raw_value(holder, get(holder["id"], hold_key), col)
    value = target if op["op"] == "link" else None
    connector.write_row(hold_ref["table"], {col: value}, hold_ref["key_column"], hold_key, conn=conn)
    pending.append({"type_id": lt["id"], "key": f"{fk_}→{tk_}", "property": "@fk",
                    "value": {"type_id": holder["id"], "key": hold_key, "column": col, "value": value},
                    "prev": {"type_id": holder["id"], "key": hold_key, "column": col, "value": prev},
                    "mode": op["op"], "label": ("建立关系" if op["op"] == "link" else "解除关系") + label})


def _brief(v: Any) -> str:
    if v is None or v == "":
        return "空"
    if isinstance(v, float) and v.is_integer():
        return str(int(v))
    if isinstance(v, dict):
        return "、".join(f"{k}={_brief(x)}" for k, x in list(v.items())[:4])
    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),
                 jload(e.value_json, None)) for e in rows if e is not None and e.active]
    by_ds: dict[int, list] = {}
    for x in info:
        mode, type_id = x[1], x[2]
        if mode in ("db", "create", "delete"):
            by_ds.setdefault(int(table_binding(object_type(type_id))["ds_id"]), []).append(x)
        elif mode in ("link", "unlink"):
            lt = service.rt_get(type_id) or {}
            jb = service.rt_binding(lt, "join") if lt else None
            by_ds.setdefault(int((jb or {}).get("ds_id") or 0), []).append(x)
    changes: list[dict] = []
    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, value in reversed(items):
                if mode in ("link", "unlink"):
                    _revert_link(conn_obj, conn, type_id, prop, mode, prev, value)
                    continue
                ref = table_binding(object_type(type_id))["ref"]
                if mode == "create":
                    conn_obj.delete_row(ref["table"], ref["key_column"], key, conn=conn)
                    changes.append({"type_id": type_id, "key": key, "property": "*", "old": "created",
                                    "new": "removed", "source": "revert"})
                elif mode == "delete":
                    conn_obj.insert_row(ref["table"], dict(prev or {}), ref["key_column"], conn=conn)
                    changes.append({"type_id": type_id, "key": key, "property": "*", "old": "removed",
                                    "new": "created", "source": "revert"})
                else:
                    col = sources.write_column(ref, prop) or prop
                    conn_obj.write_row(ref["table"], {col: prev}, ref["key_column"], key, conn=conn)
                    changes.append({"type_id": type_id, "key": key, "property": prop, "old": value, "new": prev,
                                    "source": "revert"})
    for _, mode, type_id, key, prop, prev, value in info:
        if mode == "overlay":
            changes.append({"type_id": type_id, "key": key, "property": prop, "old": value, "new": prev,
                            "source": "revert"})
    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)
    record_changes(changes)
    return out


def _revert_link(conn_obj: Any, conn: Any, link_id: str, prop: str, mode: str, prev: Any, value: Any) -> None:
    lt = service.rt_get(link_id) or {}
    jb = service.rt_binding(lt, "join") if lt else None
    if not jb:
        return
    j = jb["ref"]
    if prop == "@fk":
        rec = prev or {}
        ref = table_binding(object_type(rec["type_id"]))["ref"]
        conn_obj.write_row(ref["table"], {rec["column"]: rec.get("value")}, ref["key_column"], rec["key"], conn=conn)
        return
    from sqlalchemy import column, delete, table as sa_table
    if mode == "link" and isinstance(value, dict):
        t = sa_table(j["via_table"], column(j["via_from"]), column(j["via_to"]))
        conn.execute(delete(t).where(t.c[j["via_from"]] == value.get(j["via_from"]),
                                     t.c[j["via_to"]] == value.get(j["via_to"])))
    elif mode == "unlink":
        for row in prev or []:
            conn_obj.insert_row(j["via_table"], row, "", conn=conn)


# ---------------- 关联对象 ----------------
def link_sides(ot: dict) -> list[dict]:
    """这类对象能沿哪些关系走到别的对象:[{link, link_id, direction, other, my_col, other_col, single, via?}]。
    single:对方那头的关联列是对方的主键(一对一 / 多对一),走过去只会有一个。
    via:中间表关系 {table, mine, other, props, ds_id},走过去先经中间表。"""
    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"), "out"))
        if _same(spec.get("to_type"), ot):
            sides.append((spec.get("from_type"), "in"))
        for other_ref, direction in sides:
            other = service.rt_find(other_ref, "object_type") if other_ref else None
            ob = binding(other) if other else None
            mb = binding(ot)
            if not ob or not mb:
                continue
            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"])))
            if j.get("via_table"):
                mine_col = (j.get("from_column") if direction == "out" else j.get("to_column")) or mb["ref"]["key_column"]
                other_col = (j.get("to_column") if direction == "out" else j.get("from_column")) or ob["ref"]["key_column"]
                via = {"table": j["via_table"], "ds_id": int(jb["ds_id"] or mb["ds_id"]),
                       "mine": j["via_from"] if direction == "out" else j["via_to"],
                       "other": j["via_to"] if direction == "out" else j["via_from"], "props": j.get("props") or {}}
                out.append({"link": lt["name"], "link_id": lt["id"], "direction": direction, "other": other,
                            "my_col": mine_col, "other_col": other_col, "label": label, "single": False, "via": via})
                continue
            my_col, other_col = (j["from_column"], j["to_column"]) if direction == "out" else (j["to_column"], j["from_column"])
            out.append({"link": lt["name"], "link_id": lt["id"], "direction": direction, "other": other,
                        "my_col": my_col, "other_col": other_col, "label": label,
                        "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 _via_pairs(side: dict, values: list[Any]) -> list[tuple[str, str, dict]]:
    """中间表里这些值连着谁:[(我这头的值, 对方那头的值, 关系属性)]。"""
    v = side["via"]
    if not values:
        return []
    cols = [v["mine"], v["other"], *v["props"].values()]
    sql = (f"SELECT {', '.join(ident(c) for c in dict.fromkeys(cols))} FROM {ident(v['table'])} "
           f"WHERE {ident(v['mine'])} IN ({', '.join(lit(x) for x in values)})")
    names, rows = _run(v["ds_id"], sql)
    out = []
    for r in rows:
        d = dict(zip(names, r))
        out.append((str(d.get(v["mine"])), str(d.get(v["other"])),
                    {p: d.get(c) for p, c in v["props"].items()}))
    return out


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:
            if side.get("via"):
                pairs = _via_pairs(side, [val])
                props_of = {o: p for _, o, p in pairs}
                vals = list(props_of)
                items, total = (_fetch(other, [_filter_sql(f"q.{ident(side['other_col'])}", "in", vals)],
                                       limit=int(limit), count=True) if vals else ([], 0))
                for o in items:
                    lp = props_of.get(str(_raw_value(other, o, side["other_col"])))
                    if lp:
                        o["link_props"] = lp
            else:
                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"))
    for k, v in (o.get("link_props") or {}).items():
        out.setdefault(k, v)
    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 父对象的关联值),再递归下一层。
    中间表关系多一条 SQL:先查中间表里父对象连着谁(带关系属性)。"""
    side = _find_side(ot, str(inc.get("link") or ""))
    other = side["other"]
    oref = table_binding(other)["ref"]
    oplan = read_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]] = {}
    pairs: list[tuple[str, str, dict]] = []
    if side.get("via") and vals:
        pairs = _via_pairs(side, vals)
        targets = list(dict.fromkeys(o for _, o, _ in pairs))
    else:
        targets = vals
    if targets and budget[0] > 0:
        where = [_filter_sql(f"q.{ident(side['other_col'])}", "in", targets)]
        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]
        if side.get("via"):
            by_other = {str(_raw_value(other, o, side["other_col"])): o for o in items}
            for mine, oth, lp in pairs:
                o = by_other.get(oth)
                if o is not None:
                    child_raw.setdefault(mine, []).append({**o, "link_props": lp} if lp else o)
        else:
            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", keys: list[str] | None = None) -> 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: [...下一层]}]
    keys:只要这些主键(对象集算出来的一批)。mode=one:只要第一条,返回 {item, found};list:返回 {items, total}。"""
    ot = object_type(object_type_ref)
    ref = table_binding(ot)["ref"]
    plan = read_plan(ot, ref)
    w = cond_sql(ot, ref, plan, where)
    conds = [w] if w else []
    if keys is not None:
        conds.append(_filter_sql(f"q.{ident(ref['key_column'])}", "in", list(keys)))
    one = mode == "one"
    n = 1 if one else max(1, min(int(limit or 50), 500))
    items, total = _fetch(ot, conds, _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 "")}