objectset.py
8.55 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
"""对象集:一批对象的定义 —— 函数的一个类别(category=object_set)。
{base: 对象类型 / 接口 / 另一个对象集,
where: 条件组 {mode: all|any, items: [{left: 属性, op, right}]}(right 可以写 $输入名),
around: [{link: 关系名或对方对象名, where: 条件组}] —— 沿关系走过去,结果变成对方的对象,
combine: [{op: union|intersect|subtract, set: 另一个对象集}] —— 和别的对象集并 / 交 / 差(要同一类对象),
sort: [{property, dir}], limit: 只要前几个(0 = 不限),
inputs: [{name, label, type}] —— 参数,条件里用 $名字 引用}
「低于下限的库存位」「近 7 天有未结单据的客户」「这些客户名下的逾期订单」都写成对象集,
预警规则看什么、动作批量对谁做、流程卡查哪些、指标统计哪一批、问数问哪些,都直接引用它 —— 只定义一次。
"""
from __future__ import annotations
import threading
from typing import Any
from fastapi import HTTPException
from . import service
MAX_KEYS = 5000
_OPS = ("union", "intersect", "subtract")
class SetError(ValueError):
pass
def _cond(v: Any, what: str) -> dict:
if v in (None, "", {}):
return {}
if not isinstance(v, dict) or not isinstance(v.get("items"), list):
raise SetError(f"{what}要写成条件组:{{mode: all|any, items: [{{left, op, right}}]}}")
return {"mode": "any" if v.get("mode") == "any" else "all", "items": v["items"]}
def normalize(spec: dict) -> dict:
from .signature import norm_inputs
base = str(spec.get("base") or "").strip()
if not base:
raise SetError("对象集要选从哪类对象(或哪个对象集)出发")
around = []
for i, a in enumerate(spec.get("around") or [], 1):
if not isinstance(a, dict) or not str(a.get("link") or "").strip():
raise SetError(f"第 {i} 步沿关系走要写关系名")
around.append({"link": str(a["link"]).strip(), "where": _cond(a.get("where"), f"第 {i} 步的条件")})
combine = []
for i, c in enumerate(spec.get("combine") or [], 1):
op = str((c or {}).get("op") or "")
if op not in _OPS or not str(c.get("set") or "").strip():
raise SetError(f"第 {i} 个集合运算要写 op(union / intersect / subtract)和另一个对象集")
combine.append({"op": op, "set": str(c["set"]).strip()})
sort = [{"property": str(s.get("property")), "dir": "desc" if str(s.get("dir")).lower() == "desc" else "asc"}
for s in spec.get("sort") or [] if isinstance(s, dict) and s.get("property")]
try:
limit = max(0, min(int(spec.get("limit") or 0), MAX_KEYS))
except (TypeError, ValueError) as e:
raise SetError("只要前几个要写数字") from e
return {"base": base, "where": _cond(spec.get("where"), "筛选条件"), "around": around, "combine": combine,
"sort": sort, "limit": limit, "inputs": norm_inputs(spec.get("inputs"), "string"),
"text": str(spec.get("text") or "").strip()}
def _render(cond: Any, inputs: dict) -> Any:
"""条件右边引用的参数($名字)换成真实的值;没给值的条件当作没写(objects.cond_sql 会跳过空值)。"""
if isinstance(cond, dict):
if "items" in cond:
return {**cond, "items": [_render(x, inputs) for x in cond.get("items") or []]}
r = cond.get("right")
if isinstance(r, str) and r.startswith("$"):
return {**cond, "right": inputs.get(r[1:].split(".")[0])}
return cond
return cond
_stack = threading.local()
def resolve(ref: str | dict) -> dict:
"""名称 / id → 对象集函数;也可以直接给一份 spec(试跑没发布的定义)。"""
if isinstance(ref, dict):
spec = ref.get("spec") if "spec" in ref else ref
return {"id": ref.get("id") or "", "name": ref.get("name") or "(试跑)", "spec": normalize(spec or {})}
c = service.rt_fn(ref, "object_set")
if c is None:
raise HTTPException(404, f"找不到已发布的对象集「{ref}」")
return c
def _keys_of(ot: dict, where: Any, keys: list[str] | None) -> tuple[list[str], list[dict]]:
from . import objects
r = objects.query(ot["id"], where=where, keys=keys, limit=MAX_KEYS)
return [o["key"] for o in r["items"]], r["items"]
def evaluate(ref: str | dict, inputs: dict | None = None) -> dict:
"""算出这批对象:{type_id, type_name, keys, total, truncated}。"""
from . import objects
fn = resolve(ref)
spec = fn.get("spec") or {}
inputs = dict(inputs or {})
for i in spec.get("inputs") or []:
if inputs.get(i["name"]) in (None, "") and i.get("default") not in (None, ""):
inputs[i["name"]] = i["default"]
stack = getattr(_stack, "ids", ())
if fn.get("id") and fn["id"] in stack:
raise HTTPException(422, f"对象集「{fn['name']}」绕了一圈引用到自己")
_stack.ids = stack + ((fn.get("id") or fn["name"]),)
try:
base = spec["base"]
sub = service.rt_fn(base, "object_set")
if sub is not None:
inner = evaluate(sub["id"], inputs)
ot = objects.object_type(inner["type_id"])
keys, items = _keys_of(ot, _render(spec.get("where"), inputs), inner["keys"])
else:
ot = objects.object_type(base)
keys, items = _keys_of(ot, _render(spec.get("where"), inputs), None)
for step in spec.get("around") or []:
side = objects._find_side(ot, step["link"])
mine = [v for v in (objects._raw_value(ot, o, side["my_col"]) for o in items) if v not in (None, "")]
if side.get("via"):
others = list(dict.fromkeys(o for _, o, _ in objects._via_pairs(side, list(dict.fromkeys(mine)))))
else:
others = list(dict.fromkeys(str(v) for v in mine))
nxt = side["other"]
oref = objects.table_binding(nxt)["ref"]
plan = objects.read_plan(nxt, oref)
where = [objects._filter_sql(f"q.{_q(side['other_col'])}", "in", others)]
extra = objects.cond_sql(nxt, oref, plan, _render(step.get("where"), inputs))
if extra:
where.append(f"({extra})")
found, _ = objects._fetch(nxt, where, limit=MAX_KEYS)
ot, items = nxt, found
keys = [o["key"] for o in found]
for c in spec.get("combine") or []:
other = evaluate(c["set"], inputs)
if other["type_id"] != ot["id"]:
raise HTTPException(422, f"对象集只能和同一类对象的对象集做集合运算(「{c['set']}」是{other['type_name']})")
theirs = set(other["keys"])
if c["op"] == "union":
keys = list(dict.fromkeys([*keys, *other["keys"]]))
elif c["op"] == "intersect":
keys = [k for k in keys if k in theirs]
else:
keys = [k for k in keys if k not in theirs]
if spec.get("sort") or spec.get("limit"):
r = objects.query(ot["id"], keys=keys, sort=spec.get("sort"), limit=spec.get("limit") or MAX_KEYS)
keys = [o["key"] for o in r["items"]]
finally:
_stack.ids = stack
return {"type_id": ot["id"], "type_name": ot["name"], "keys": keys, "total": len(keys),
"truncated": len(keys) >= MAX_KEYS, "set": fn.get("name") or ""}
def _q(col: str) -> str:
from .sqlutil import ident
return ident(col)
def items(ref: str | dict, inputs: dict | None = None, *, limit: int = 50, offset: int = 0,
sort: list[dict] | None = None, q: str = "") -> dict:
"""这批对象本身(分页),对象表格、问数、流程卡用。"""
from . import objects
r = evaluate(ref, inputs)
if not r["keys"]:
out = objects.query(r["type_id"], keys=[], limit=1)
return {**out, "total": 0, "items": [], "set": r["set"]}
out = objects.query(r["type_id"], keys=r["keys"], sort=sort, q=q, limit=limit, offset=offset)
return {**out, "set": r["set"], "truncated": r["truncated"]}
def sql_base(ref: str | dict, inputs: dict | None = None) -> tuple[int, str, dict]:
"""把对象集当成一张表来查(指标统计「哪一批」用):返回 (数据源, 子查询, 对象类型)。"""
from . import objects
r = evaluate(ref, inputs)
ot = objects.object_type(r["type_id"])
ds_id, sub = objects.source_sql(ot)
key = objects.table_binding(ot)["ref"]["key_column"]
cond = objects._filter_sql(f"s.{_q(key)}", "in", r["keys"])
return ds_id, f"(SELECT s.* FROM {sub} AS s WHERE {cond})", ot