objects.py
10.6 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
"""对象实例:按 ObjectType 的数据绑定从业务库读(只读),叠加写回层。
业务库永远只读 —— Action 对对象的修改只写 `onto_object_edit`,读取时按属性覆盖。
所有 SQL 都经 text2sql.executor(同一套 guard + 行数上限 + 超时),不另开执行通道。
"""
from __future__ import annotations
import logging
from typing import Any
from fastapi import HTTPException
from sqlalchemy import delete, select
from ..core import identity
from ..core.dbx import iso, jdump, jload, session
from ..governance import audit
from . import service
from .models import InstanceCache, ObjectEdit
from .sqlutil import ident, jsonable, lit
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
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, sql, ds["ds_type"])
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 _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"{ident(col)} IN ({', '.join(lit(v) for v in vals)})")
return conds
def _to_obj(ot: dict, ref: dict, cols: list[str], row: list[Any]) -> 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()}
key = raw.get(ref["key_column"])
label = raw.get(ref.get("label_column") or "") if ref.get("label_column") else None
return {"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}
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 get(type_ref: str, key: str) -> dict:
ot = object_type(type_ref)
b = table_binding(ot)
ref = b["ref"]
where = [f"{ident(ref['key_column'])} = {lit(key)}"] + _scope_where(ot, ref)
cols, rows = _run(b["ds_id"], f"SELECT * FROM {ident(ref['table'])} WHERE "
+ " AND ".join(where) + " LIMIT 1")
if not rows:
raise HTTPException(404, f"{ot['name']}「{key}」不存在或不在你的数据范围内")
return _overlay(_to_obj(ot, ref, cols, rows[0]))
def search(type_ref: str, q: str = "", limit: int = 20, offset: int = 0) -> list[dict]:
ot = object_type(type_ref)
b = table_binding(ot)
ref = b["ref"]
where = _scope_where(ot, ref)
if q:
col = ref.get("label_column") or ref["key_column"]
like = q.replace("\\", "").replace("%", "").replace("_", "")
where.append(f"({ident(col)} LIKE {lit('%' + like + '%')} OR "
f"{ident(ref['key_column'])} = {lit(q)})")
sql = f"SELECT * FROM {ident(ref['table'])}"
if where:
sql += " WHERE " + " AND ".join(where)
sql += f" LIMIT {int(max(1, min(limit, 200)))} OFFSET {int(max(0, offset))}"
cols, rows = _run(b["ds_id"], sql)
return [_overlay(_to_obj(ot, ref, cols, r)) for r in rows]
def sync_instances(type_ref: str, limit: int = 5000) -> int:
"""把对象的 key/label 名录拉进本地,供问句里的实例链接使用。"""
ot = object_type(type_ref)
b = table_binding(ot)
ref = b["ref"]
label_col = ref.get("label_column") or ref["key_column"]
cols, rows = _run(b["ds_id"], f"SELECT {ident(ref['key_column'])}, {ident(label_col)} "
f"FROM {ident(ref['table'])} LIMIT {int(limit)}")
ws = identity.current().workspace
with session() as s:
s.execute(delete(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"]))
seen = set()
for k, lab in rows:
if k is None:
continue
label = str(lab if lab not in (None, "") else k)[:255]
if (str(k), label) in seen:
continue
seen.add((str(k), label))
s.add(InstanceCache(workspace=ws, concept_id=ot["id"], obj_key=str(k)[:255],
label=label))
s.commit()
from . import linker
linker.invalidate()
return len(seen)
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,
"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).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 write(type_ref: str, key: str, prop: str, value: Any, action_run_id: str = "") -> dict:
"""只能被 Tool `object.write` 调用(它又只能被审批过的 Action 调用)。"""
ot = object_type(type_ref)
props = {p["name"]: p for p in (ot.get("spec") or {}).get("properties") or []}
if prop not in props:
raise HTTPException(422, f"{ot['name']} 没有属性「{prop}」")
if not props[prop].get("is_writable"):
raise HTTPException(422, f"属性「{prop}」未开放写回(在本体里把它标为可写后才能被 Action 修改)")
enum = props[prop].get("enum_values") or []
if enum and value not in enum:
raise HTTPException(422, f"「{prop}」只能取 {'/'.join(enum)}")
prev = current_value(ot["id"], key, prop)
actor = identity.current()
with session() as s:
e = ObjectEdit(workspace=actor.workspace, object_type=ot["id"], object_key=str(key),
property=prop, value_json=jdump(value), prev_json=jdump(prev),
action_run_id=action_run_id, created_by=actor.id)
s.add(e)
s.commit()
out = _edit_dict(e)
audit.record("object.write", "object", f"{ot['id']}:{key}",
f"{ot['name']}「{key}」.{prop}:{prev!r} → {value!r}",
before={prop: prev}, after={prop: value})
return out
def revert_edit(edit_id: int) -> dict:
with session() as s:
e = s.get(ObjectEdit, edit_id)
if e is None:
raise HTTPException(404, "写回记录不存在")
e.active = 0
s.commit()
out = _edit_dict(e)
audit.record("object.revert", "object", f"{out['object_type']}:{out['object_key']}",
f"撤销写回 {out['property']}(恢复为 {out['prev']!r})", before=out)
return out
# ---------------- 关联对象 ----------------
def linked(type_ref: str, key: str, limit: int = 20) -> list[dict]:
ot = object_type(type_ref)
me = get(ot["id"], key)
raw_me = me["properties"]
my_ref = table_binding(ot)["ref"]
col2prop = {v: k for k, v in (my_ref.get("columns") or {}).items()}
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"]
if spec.get("from_type") == ot["id"]:
other_ref, my_col, other_col, direction = spec.get("to_type"), j["from_column"], j["to_column"], "out"
elif spec.get("to_type") == ot["id"]:
other_ref, my_col, other_col, direction = spec.get("from_type"), j["to_column"], j["from_column"], "in"
else:
continue
val = raw_me.get(col2prop.get(my_col, my_col))
if val is None or not other_ref:
continue
try:
other = object_type(other_ref)
ob = table_binding(other)
cols, rows = _run(ob["ds_id"], f"SELECT * FROM {ident(ob['ref']['table'])} WHERE "
+ " AND ".join([f"{ident(other_col)} = {lit(val)}"]
+ _scope_where(other, ob["ref"]))
+ f" LIMIT {int(limit)}")
except HTTPException as e:
log.debug("关联对象查询失败:%s", e.detail)
continue
out.append({"link_type": lt["name"], "link_id": lt["id"], "direction": direction,
"object_type": other["name"], "object_type_id": other["id"],
"items": [_to_obj(other, ob["ref"], cols, r) for r in rows]})
return out