yang_base/table/field_config.rs
1//! 编译后的字段配置
2//!
3//! 应用侧通过 [`super::Field`] 声明字段;本模块只保存构建完成后的执行期表示。
4
5use crate::error::BaseError;
6use crate::table::{FieldType, RegexCache, Validator};
7use serde::{Deserialize, Serialize};
8use std::collections::HashSet;
9
10/// Schema-first DSL 构建后的内部字段配置。
11#[derive(Debug, Clone)]
12#[non_exhaustive]
13pub(crate) struct FieldConfig {
14 /// 字段名
15 ///
16 /// 数据库中的字段名称,通常使用蛇形命名法(snake_case)
17 pub name: String,
18
19 /// 显示名称
20 ///
21 /// 用于前端展示的字段名称,通常使用中文
22 pub display_name: String,
23
24 /// 字段类型
25 ///
26 /// 定义字段的数据类型,如字符串、整数、枚举等
27 pub field_type: FieldType,
28
29 /// 是否必填
30 ///
31 /// 如果为 true,则字段值不能为 null
32 pub required: bool,
33
34 /// 默认值
35 ///
36 /// 当插入数据时未提供该字段值时使用的默认值
37 pub default_value: Option<serde_json::Value>,
38
39 /// 是否由数据库自动生成递增值。
40 ///
41 /// 仅允许用于整数类型的主键字段;schema 同步器会在启动期校验该约束。
42 pub auto_increment: bool,
43
44 /// 显式声明该字段由哪个旧列原位改名而来。
45 pub renamed_from: Option<String>,
46
47 /// 生成列表达式(PostgreSQL `GENERATED ALWAYS AS (<expr>) STORED`)。
48 ///
49 /// 生成列由数据库计算,声明后不可写入;schema 同步只创建列,不自动改写表达式。
50 pub generated: Option<String>,
51
52 /// 列注释;PostgreSQL 通过 `COMMENT ON COLUMN` 同步。
53 pub comment: Option<String>,
54
55 /// 列排序规则(PostgreSQL `COLLATE`);MySQL 不支持字段级 collation。
56 pub collation: Option<String>,
57
58 /// PostgreSQL 原生枚举类型名(`CREATE TYPE ... AS ENUM`);仅枚举字段可声明。
59 ///
60 /// 未声明时 PostgreSQL 使用 `VARCHAR + CHECK` 存储枚举;声明后复用既有
61 /// 原生枚举类型,适配已使用 PG enum 的存量表。MySQL 方言明确拒绝。
62 pub native_enum: Option<String>,
63
64 /// 验证器列表
65 ///
66 /// 用于验证字段值的验证器,按顺序执行
67 pub validators: Vec<Validator>,
68
69 /// 字段权限
70 ///
71 /// 定义不同角色对该字段的访问权限
72 pub permissions: FieldPermissions,
73
74 /// 是否从通用记录输出和表 JSON Schema 中隐藏。
75 pub(crate) hidden: bool,
76
77 /// 是否可搜索
78 ///
79 /// 如果为 true,则该字段可以参与关键词搜索(OR LIKE);与结构化筛选
80 /// 的 `filterable` 位相互独立,默认 fail-closed。
81 pub searchable: bool,
82
83 /// 是否可筛选
84 ///
85 /// 如果为 true,则该字段可以用于 WHERE 条件筛选
86 pub filterable: bool,
87
88 /// 是否可排序
89 ///
90 /// 如果为 true,则该字段可以用于 ORDER BY 排序
91 pub sortable: bool,
92
93 /// 是否为租户隔离键。
94 pub tenant_key: bool,
95
96 /// 关联表配置
97 ///
98 /// 用于外键字段,定义与其他表的关联关系
99 pub relation: Option<RelationConfig>,
100}
101
102impl FieldConfig {
103 /// 创建新的字段配置
104 ///
105 /// # 参数
106 ///
107 /// - `name`: 字段名称
108 /// - `field_type`: 字段类型
109 ///
110 /// # 返回值
111 ///
112 /// 返回一个新的 FieldConfig 实例,使用默认配置
113 ///
114 pub(crate) fn new(name: impl Into<String>, field_type: FieldType) -> Self {
115 Self {
116 name: name.into(),
117 display_name: String::new(),
118 field_type,
119 required: false,
120 default_value: None,
121 auto_increment: false,
122 renamed_from: None,
123 generated: None,
124 comment: None,
125 collation: None,
126 native_enum: None,
127 validators: Vec::new(),
128 permissions: FieldPermissions::default(),
129 hidden: false,
130 searchable: false,
131 filterable: true,
132 sortable: true,
133 tenant_key: false,
134 relation: None,
135 }
136 }
137
138 /// 验证字段值
139 ///
140 /// 执行完整的字段验证流程:
141 /// 1. 检查必填约束
142 /// 2. 执行字段类型验证
143 /// 3. 依次执行所有配置的验证器
144 ///
145 /// # 参数
146 ///
147 /// - `value`: 要验证的值
148 /// - `cache`: 共享正则缓存(Email/Phone/Regex 验证器复用预编译结果)
149 ///
150 /// # 返回值
151 ///
152 /// 如果验证通过返回 Ok(()),否则返回相应的错误
153 ///
154 /// # 错误
155 ///
156 /// - `BaseError::FieldRequired`: 字段为必填但值为 null
157 /// - `BaseError::InvalidFieldType`: 字段类型验证失败
158 /// - `BaseError::ValidationFailed`: 验证器验证失败
159 ///
160 pub(crate) fn validate(
161 &self,
162 value: &serde_json::Value,
163 cache: &RegexCache,
164 ) -> Result<(), BaseError> {
165 // 1. 检查必填约束
166 if self.required && value.is_null() {
167 return Err(BaseError::FieldRequired(self.name.clone()));
168 }
169
170 // 如果值为 null 且字段非必填,跳过后续验证
171 if value.is_null() {
172 return Ok(());
173 }
174
175 // 2. 执行字段类型验证
176 self.field_type.validate(&self.name, value)?;
177
178 // 3. 依次执行所有配置的验证器
179 for validator in &self.validators {
180 validator.validate_with(&self.name, value, cache)?;
181 }
182
183 Ok(())
184 }
185}
186
187/// 字段操作的访问范围。
188///
189/// 使用显式的 `Everyone` / `Nobody`,避免旧版“空角色集合等于公开”导致无法表达
190/// 禁止访问的歧义。
191#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(tag = "kind", content = "roles", rename_all = "snake_case")]
193pub(crate) enum Audience {
194 /// 所有调用方都可以访问。
195 #[default]
196 Everyone,
197 /// 所有调用方都不可以访问。
198 Nobody,
199 /// 至少拥有其中一个角色时可以访问。
200 Roles(HashSet<String>),
201}
202
203impl Audience {
204 /// 创建角色受限的访问范围。
205 pub(crate) fn roles<I, S>(roles: I) -> Self
206 where
207 I: IntoIterator<Item = S>,
208 S: Into<String>,
209 {
210 Self::Roles(roles.into_iter().map(Into::into).collect())
211 }
212
213 /// 判断给定角色集合是否满足访问范围。
214 pub(crate) fn allows(&self, user_roles: &HashSet<String>) -> bool {
215 match self {
216 Self::Everyone => true,
217 Self::Nobody => false,
218 Self::Roles(roles) => user_roles.iter().any(|role| roles.contains(role)),
219 }
220 }
221}
222
223/// 字段权限配置。
224///
225/// 四类操作分别使用明确访问范围;默认全部公开。
226#[derive(Debug, Clone, Default, Serialize, Deserialize)]
227pub(crate) struct FieldPermissions {
228 /// 读取权限。
229 pub readable: Audience,
230 /// 写入权限。
231 pub writable: Audience,
232 /// 筛选权限。
233 pub filterable: Audience,
234 /// 排序权限。
235 pub sortable: Audience,
236}
237
238impl FieldPermissions {
239 /// 检查用户是否有读取权限
240 ///
241 /// # 参数
242 ///
243 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
244 ///
245 /// # 返回值
246 ///
247 /// 如果用户有读取权限返回 true,否则返回 false
248 ///
249 pub(crate) fn can_read(&self, user_roles: &HashSet<String>) -> bool {
250 self.readable.allows(user_roles)
251 }
252
253 /// 检查用户是否有写入权限
254 ///
255 /// # 参数
256 ///
257 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
258 ///
259 /// # 返回值
260 ///
261 /// 如果用户有写入权限返回 true,否则返回 false
262 ///
263 #[cfg(any(feature = "mysql", feature = "postgres", test))]
264 pub(crate) fn can_write(&self, user_roles: &HashSet<String>) -> bool {
265 self.writable.allows(user_roles)
266 }
267
268 /// 检查用户是否有筛选权限
269 ///
270 /// # 参数
271 ///
272 /// - `user_roles`: 用户的角色列表
273 ///
274 /// # 返回值
275 ///
276 /// 如果用户有筛选权限返回 true,否则返回 false
277 ///
278 pub(crate) fn can_filter(&self, user_roles: &HashSet<String>) -> bool {
279 self.filterable.allows(user_roles)
280 }
281
282 /// 检查用户是否有排序权限
283 ///
284 /// # 参数
285 ///
286 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
287 ///
288 /// # 返回值
289 ///
290 /// 如果用户有排序权限返回 true,否则返回 false
291 ///
292 pub(crate) fn can_sort(&self, user_roles: &HashSet<String>) -> bool {
293 self.sortable.allows(user_roles)
294 }
295}
296
297/// 关联表配置
298///
299/// 定义字段与其他表的关联关系,用于外键字段。
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub(crate) struct RelationConfig {
302 /// 关联的目标表名
303 pub table: String,
304
305 /// 关联的目标字段名
306 pub field: String,
307
308 /// 显示字段列表
309 ///
310 /// 当查询关联数据时,需要返回的字段列表
311 pub display_fields: Vec<String>,
312
313 /// 关联类型
314 pub relation_type: RelationType,
315}
316
317/// 关联类型
318///
319/// 定义表之间的关联关系类型
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
321pub enum RelationType {
322 /// 一对一关联
323 ///
324 /// 一条记录对应另一个表的一条记录
325 OneToOne,
326
327 /// 一对多关联
328 ///
329 /// 一条记录对应另一个表的多条记录
330 OneToMany,
331
332 /// 多对一关联
333 ///
334 /// 多条当前表记录关联目标表的一条记录,常用于普通外键列
335 ManyToOne,
336
337 /// 多对多关联
338 ///
339 /// 多条记录对应另一个表的多条记录,通常需要中间表
340 ManyToMany,
341}