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 /// 验证器列表
48 ///
49 /// 用于验证字段值的验证器,按顺序执行
50 pub validators: Vec<Validator>,
51
52 /// 字段权限
53 ///
54 /// 定义不同角色对该字段的访问权限
55 pub permissions: FieldPermissions,
56
57 /// 是否从通用记录输出和表 JSON Schema 中隐藏。
58 pub(crate) hidden: bool,
59
60 /// 是否可搜索
61 ///
62 /// 如果为 true,则该字段可以参与关键词搜索(OR LIKE);与结构化筛选
63 /// 的 `filterable` 位相互独立,默认 fail-closed。
64 pub searchable: bool,
65
66 /// 是否可筛选
67 ///
68 /// 如果为 true,则该字段可以用于 WHERE 条件筛选
69 pub filterable: bool,
70
71 /// 是否可排序
72 ///
73 /// 如果为 true,则该字段可以用于 ORDER BY 排序
74 pub sortable: bool,
75
76 /// 是否为租户隔离键。
77 pub tenant_key: bool,
78
79 /// 关联表配置
80 ///
81 /// 用于外键字段,定义与其他表的关联关系
82 pub relation: Option<RelationConfig>,
83}
84
85impl FieldConfig {
86 /// 创建新的字段配置
87 ///
88 /// # 参数
89 ///
90 /// - `name`: 字段名称
91 /// - `field_type`: 字段类型
92 ///
93 /// # 返回值
94 ///
95 /// 返回一个新的 FieldConfig 实例,使用默认配置
96 ///
97 pub(crate) fn new(name: impl Into<String>, field_type: FieldType) -> Self {
98 Self {
99 name: name.into(),
100 display_name: String::new(),
101 field_type,
102 required: false,
103 default_value: None,
104 auto_increment: false,
105 renamed_from: None,
106 validators: Vec::new(),
107 permissions: FieldPermissions::default(),
108 hidden: false,
109 searchable: false,
110 filterable: true,
111 sortable: true,
112 tenant_key: false,
113 relation: None,
114 }
115 }
116
117 /// 验证字段值
118 ///
119 /// 执行完整的字段验证流程:
120 /// 1. 检查必填约束
121 /// 2. 执行字段类型验证
122 /// 3. 依次执行所有配置的验证器
123 ///
124 /// # 参数
125 ///
126 /// - `value`: 要验证的值
127 /// - `cache`: 共享正则缓存(Email/Phone/Regex 验证器复用预编译结果)
128 ///
129 /// # 返回值
130 ///
131 /// 如果验证通过返回 Ok(()),否则返回相应的错误
132 ///
133 /// # 错误
134 ///
135 /// - `BaseError::FieldRequired`: 字段为必填但值为 null
136 /// - `BaseError::InvalidFieldType`: 字段类型验证失败
137 /// - `BaseError::ValidationFailed`: 验证器验证失败
138 ///
139 pub(crate) fn validate(
140 &self,
141 value: &serde_json::Value,
142 cache: &RegexCache,
143 ) -> Result<(), BaseError> {
144 // 1. 检查必填约束
145 if self.required && value.is_null() {
146 return Err(BaseError::FieldRequired(self.name.clone()));
147 }
148
149 // 如果值为 null 且字段非必填,跳过后续验证
150 if value.is_null() {
151 return Ok(());
152 }
153
154 // 2. 执行字段类型验证
155 self.field_type.validate(&self.name, value)?;
156
157 // 3. 依次执行所有配置的验证器
158 for validator in &self.validators {
159 validator.validate_with(&self.name, value, cache)?;
160 }
161
162 Ok(())
163 }
164}
165
166/// 字段操作的访问范围。
167///
168/// 使用显式的 `Everyone` / `Nobody`,避免旧版“空角色集合等于公开”导致无法表达
169/// 禁止访问的歧义。
170#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(tag = "kind", content = "roles", rename_all = "snake_case")]
172pub(crate) enum Audience {
173 /// 所有调用方都可以访问。
174 #[default]
175 Everyone,
176 /// 所有调用方都不可以访问。
177 Nobody,
178 /// 至少拥有其中一个角色时可以访问。
179 Roles(HashSet<String>),
180}
181
182impl Audience {
183 /// 创建角色受限的访问范围。
184 pub(crate) fn roles<I, S>(roles: I) -> Self
185 where
186 I: IntoIterator<Item = S>,
187 S: Into<String>,
188 {
189 Self::Roles(roles.into_iter().map(Into::into).collect())
190 }
191
192 /// 判断给定角色集合是否满足访问范围。
193 pub(crate) fn allows(&self, user_roles: &HashSet<String>) -> bool {
194 match self {
195 Self::Everyone => true,
196 Self::Nobody => false,
197 Self::Roles(roles) => user_roles.iter().any(|role| roles.contains(role)),
198 }
199 }
200}
201
202/// 字段权限配置。
203///
204/// 四类操作分别使用明确访问范围;默认全部公开。
205#[derive(Debug, Clone, Default, Serialize, Deserialize)]
206pub(crate) struct FieldPermissions {
207 /// 读取权限。
208 pub readable: Audience,
209 /// 写入权限。
210 pub writable: Audience,
211 /// 筛选权限。
212 pub filterable: Audience,
213 /// 排序权限。
214 pub sortable: Audience,
215}
216
217impl FieldPermissions {
218 /// 检查用户是否有读取权限
219 ///
220 /// # 参数
221 ///
222 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
223 ///
224 /// # 返回值
225 ///
226 /// 如果用户有读取权限返回 true,否则返回 false
227 ///
228 pub(crate) fn can_read(&self, user_roles: &HashSet<String>) -> bool {
229 self.readable.allows(user_roles)
230 }
231
232 /// 检查用户是否有写入权限
233 ///
234 /// # 参数
235 ///
236 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
237 ///
238 /// # 返回值
239 ///
240 /// 如果用户有写入权限返回 true,否则返回 false
241 ///
242 #[cfg(any(feature = "mysql", test))]
243 pub(crate) fn can_write(&self, user_roles: &HashSet<String>) -> bool {
244 self.writable.allows(user_roles)
245 }
246
247 /// 检查用户是否有筛选权限
248 ///
249 /// # 参数
250 ///
251 /// - `user_roles`: 用户的角色列表
252 ///
253 /// # 返回值
254 ///
255 /// 如果用户有筛选权限返回 true,否则返回 false
256 ///
257 pub(crate) fn can_filter(&self, user_roles: &HashSet<String>) -> bool {
258 self.filterable.allows(user_roles)
259 }
260
261 /// 检查用户是否有排序权限
262 ///
263 /// # 参数
264 ///
265 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
266 ///
267 /// # 返回值
268 ///
269 /// 如果用户有排序权限返回 true,否则返回 false
270 ///
271 pub(crate) fn can_sort(&self, user_roles: &HashSet<String>) -> bool {
272 self.sortable.allows(user_roles)
273 }
274}
275
276/// 关联表配置
277///
278/// 定义字段与其他表的关联关系,用于外键字段。
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub(crate) struct RelationConfig {
281 /// 关联的目标表名
282 pub table: String,
283
284 /// 关联的目标字段名
285 pub field: String,
286
287 /// 显示字段列表
288 ///
289 /// 当查询关联数据时,需要返回的字段列表
290 pub display_fields: Vec<String>,
291
292 /// 关联类型
293 pub relation_type: RelationType,
294}
295
296/// 关联类型
297///
298/// 定义表之间的关联关系类型
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
300pub enum RelationType {
301 /// 一对一关联
302 ///
303 /// 一条记录对应另一个表的一条记录
304 OneToOne,
305
306 /// 一对多关联
307 ///
308 /// 一条记录对应另一个表的多条记录
309 OneToMany,
310
311 /// 多对一关联
312 ///
313 /// 多条当前表记录关联目标表的一条记录,常用于普通外键列
314 ManyToOne,
315
316 /// 多对多关联
317 ///
318 /// 多条记录对应另一个表的多条记录,通常需要中间表
319 ManyToMany,
320}