objects.py 12.8 KB
"""对象实例:按 ObjectType 的数据绑定从业务库读,叠加写回层。

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

import logging
from typing import Any

from fastapi import HTTPException
from sqlalchemy import 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, to_dialect

log = logging.getLogger(__name__)


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


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


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"])
    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
    if label in (None, "") and not ref.get("label_column"):
        # 没有名称列:用关系键(xx_id)拼一个,比光秃秃的自增主键好认
        fks = [str(v) for c, v in raw.items() if c != ref["key_column"] and c.lower().endswith("_id") and v is not None]
        label = " · ".join(fks[:3]) or 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 _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 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 instances(workspace: str) -> list[dict]:
    with session() as s:
        return [{"concept_id": r.concept_id, "key": r.obj_key, "label": r.label}
                for r in s.scalars(select(InstanceCache).where(
                    InstanceCache.workspace == workspace)).all()]


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


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


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


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


def 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()
    b = table_binding(ot)
    mode = "overlay"
    if _writeback(b["ds_id"]):
        col = (b["ref"].get("columns") or {}).get(prop) or prop
        n = _connector(b["ds_id"]).write_row(b["ref"]["table"], {col: value}, b["ref"]["key_column"], key)
        if not n:
            raise HTTPException(404, f"{ot['name']}「{key}」在业务库里不存在,未写回")
        mode = "db"
    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, mode=mode)
        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 create(type_ref: str, values: dict[str, Any], action_run_id: str = "") -> dict:
    """在业务库新建一个对象(一行)。只能被 Tool `object.create` 调用,且数据源必须开了写回。"""
    ot = object_type(type_ref)
    b = table_binding(ot)
    ref = b["ref"]
    if not _writeback(b["ds_id"]):
        raise HTTPException(422, f"「{ot['name']}」所在的数据源没有开启「写回业务库」,不能新建对象"
                                 f"(在数据连接里编辑数据源,打开写回开关)")
    cols = ref.get("columns") or {}
    props = {p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
    unknown = [k for k in values if k not in props and k not in cols]
    if unknown:
        raise HTTPException(422, f"{ot['name']} 没有属性:{'、'.join(unknown)}")
    row = {cols.get(k, k): v for k, v in values.items() if v is not None}
    key = row.get(ref["key_column"])
    _connector(b["ds_id"]).write_row(ref["table"], row)
    actor = identity.current()
    with session() as s:
        e = ObjectEdit(workspace=actor.workspace, object_type=ot["id"], object_key=str(key or ""),
                       property="*", value_json=jdump(values), prev_json="null",
                       action_run_id=action_run_id, created_by=actor.id, mode="create")
        s.add(e)
        s.commit()
        out = _edit_dict(e)
    audit.record("object.create", "object", f"{ot['id']}:{key}", f"新建{ot['name']}「{key}」",
                 after=values)
    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, "写回记录不存在")
        if e.mode in ("db", "create") and e.active:
            b = table_binding(object_type(e.object_type))
            ref = b["ref"]
            conn = _connector(b["ds_id"])
            if e.mode == "create":
                conn.delete_row(ref["table"], ref["key_column"], e.object_key)
            else:
                col = (ref.get("columns") or {}).get(e.property) or e.property
                conn.write_row(ref["table"], {col: jload(e.prev_json, None)}, ref["key_column"], e.object_key)
        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