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