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