rules.py 22.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
"""规则表达式:安全求值。

口径、判定、SOP 分支条件、Action 前置校验共用这一套。语法是 Python 表达式的子集:
算术、比较、and/or/not、条件表达式、`a.b` 取字段、`a[0]` 下标、白名单函数。
不支持赋值、lambda、推导式、任意属性/方法调用 —— 规则由业务人员录入、也可能由 AI 起草,
绝不能是一个能执行任意代码的口子。
"""
from __future__ import annotations

import ast
import datetime as dt
import math
import re
from typing import Any


class RuleError(ValueError):
    pass


def _to_date(v: Any) -> dt.date:
    if isinstance(v, dt.datetime):
        return v.date()
    if isinstance(v, dt.date):
        return v
    return dt.date.fromisoformat(str(v)[:10])


def _coalesce(*xs: Any) -> Any:
    for x in xs:
        if x is not None and x != "":
            return x
    return None


def _safe_div(a: Any, b: Any, default: Any = None) -> Any:
    try:
        return a / b if b else default
    except Exception:  # noqa: BLE001
        return default


def _rows(v: Any) -> list:
    """列表函数的入参:查数据的结果 {items}、取数结果 {columns, rows} 都当成「一行一个字典」的列表。"""
    if isinstance(v, dict) and isinstance(v.get("items"), list):
        return v["items"]
    if isinstance(v, dict) and isinstance(v.get("rows"), list):
        cols = [str(c) for c in v.get("columns") or []]
        return [r if isinstance(r, dict) else dict(zip(cols, r)) for r in v["rows"]]
    if isinstance(v, (list, tuple)):
        return list(v)
    return [] if v is None else [v]


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


_WHERE_OPS = {
    "==": lambda a, b: a == b, "eq": lambda a, b: a == b, "!=": lambda a, b: a != b, "ne": lambda a, b: a != b,
    ">": lambda a, b: a > b, "gt": lambda a, b: a > b, ">=": lambda a, b: a >= b, "ge": lambda a, b: a >= b,
    "<": lambda a, b: a < b, "lt": lambda a, b: a < b, "<=": lambda a, b: a <= b, "le": lambda a, b: a <= b,
    "in": lambda a, b: a in (b or []), "contains": lambda a, b: b in (a or ""),
    "empty": lambda a, b: a in (None, ""), "not_empty": lambda a, b: a not in (None, ""),
}


def _where(rows: Any, field: str, op: str = "==", value: Any = None) -> list:
    fn = _WHERE_OPS.get(str(op))
    if fn is None:
        raise RuleError(f"where 不认识比较方式 {op},可用:{'、'.join(_WHERE_OPS)}")
    out = []
    for r in _rows(rows):
        try:
            if fn(_num(_field(r, field)), _num(value)):
                out.append(r)
        except TypeError:
            continue
    return out


def _nums(rows: Any, field: Any = None) -> list:
    return [x for x in (_num(_field(r, field)) for r in _rows(rows)) if isinstance(x, (int, float))]


def _sort_by(rows: Any, field: str, desc: Any = False) -> list:
    items = _rows(rows)
    present = [r for r in items if _field(r, field) is not None]
    rest = [r for r in items if _field(r, field) is None]
    try:
        present.sort(key=lambda r: _num(_field(r, field)), reverse=bool(desc))
    except TypeError:
        present.sort(key=lambda r: str(_field(r, field)), reverse=bool(desc))
    return present + rest


def _group_sum(rows: Any, key: str, field: str) -> list:
    acc: dict[Any, float] = {}
    for r in _rows(rows):
        k = _field(r, key)
        v = _num(_field(r, field))
        acc[k] = acc.get(k, 0) + (v if isinstance(v, (int, float)) else 0)
    return [{"key": k, "value": v} for k, v in acc.items()]


def _pick(rows: Any, *fields: str) -> list:
    return [{f.split(".")[-1]: _field(r, f) for f in fields} for r in _rows(rows)]


def _merge(*objs: Any) -> dict:
    out: dict = {}
    for o in objs:
        if isinstance(o, dict):
            out.update(o)
    return out


# 列表函数:查数据 / 取数得到的多行数据,在「计算」节点、条件、动作公式里都能直接算
LIST_FUNCS: dict[str, Any] = {
    "count": lambda rows: len(_rows(rows)),
    "pluck": lambda rows, field: [_field(r, field) for r in _rows(rows)],
    "sum_by": lambda rows, field=None: sum(_nums(rows, field)),
    "avg_by": lambda rows, field=None: (sum(_nums(rows, field)) / len(_nums(rows, field))) if _nums(rows, field) else None,
    "max_by": lambda rows, field=None: max(_nums(rows, field), default=None),
    "min_by": lambda rows, field=None: min(_nums(rows, field), default=None),
    "where": _where,
    "first": lambda rows: (_rows(rows) or [None])[0],
    "last": lambda rows: (_rows(rows) or [None])[-1],
    "sort_by": _sort_by,
    "unique": lambda rows, field=None: list(dict.fromkeys(_field(r, field) for r in _rows(rows))),
    "group_sum": _group_sum,
    "pick": _pick,
    "merge": _merge,
    "join": lambda rows, sep=",": str(sep).join("" if x is None else str(x) for x in _rows(rows)),
    "any_of": lambda rows, field=None: any(bool(_field(r, field)) for r in _rows(rows)),
    "all_of": lambda rows, field=None: all(bool(_field(r, field)) for r in _rows(rows)),
}


def _kept(rows: Any, cond: Any) -> list:
    return [r for r in _rows(rows) if cond in (None, "") or bool(_field(r, cond))]


# 汇总「指向我的那些记录」:count_of(订单, 'is_overdue') = 我名下逾期的订单有几张。
# 第一个参数是关系名(或对方对象名),后面是对方的属性名(字符串);条件只能是对方一个是/否属性。
# 逐行求值时第一个参数是那几条记录的列表;对象的计算公式里编译成关联子查询。
ROLLUP_FUNCS: dict[str, Any] = {
    "count_of": lambda rows, cond=None: len(_kept(rows, cond)),
    "sum_of": lambda rows, field, cond=None: sum(_nums(_kept(rows, cond), field)),
    "avg_of": lambda rows, field, cond=None: (sum(_nums(_kept(rows, cond), field)) / len(_nums(_kept(rows, cond), field)))
    if _nums(_kept(rows, cond), field) else None,
    "max_of": lambda rows, field, cond=None: max(_nums(_kept(rows, cond), field), default=None),
    "min_of": lambda rows, field, cond=None: min(_nums(_kept(rows, cond), field), default=None),
}

FUNCS: dict[str, Any] = {
    **LIST_FUNCS,
    **ROLLUP_FUNCS,
    "min": min, "max": max, "abs": abs, "round": round, "len": len, "sum": sum,
    "int": int, "float": float, "str": str, "bool": bool,
    "floor": math.floor, "ceil": math.ceil, "ceiling": math.ceil,
    "coalesce": _coalesce, "safe_div": _safe_div,
    "today": lambda: dt.date.today().isoformat(),
    "date": lambda v: _to_date(v).isoformat(),
    "day": lambda v: _to_date(v).day,
    "month": lambda v: _to_date(v).month,
    "year": lambda v: _to_date(v).year,
    "days_between": lambda a, b: (_to_date(b) - _to_date(a)).days,
    "add_days": lambda a, n: (_to_date(a) + dt.timedelta(days=int(n))).isoformat(),
    "contains": lambda a, b: (b in a) if a is not None else False,
    "startswith": lambda a, b: str(a or "").startswith(str(b)),
    # 只在对象的计算公式里有意义(编译成 SQL 的窗口函数);逐行求值时没有「同组的其他行」
    "share": lambda *a: None, "total": lambda *a: None,
}

CONSTS = {"true": True, "false": False, "null": None, "True": True, "False": False, "None": None}

_BIN = {
    ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b, ast.Mult: lambda a, b: a * b,
    ast.Div: lambda a, b: a / b, ast.FloorDiv: lambda a, b: a // b,
    ast.Mod: lambda a, b: a % b, ast.Pow: lambda a, b: a ** b,
}
_CMP = {
    ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b, ast.Lt: lambda a, b: a < b,
    ast.LtE: lambda a, b: a <= b, ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b,
    ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b,
    ast.Is: lambda a, b: a is b, ast.IsNot: lambda a, b: a is not b,
}
_ALLOWED = (ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp,
            ast.Call, ast.Constant, ast.Name, ast.Load, ast.Attribute, ast.Subscript,
            ast.List, ast.Tuple, ast.Dict, ast.And, ast.Or, ast.Not, ast.USub, ast.UAdd,
            ast.Slice, *_BIN.keys(), *_CMP.keys())


_DOLLAR = re.compile(r"\$(?=[A-Za-z_一-鿿])")
# SQL 习惯写法 x like '%大%':意思明确,翻成 contains / startswith
_LIKE = re.compile(r"([A-Za-z_一-鿿][\w.一-鿿]*)\s+(not\s+)?like\s+(['\"])(%?)([^'\"%]*)(%?)\3", re.I)


def _like(m: re.Match) -> str:
    field, neg, head, body, tail = m.group(1), m.group(2), m.group(4), m.group(5), m.group(6)
    call = f"startswith({field}, '{body}')" if tail and not head else f"contains({field}, '{body}')"
    if not head and not tail:
        call = f"{field} == '{body}'"
    return f"(not {call})" if neg else call


def _prep(expr: str) -> str:
    # 业务人员(和 AI)常写中文标点、&& ||,动作里又惯用 $参数 引用变量、= 开头表示表达式。
    # 这些写法意思都明确,这里宽容一下,不让它们变成「语法错误」(null / true 由 CONSTS 兜住)
    s = (expr.replace("(", "(").replace(")", ")").replace(",", ",")
         .replace("≥", ">=").replace("≤", "<=").replace("≠", "!=")
         .replace("&&", " and ").replace("||", " or ").replace("\r", " ").replace("\n", " ").strip())
    s = _LIKE.sub(_like, s)
    return _DOLLAR.sub("", s.lstrip("=").strip())


def normalize_text(expr: str) -> str:
    """把宽容写法(like、中文标点、&&)改成规范写法,存进定义里给人看。"""
    return _prep(expr) if expr else expr


def parse(expr: str) -> ast.Expression:
    if not expr or not expr.strip():
        raise RuleError("表达式为空")
    if len(expr) > 2000:
        raise RuleError("表达式过长")
    try:
        tree = ast.parse(_prep(expr), mode="eval")
    except SyntaxError as e:
        raise RuleError(f"语法错误:{e.msg}") from e
    for node in ast.walk(tree):
        if not isinstance(node, _ALLOWED):
            raise RuleError(f"不允许的语法:{type(node).__name__}")
        if isinstance(node, ast.Call):
            if not isinstance(node.func, ast.Name) or node.func.id not in FUNCS:
                raise RuleError("只能调用白名单函数:" + "、".join(sorted(FUNCS)))
            if node.keywords:
                raise RuleError("函数不支持关键字参数")
        if isinstance(node, ast.Attribute) and node.attr.startswith("_"):
            raise RuleError("不允许访问下划线开头的字段")
    return tree


def free_names(expr: str) -> list[str]:
    """表达式里引用的顶层变量名(不含函数名与常量),按出现顺序去重。"""
    tree = parse(expr)
    out: list[str] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Name) and node.id not in FUNCS and node.id not in CONSTS:
            if node.id not in out:
                out.append(node.id)
    return out


def rollup_names(expr: str) -> list[str]:
    """表达式里汇总函数(count_of / sum_of …)的第一个参数:那是关系名或对方对象名,不是自己的属性。"""
    out: list[str] = []
    for node in ast.walk(parse(expr)):
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in ROLLUP_FUNCS \
                and node.args and isinstance(node.args[0], ast.Name) and node.args[0].id not in out:
            out.append(node.args[0].id)
    return out


def _get(obj: Any, key: Any) -> Any:
    if isinstance(obj, dict):
        return obj.get(key)
    if isinstance(obj, (list, tuple, str)) and isinstance(key, (int, slice)):
        try:
            return obj[key]
        except IndexError:
            return None
    return None


def _num(v: Any) -> Any:
    """数据库回来的数常是 Decimal / 字符串,比较前尽量转成数。"""
    if isinstance(v, bool) or v is None:
        return v
    if isinstance(v, (int, float)):
        return v
    try:
        from decimal import Decimal
        if isinstance(v, Decimal):
            return float(v)
    except Exception:  # noqa: BLE001
        pass
    if isinstance(v, str):
        s = v.strip().rstrip("%")
        try:
            return float(s) if "." in s or "e" in s.lower() else int(s)
        except ValueError:
            return v
    return v


def _ev(node: ast.AST, env: dict) -> Any:
    if isinstance(node, ast.Expression):
        return _ev(node.body, env)
    if isinstance(node, ast.Constant):
        return node.value
    if isinstance(node, ast.Name):
        if node.id in CONSTS:
            return CONSTS[node.id]
        if node.id not in env:
            raise RuleError(f"缺少变量:{node.id}")
        return env[node.id]
    if isinstance(node, ast.Attribute):
        return _get(_ev(node.value, env), node.attr)
    if isinstance(node, ast.Subscript):
        return _get(_ev(node.value, env), _ev(node.slice, env))
    if isinstance(node, ast.List):
        return [_ev(x, env) for x in node.elts]
    if isinstance(node, ast.Tuple):
        return tuple(_ev(x, env) for x in node.elts)
    if isinstance(node, ast.Dict):
        return {_ev(k, env): _ev(v, env) for k, v in zip(node.keys, node.values) if k is not None}
    if isinstance(node, ast.BoolOp):
        if isinstance(node.op, ast.And):
            val: Any = True
            for x in node.values:
                val = _ev(x, env)
                if not val:
                    return val
            return val
        val = False
        for x in node.values:
            val = _ev(x, env)
            if val:
                return val
        return val
    if isinstance(node, ast.UnaryOp):
        v = _ev(node.operand, env)
        if isinstance(node.op, ast.Not):
            return not v
        v = _num(v)
        return -v if isinstance(node.op, ast.USub) else +v
    if isinstance(node, ast.BinOp):
        ra, rb = _ev(node.left, env), _ev(node.right, env)
        if isinstance(node.op, ast.Add) and any(isinstance(x, str) and isinstance(_num(x), str) for x in (ra, rb)):
            return f"{'' if ra is None else ra}{'' if rb is None else rb}"     # 'PO' + 单号:拼字符串
        a, b = _num(ra), _num(rb)
        if isinstance(node.op, ast.Pow) and isinstance(b, (int, float)) and abs(b) > 100:
            raise RuleError("指数过大")
        try:
            return _BIN[type(node.op)](a, b)
        except ZeroDivisionError:
            return None
        except TypeError as e:
            raise RuleError(f"运算类型不匹配:{e}") from e
    if isinstance(node, ast.Compare):
        left = _num(_ev(node.left, env))
        for op, comp in zip(node.ops, node.comparators):
            right = _num(_ev(comp, env))
            try:
                ok = _CMP[type(op)](left, right)
            except TypeError:
                ok = False     # None 与数比较一律视为不成立,而不是让整个流程崩掉
            if not ok:
                return False
            left = right
        return True
    if isinstance(node, ast.IfExp):
        return _ev(node.body, env) if _ev(node.test, env) else _ev(node.orelse, env)
    if isinstance(node, ast.Call):
        fn = FUNCS[node.func.id]  # type: ignore[attr-defined]
        args = [_ev(a, env) for a in node.args]
        if node.func.id not in ("str", "len", "contains", "startswith", "coalesce", "date",  # type: ignore[attr-defined]
                                "day", "month", "year", "days_between", "today", "add_days", *LIST_FUNCS):
            args = [_num(a) for a in args]
        try:
            return fn(*args)
        except Exception as e:  # noqa: BLE001
            raise RuleError(f"函数 {node.func.id} 调用失败:{e}") from e  # type: ignore[attr-defined]
    raise RuleError(f"不支持的语法:{type(node).__name__}")


def evaluate(expr: str, env: dict | None = None) -> Any:
    return _ev(parse(expr), dict(env or {}))


# ---------------- 编译成 SQL(派生属性用)----------------
_SQL_BIN = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Mod: "%"}
_SQL_CMP = {ast.Eq: "=", ast.NotEq: "<>", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="}
_SQL_FN = {"max": "GREATEST", "min": "LEAST", "abs": "ABS", "round": "ROUND", "floor": "FLOOR",
           "ceil": "CEIL", "ceiling": "CEIL", "coalesce": "COALESCE", "year": "YEAR", "month": "MONTH", "day": "DAY",
           "date": "DATE"}


def to_sql(expr: str, name_sql, attr_sql, rollup_sql=None) -> str:
    """把表达式编译成一段 SQL(MySQL 写法)。

    name_sql(名字) → 这个变量对应的 SQL 片段;attr_sql(对象, 属性) → 关联对象属性的 SQL 片段;
    rollup_sql(函数, 关系或对象名, 字段, 条件属性) → 「指向我的那些记录」的汇总子查询(不给就不支持汇总)。
    几个回调遇到不认识的名字应抛 RuleError。只支持能确定性翻译的那部分语法:算术、比较、
    and / or / not、条件表达式和一部分函数;其余的直接报错,由调用方告诉用户哪里写不了。
    """
    def lit(v: Any) -> str:
        if v is None:
            return "NULL"
        if isinstance(v, bool):
            return "1" if v else "0"
        if isinstance(v, (int, float)):
            return repr(v)
        return "'" + str(v).replace("\\", "\\\\").replace("'", "''") + "'"

    def go(n: ast.AST) -> str:
        if isinstance(n, ast.Expression):
            return go(n.body)
        if isinstance(n, ast.Constant):
            return lit(n.value)
        if isinstance(n, ast.Name):
            if n.id in CONSTS:
                return lit(CONSTS[n.id])
            return name_sql(n.id)
        if isinstance(n, ast.Attribute):
            if not isinstance(n.value, ast.Name):
                raise RuleError("只能写「关联对象.属性」,不能连着点两层")
            return attr_sql(n.value.id, n.attr)
        if isinstance(n, ast.UnaryOp):
            v = go(n.operand)
            if isinstance(n.op, ast.Not):
                return f"(NOT {v})"
            return f"(-{v})" if isinstance(n.op, ast.USub) else v
        if isinstance(n, ast.BinOp):
            a, b = go(n.left), go(n.right)
            if isinstance(n.op, ast.Div):
                return f"({a} / NULLIF({b}, 0))"
            if isinstance(n.op, ast.FloorDiv):
                return f"FLOOR({a} / NULLIF({b}, 0))"
            if type(n.op) not in _SQL_BIN:
                raise RuleError("这种运算不能用在派生属性里")
            return f"({a} {_SQL_BIN[type(n.op)]} {b})"
        if isinstance(n, ast.BoolOp):
            op = " AND " if isinstance(n.op, ast.And) else " OR "
            return "(" + op.join(go(x) for x in n.values) + ")"
        if isinstance(n, ast.Compare):
            parts, left = [], n.left
            for op, comp in zip(n.ops, n.comparators):
                if isinstance(op, (ast.In, ast.NotIn)) and isinstance(comp, (ast.List, ast.Tuple)):
                    vals = ", ".join(go(x) for x in comp.elts) or "NULL"
                    parts.append(f"({go(left)} {'NOT IN' if isinstance(op, ast.NotIn) else 'IN'} ({vals}))")
                elif isinstance(comp, ast.Constant) and comp.value is None and isinstance(op, (ast.Eq, ast.Is)):
                    parts.append(f"({go(left)} IS NULL)")
                elif isinstance(comp, ast.Constant) and comp.value is None and isinstance(op, (ast.NotEq, ast.IsNot)):
                    parts.append(f"({go(left)} IS NOT NULL)")
                elif type(op) in _SQL_CMP:
                    parts.append(f"({go(left)} {_SQL_CMP[type(op)]} {go(comp)})")
                else:
                    raise RuleError("这种比较不能用在派生属性里")
                left = comp
            return parts[0] if len(parts) == 1 else "(" + " AND ".join(parts) + ")"
        if isinstance(n, ast.IfExp):
            return f"(CASE WHEN {go(n.test)} THEN {go(n.body)} ELSE {go(n.orelse)} END)"
        if isinstance(n, ast.Call):
            fn = n.func.id  # type: ignore[attr-defined]
            if fn in ROLLUP_FUNCS:
                if rollup_sql is None:
                    raise RuleError(f"函数 {fn} 只能用在对象的计算属性里")
                if not n.args or not isinstance(n.args[0], ast.Name):
                    raise RuleError(f"{fn} 的第一个参数要写关系名或对方对象名,如 {fn}(订单, ...)")
                rest = [a.value if isinstance(a, ast.Constant) else None for a in n.args[1:]]
                if any(not isinstance(x, str) for x in rest):
                    raise RuleError(f"{fn} 后面的参数要写对方的属性名(加引号),如 count_of(订单, 'is_overdue')")
                field = "" if fn == "count_of" else (rest[0] if rest else "")
                cond = (rest[0] if rest else "") if fn == "count_of" else (rest[1] if len(rest) > 1 else "")
                if fn != "count_of" and not field:
                    raise RuleError(f"{fn} 要写汇总哪个属性,如 {fn}(订单, 'amount')")
                return rollup_sql(fn, n.args[0].id, field, cond)
            args = [go(a) for a in n.args]
            if fn == "contains" and len(args) == 2:
                return f"(LOCATE({args[1]}, {args[0]}) > 0)"
            if fn == "startswith" and len(args) == 2:
                return f"({args[0]} LIKE CONCAT({args[1]}, '%'))"
            if fn == "safe_div":
                dflt = args[2] if len(args) > 2 else "NULL"
                return f"COALESCE({args[0]} / NULLIF({args[1]}, 0), {dflt})"
            if fn == "days_between":
                return f"DATEDIFF({args[1]}, {args[0]})"
            if fn == "today":
                return "CURDATE()"
            if fn == "add_days":
                return f"DATE_ADD({args[0]}, INTERVAL {args[1]} DAY)"
            if fn in ("int", "float"):
                return f"({args[0]} + 0)"
            if fn == "str":
                return f"CAST({args[0]} AS CHAR)"
            if fn in ("share", "total") and args:
                # 占比 / 合计:看的是同一组里所有行,如 share(数量, 品类) = 这一行的数量 ÷ 同一品类各行数量之和
                over = f"SUM({args[0]}) OVER ({'PARTITION BY ' + ', '.join(args[1:]) if args[1:] else ''})"
                return over if fn == "total" else f"({args[0]} / NULLIF({over}, 0))"
            if fn in _SQL_FN and args:
                return f"{_SQL_FN[fn]}({', '.join(args)})"
            raise RuleError(f"函数 {fn} 不能用在派生属性里")
        raise RuleError(f"派生属性不支持这种写法:{type(n).__name__}")

    return go(parse(expr))