yang_base/table/field_config.rs
1//! 编译后的字段配置
2//!
3//! 应用侧通过 [`super::Field`] 声明字段;本模块只保存构建完成后的执行期表示。
4
5use crate::error::BaseError;
6use crate::table::{FieldType, 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 ///
128 /// # 返回值
129 ///
130 /// 如果验证通过返回 Ok(()),否则返回相应的错误
131 ///
132 /// # 错误
133 ///
134 /// - `BaseError::FieldRequired`: 字段为必填但值为 null
135 /// - `BaseError::InvalidFieldType`: 字段类型验证失败
136 /// - `BaseError::ValidationFailed`: 验证器验证失败
137 ///
138 pub(crate) fn validate(&self, value: &serde_json::Value) -> Result<(), BaseError> {
139 // 1. 检查必填约束
140 if self.required && value.is_null() {
141 return Err(BaseError::FieldRequired(self.name.clone()));
142 }
143
144 // 如果值为 null 且字段非必填,跳过后续验证
145 if value.is_null() {
146 return Ok(());
147 }
148
149 // 2. 执行字段类型验证
150 self.field_type.validate(&self.name, value)?;
151
152 // 3. 依次执行所有配置的验证器
153 for validator in &self.validators {
154 validator.validate(&self.name, value)?;
155 }
156
157 Ok(())
158 }
159}
160
161/// 字段操作的访问范围。
162///
163/// 使用显式的 `Everyone` / `Nobody`,避免旧版“空角色集合等于公开”导致无法表达
164/// 禁止访问的歧义。
165#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(tag = "kind", content = "roles", rename_all = "snake_case")]
167pub(crate) enum Audience {
168 /// 所有调用方都可以访问。
169 #[default]
170 Everyone,
171 /// 所有调用方都不可以访问。
172 Nobody,
173 /// 至少拥有其中一个角色时可以访问。
174 Roles(HashSet<String>),
175}
176
177impl Audience {
178 /// 创建角色受限的访问范围。
179 pub(crate) fn roles<I, S>(roles: I) -> Self
180 where
181 I: IntoIterator<Item = S>,
182 S: Into<String>,
183 {
184 Self::Roles(roles.into_iter().map(Into::into).collect())
185 }
186
187 /// 判断给定角色集合是否满足访问范围。
188 pub(crate) fn allows(&self, user_roles: &HashSet<String>) -> bool {
189 match self {
190 Self::Everyone => true,
191 Self::Nobody => false,
192 Self::Roles(roles) => user_roles.iter().any(|role| roles.contains(role)),
193 }
194 }
195}
196
197/// 字段权限配置。
198///
199/// 四类操作分别使用明确访问范围;默认全部公开。
200#[derive(Debug, Clone, Default, Serialize, Deserialize)]
201pub(crate) struct FieldPermissions {
202 /// 读取权限。
203 pub readable: Audience,
204 /// 写入权限。
205 pub writable: Audience,
206 /// 筛选权限。
207 pub filterable: Audience,
208 /// 排序权限。
209 pub sortable: Audience,
210}
211
212impl FieldPermissions {
213 /// 检查用户是否有读取权限
214 ///
215 /// # 参数
216 ///
217 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
218 ///
219 /// # 返回值
220 ///
221 /// 如果用户有读取权限返回 true,否则返回 false
222 ///
223 pub(crate) fn can_read(&self, user_roles: &HashSet<String>) -> bool {
224 self.readable.allows(user_roles)
225 }
226
227 /// 检查用户是否有写入权限
228 ///
229 /// # 参数
230 ///
231 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
232 ///
233 /// # 返回值
234 ///
235 /// 如果用户有写入权限返回 true,否则返回 false
236 ///
237 #[cfg(any(feature = "mysql", test))]
238 pub(crate) fn can_write(&self, user_roles: &HashSet<String>) -> bool {
239 self.writable.allows(user_roles)
240 }
241
242 /// 检查用户是否有筛选权限
243 ///
244 /// # 参数
245 ///
246 /// - `user_roles`: 用户的角色列表
247 ///
248 /// # 返回值
249 ///
250 /// 如果用户有筛选权限返回 true,否则返回 false
251 ///
252 pub(crate) fn can_filter(&self, user_roles: &HashSet<String>) -> bool {
253 self.filterable.allows(user_roles)
254 }
255
256 /// 检查用户是否有排序权限
257 ///
258 /// # 参数
259 ///
260 /// - `user_roles`: 用户的角色集合(HashSet,支持 O(1) 查找)
261 ///
262 /// # 返回值
263 ///
264 /// 如果用户有排序权限返回 true,否则返回 false
265 ///
266 pub(crate) fn can_sort(&self, user_roles: &HashSet<String>) -> bool {
267 self.sortable.allows(user_roles)
268 }
269}
270
271/// 关联表配置
272///
273/// 定义字段与其他表的关联关系,用于外键字段。
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub(crate) struct RelationConfig {
276 /// 关联的目标表名
277 pub table: String,
278
279 /// 关联的目标字段名
280 pub field: String,
281
282 /// 显示字段列表
283 ///
284 /// 当查询关联数据时,需要返回的字段列表
285 pub display_fields: Vec<String>,
286
287 /// 关联类型
288 pub relation_type: RelationType,
289}
290
291/// 关联类型
292///
293/// 定义表之间的关联关系类型
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
295pub enum RelationType {
296 /// 一对一关联
297 ///
298 /// 一条记录对应另一个表的一条记录
299 OneToOne,
300
301 /// 一对多关联
302 ///
303 /// 一条记录对应另一个表的多条记录
304 OneToMany,
305
306 /// 多对一关联
307 ///
308 /// 多条当前表记录关联目标表的一条记录,常用于普通外键列
309 ManyToOne,
310
311 /// 多对多关联
312 ///
313 /// 多条记录对应另一个表的多条记录,通常需要中间表
314 ManyToMany,
315}