schema.py
8.7 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
"""元模型:概念有哪些 kind、每种 kind 的 spec 长什么样、怎么校验。
这里是**唯一**定义「本体是什么」的地方,里面不能出现任何具体行业的词 ——
行业内容全部是数据(模板包 / 抽取提议 / 用户录入)。
"""
from __future__ import annotations
import re
from typing import Any
KINDS: dict[str, dict[str, str]] = {
"object_type": {"label": "对象类型", "desc": "业务里可被指认、有属性的实体类别,如客户、订单、网点"},
"link_type": {"label": "关系类型", "desc": "两个对象类型之间的关系,带方向与基数"},
"metric": {"label": "指标", "desc": "可量化的业务度量,绑定到数据后可直接取数"},
"dimension": {"label": "维度", "desc": "拆分指标的角度,如区域、品类"},
"rule": {"label": "规则", "desc": "口径、判定或计算规则,写成可求值表达式"},
"calendar": {"label": "日历/周期", "desc": "统计周期定义,如自然月、自定义起止日的业务月"},
"role": {"label": "角色", "desc": "岗位或职责主体,流程与审批按它派发"},
"process": {"label": "流程", "desc": "业务流程,可挂一份可执行 SOP"},
"term": {"label": "术语", "desc": "业务术语或别称,指向某个概念"},
}
DATA_TYPES = ("string", "number", "integer", "boolean", "date", "datetime", "enum", "text")
RULE_KINDS = ("judgement", "calibre", "calculation")
DIRECTIONS = ("higher_better", "lower_better", "neutral")
CARDINALITY = ("1:1", "1:n", "n:1", "n:n")
_IDENT = re.compile(r"^[A-Za-z_一-鿿][\w一-鿿$]*$")
class SpecError(ValueError):
pass
def _str(v: Any, default: str = "") -> str:
return str(v).strip() if v is not None else default
def _list_str(v: Any) -> list[str]:
if isinstance(v, str):
v = re.split(r"[,,、;\n]", v)
return [str(x).strip() for x in (v or []) if str(x).strip()]
def normalize_spec(kind: str, spec: dict | None) -> dict:
"""按 kind 规整 spec,缺的补默认值,错的抛 SpecError。"""
if kind not in KINDS:
raise SpecError(f"未知的概念类别:{kind}")
spec = dict(spec or {})
fn = _NORMALIZERS.get(kind)
return fn(spec) if fn else spec
def _object_type(spec: dict) -> dict:
props = []
seen = set()
for p in spec.get("properties") or []:
if not isinstance(p, dict):
continue
name = _str(p.get("name"))
if not name:
continue
if name in seen:
raise SpecError(f"属性重名:{name}")
seen.add(name)
dt = _str(p.get("data_type"), "string") or "string"
if dt not in DATA_TYPES:
dt = "string"
props.append({"name": name, "display_name": _str(p.get("display_name")),
"data_type": dt, "description": _str(p.get("description")),
"is_key": bool(p.get("is_key")), "is_time": bool(p.get("is_time")),
"is_writable": bool(p.get("is_writable")),
"enum_values": _list_str(p.get("enum_values"))})
keys = [p["name"] for p in props if p["is_key"]]
if len(keys) > 1:
raise SpecError("对象类型只能有一个主键属性")
label = _str(spec.get("label_property"))
if label and props and label not in seen:
raise SpecError(f"显示属性 {label} 不在属性列表中")
return {"properties": props, "key_property": keys[0] if keys else "",
"label_property": label}
def _link_type(spec: dict) -> dict:
card = _str(spec.get("cardinality"), "n:1") or "n:1"
if card not in CARDINALITY:
raise SpecError(f"基数只能是 {'/'.join(CARDINALITY)}")
return {"from_type": _str(spec.get("from_type")), "to_type": _str(spec.get("to_type")),
"cardinality": card, "inverse_name": _str(spec.get("inverse_name"))}
def _metric(spec: dict) -> dict:
direction = _str(spec.get("direction"), "neutral") or "neutral"
if direction not in DIRECTIONS:
direction = "neutral"
return {"object_type": _str(spec.get("object_type")), "unit": _str(spec.get("unit")),
"direction": direction, "calibre_rule": _str(spec.get("calibre_rule")),
"calendar": _str(spec.get("calendar")), "dimensions": _list_str(spec.get("dimensions")),
"formula_text": _str(spec.get("formula_text"))}
def _dimension(spec: dict) -> dict:
return {"object_type": _str(spec.get("object_type")), "property": _str(spec.get("property"))}
def _rule(spec: dict) -> dict:
from . import rules
kind = _str(spec.get("rule_kind"), "judgement") or "judgement"
if kind not in RULE_KINDS:
kind = "judgement"
expr = _str(spec.get("expression"))
params = _list_str(spec.get("params"))
if expr:
try:
names = rules.free_names(expr)
except rules.RuleError as e:
raise SpecError(f"规则表达式不合法:{e}") from e
# 表达式里用到但没声明的变量自动补进参数表,免得录入时来回改
for n in names:
if n not in params:
params.append(n)
return {"rule_kind": kind, "expression": expr, "params": params,
"text": _str(spec.get("text")), "examples": list(spec.get("examples") or [])}
def _calendar(spec: dict) -> dict:
def _day(v: Any, default: Any) -> Any:
if v in (None, ""):
return default
if str(v).lower() == "last":
return "last"
try:
d = int(v)
except (TypeError, ValueError) as e:
raise SpecError(f"日期必须是 1~31 或 last:{v}") from e
if not 1 <= d <= 31:
raise SpecError(f"日期必须是 1~31 或 last:{v}")
return d
def _off(v: Any) -> int:
try:
return int(v or 0)
except (TypeError, ValueError):
return 0
return {"start_day": _day(spec.get("start_day"), 1),
"start_month_offset": _off(spec.get("start_month_offset")),
"end_day": _day(spec.get("end_day"), "last"),
"end_month_offset": _off(spec.get("end_month_offset")),
"applies_when": _str(spec.get("applies_when")),
"text": _str(spec.get("text"))}
def _role(spec: dict) -> dict:
return {"responsibilities": _str(spec.get("responsibilities"))}
def _process(spec: dict) -> dict:
return {"sop_id": _str(spec.get("sop_id")), "roles": _list_str(spec.get("roles"))}
def _term(spec: dict) -> dict:
return {"refers_to": _str(spec.get("refers_to"))}
_NORMALIZERS = {
"object_type": _object_type, "link_type": _link_type, "metric": _metric,
"dimension": _dimension, "rule": _rule, "calendar": _calendar, "role": _role,
"process": _process, "term": _term,
}
# ---------------- 绑定 ----------------
BINDING_KINDS = {
"object_type": "table",
"metric": "metric_expr",
"link_type": "join",
}
def check_ident(name: str, what: str) -> str:
name = _str(name)
parts = name.split(".")
if not name or any(not _IDENT.match(p) for p in parts):
raise SpecError(f"{what}「{name}」不是合法的标识符")
return name
def normalize_binding(kind: str, ref: dict) -> dict:
ref = dict(ref or {})
if kind == "table":
cols = {str(k): check_ident(v, "列名") for k, v in (ref.get("columns") or {}).items() if v}
return {"table": check_ident(ref.get("table", ""), "表名"),
"key_column": check_ident(ref.get("key_column", ""), "主键列"),
"label_column": (check_ident(ref["label_column"], "显示列")
if ref.get("label_column") else ""),
"columns": cols}
if kind == "metric_expr":
dims = {str(k): check_ident(v, "维度列") for k, v in (ref.get("dimensions") or {}).items() if v}
expr = _str(ref.get("expression"))
if not expr:
raise SpecError("指标表达式不能为空")
if ";" in expr:
raise SpecError("指标表达式不能包含分号")
return {"base_table": check_ident(ref.get("base_table", ""), "基表"),
"expression": expr,
"time_column": (check_ident(ref["time_column"], "时间列")
if ref.get("time_column") else ""),
"object_key_column": (check_ident(ref["object_key_column"], "对象键列")
if ref.get("object_key_column") else ""),
"filters": [f for f in _list_str(ref.get("filters")) if ";" not in f],
"dimensions": dims}
if kind == "join":
return {"from_column": check_ident(ref.get("from_column", ""), "关联列"),
"to_column": check_ident(ref.get("to_column", ""), "关联列")}
raise SpecError(f"未知的绑定类型:{kind}")