Skip to main content

yang_base/table/
definition.rs

1//! Schema-first 数据表定义。
2//!
3//! [`Table`] 与 [`Field`] 是应用侧唯一需要使用的构建器。字段名、数据库类型、
4//! 验证、权限、索引和时间戳语义在同一处声明,最终由 [`Table::build`] 一次校验并
5//! 生成不可变 [`TableDefinition`]。
6
7use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{
9    CheckConfig, ForeignKeyConfig, IndexConfig, TableConfig, TimestampFields,
10};
11#[cfg(feature = "mysql")]
12use super::TableQuery;
13use super::{FieldType, SortOrder, Validator};
14use crate::error::BaseError;
15use serde_json::{json, Map, Value};
16use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19/// 创建数据库列名引用,用于表级排序和复合索引配置。
20pub fn col(name: impl Into<String>) -> ColumnName {
21    ColumnName(name.into())
22}
23
24/// 数据库列名引用。
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub struct ColumnName(String);
27
28impl ColumnName {
29    /// 创建升序规则。
30    pub fn asc(self) -> Order {
31        Order {
32            field: self.0,
33            direction: SortOrder::Asc,
34        }
35    }
36
37    /// 创建降序规则。
38    pub fn desc(self) -> Order {
39        Order {
40            field: self.0,
41            direction: SortOrder::Desc,
42        }
43    }
44
45    fn into_name(self) -> String {
46        self.0
47    }
48}
49
50impl From<&str> for ColumnName {
51    fn from(value: &str) -> Self {
52        Self(value.to_string())
53    }
54}
55
56impl From<String> for ColumnName {
57    fn from(value: String) -> Self {
58        Self(value)
59    }
60}
61
62/// 表的默认排序条目。
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Order {
65    field: String,
66    direction: SortOrder,
67}
68
69/// Schema-first 字段构建器。
70///
71/// 字段名和字段配置从构造函数开始就是一个整体,例如
72/// `Field::string("username", 64).required().unique()`。
73#[derive(Debug, Clone)]
74#[must_use = "字段定义必须传给 Table::fields"]
75pub struct Field {
76    config: FieldConfig,
77    primary_key: bool,
78    unique: bool,
79    unique_name: Option<String>,
80    index: bool,
81    index_name: Option<String>,
82    created_at: bool,
83    updated_at: bool,
84    deleted_at: bool,
85    soft_delete: bool,
86    relation_display_fields: Option<Vec<String>>,
87}
88
89impl Field {
90    fn new(name: impl Into<String>, field_type: FieldType) -> Self {
91        Self {
92            config: FieldConfig::new(name, field_type),
93            primary_key: false,
94            unique: false,
95            unique_name: None,
96            index: false,
97            index_name: None,
98            created_at: false,
99            updated_at: false,
100            deleted_at: false,
101            soft_delete: false,
102            relation_display_fields: None,
103        }
104    }
105
106    /// 声明当前字段由一个旧列原位改名而来;同步器不会复制或删除数据。
107    pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
108        self.config.renamed_from = Some(legacy_name.into());
109        self
110    }
111
112    /// 创建 64 位自增主键字段。
113    pub fn id(name: impl Into<String>) -> Self {
114        Self::new(name, FieldType::BigInt)
115            .required()
116            .primary_key()
117            .auto_increment()
118            .not_writable()
119    }
120
121    /// 创建定长上限字符串字段。
122    pub fn string(name: impl Into<String>, max_length: usize) -> Self {
123        Self::new(name, FieldType::String { max_length })
124    }
125
126    /// 创建 32 位整数字段。
127    pub fn integer(name: impl Into<String>) -> Self {
128        Self::new(name, FieldType::Integer)
129    }
130
131    /// 创建 64 位整数字段。
132    pub fn bigint(name: impl Into<String>) -> Self {
133        Self::new(name, FieldType::BigInt)
134    }
135
136    /// 创建 32 位浮点数字段。
137    pub fn float(name: impl Into<String>) -> Self {
138        Self::new(name, FieldType::Float)
139    }
140
141    /// 创建 64 位浮点数字段。
142    pub fn double(name: impl Into<String>) -> Self {
143        Self::new(name, FieldType::Double)
144    }
145
146    /// 创建定点小数字段。
147    pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
148        Self::new(name, FieldType::Decimal { precision, scale })
149    }
150
151    /// 创建布尔字段。
152    pub fn boolean(name: impl Into<String>) -> Self {
153        Self::new(name, FieldType::Boolean)
154    }
155
156    /// 创建日期字段。
157    pub fn date(name: impl Into<String>) -> Self {
158        Self::new(name, FieldType::Date)
159    }
160
161    /// 创建日期时间字段。
162    pub fn datetime(name: impl Into<String>) -> Self {
163        Self::new(name, FieldType::DateTime)
164    }
165
166    /// 创建 Unix 时间戳字段。
167    pub fn timestamp(name: impl Into<String>) -> Self {
168        Self::new(name, FieldType::Timestamp)
169    }
170
171    /// 创建 JSON 字段。
172    pub fn json(name: impl Into<String>) -> Self {
173        Self::new(name, FieldType::Json)
174    }
175
176    /// 创建长文本字段。
177    pub fn text(name: impl Into<String>) -> Self {
178        Self::new(name, FieldType::Text)
179    }
180
181    /// 创建枚举字段。
182    pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
183    where
184        I: IntoIterator<Item = S>,
185        S: Into<String>,
186    {
187        Self::new(
188            name,
189            FieldType::Enum {
190                values: values.into_iter().map(Into::into).collect(),
191            },
192        )
193    }
194
195    /// 创建自动写入的创建时间字段。
196    pub fn created_at(name: impl Into<String>) -> Self {
197        let mut field = Self::bigint(name).required().not_writable();
198        field.created_at = true;
199        field
200    }
201
202    /// 创建自动写入的更新时间字段。
203    pub fn updated_at(name: impl Into<String>) -> Self {
204        let mut field = Self::bigint(name).required().not_writable();
205        field.updated_at = true;
206        field
207    }
208
209    /// 创建软删除时间字段。
210    pub fn soft_delete(name: impl Into<String>) -> Self {
211        let mut field = Self::bigint(name).not_writable();
212        field.deleted_at = true;
213        field.soft_delete = true;
214        field
215    }
216
217    /// 设置展示名称。
218    pub fn label(mut self, label: impl Into<String>) -> Self {
219        self.config.display_name = label.into();
220        self
221    }
222
223    /// 设置为必填字段。
224    pub fn required(mut self) -> Self {
225        self.config.required = true;
226        self
227    }
228
229    /// 设置为可空字段。
230    pub fn nullable(mut self) -> Self {
231        self.config.required = false;
232        self
233    }
234
235    /// 设置数据库默认值。
236    pub fn default(mut self, value: impl Into<Value>) -> Self {
237        self.config.default_value = Some(value.into());
238        self
239    }
240
241    /// 设置数据库自增。
242    pub fn auto_increment(mut self) -> Self {
243        self.config.auto_increment = true;
244        self
245    }
246
247    /// 设置为主键。
248    pub fn primary_key(mut self) -> Self {
249        self.primary_key = true;
250        self
251    }
252
253    /// 添加单字段唯一索引。
254    pub fn unique(mut self) -> Self {
255        self.unique = true;
256        self
257    }
258
259    /// 添加指定名称的单字段唯一索引。
260    pub fn unique_named(mut self, name: impl Into<String>) -> Self {
261        self.unique = true;
262        self.unique_name = Some(name.into());
263        self
264    }
265
266    /// 添加单字段普通索引。
267    pub fn index(mut self) -> Self {
268        self.index = true;
269        self
270    }
271
272    /// 添加指定名称的单字段普通索引。
273    pub fn index_named(mut self, name: impl Into<String>) -> Self {
274        self.index = true;
275        self.index_name = Some(name.into());
276        self
277    }
278
279    /// 添加底层验证器。
280    pub fn validator(mut self, validator: Validator) -> Self {
281        self.config.validators.push(validator);
282        self
283    }
284
285    /// 设置字符串最小长度。
286    pub fn min_length(self, value: usize) -> Self {
287        self.validator(Validator::MinLength(value))
288    }
289
290    /// 设置字符串最大长度验证。
291    pub fn max_length(self, value: usize) -> Self {
292        self.validator(Validator::MaxLength(value))
293    }
294
295    /// 同时设置字符串最小、最大长度验证。
296    pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
297        self.min_length(*range.start()).max_length(*range.end())
298    }
299
300    /// 设置数值最小值验证。
301    pub fn min(self, value: f64) -> Self {
302        self.validator(Validator::Min(value))
303    }
304
305    /// 设置数值最大值验证。
306    pub fn max(self, value: f64) -> Self {
307        self.validator(Validator::Max(value))
308    }
309
310    /// 设置严格邮箱验证。
311    pub fn email(self) -> Self {
312        self.validator(Validator::Email)
313    }
314
315    /// 设置严格手机号验证。
316    pub fn phone(self) -> Self {
317        self.validator(Validator::Phone)
318    }
319
320    /// 设置 URL 验证。
321    pub fn url(self) -> Self {
322        self.validator(Validator::Url)
323    }
324
325    /// 设置正则表达式验证。
326    pub fn regex(self, pattern: impl Into<String>) -> Self {
327        self.validator(Validator::Regex(pattern.into()))
328    }
329
330    /// 允许所有角色读取。
331    pub fn readable(mut self) -> Self {
332        self.config.permissions.readable = Audience::Everyone;
333        self
334    }
335
336    /// 禁止任何角色读取。
337    pub fn not_readable(mut self) -> Self {
338        self.config.permissions.readable = Audience::Nobody;
339        self
340    }
341
342    /// 仅允许指定角色读取。
343    pub fn readable_by<I, S>(mut self, roles: I) -> Self
344    where
345        I: IntoIterator<Item = S>,
346        S: Into<String>,
347    {
348        self.config.permissions.readable = Audience::roles(roles);
349        self
350    }
351
352    /// 仅允许指定角色写入。
353    pub fn writable_by<I, S>(mut self, roles: I) -> Self
354    where
355        I: IntoIterator<Item = S>,
356        S: Into<String>,
357    {
358        self.config.permissions.writable = Audience::roles(roles);
359        self
360    }
361
362    /// 允许所有角色写入。
363    pub fn writable(mut self) -> Self {
364        self.config.permissions.writable = Audience::Everyone;
365        self
366    }
367
368    /// 禁止任何角色写入。
369    pub fn not_writable(mut self) -> Self {
370        self.config.permissions.writable = Audience::Nobody;
371        self
372    }
373
374    /// 允许字段用于关键词搜索(OR LIKE)。
375    ///
376    /// 与结构化筛选的 [`Field::filterable`] 位相互独立;只有文本字段
377    /// (`Field::string` / `Field::text`)会实际参与搜索,定义层在构建期
378    /// 会对非文本字段的 searchable 声明报错。
379    pub fn searchable(mut self) -> Self {
380        self.config.searchable = true;
381        self
382    }
383
384    /// 允许字段用于筛选。
385    pub fn filterable(mut self) -> Self {
386        self.config.filterable = true;
387        self.config.permissions.filterable = Audience::Everyone;
388        self
389    }
390
391    /// 禁止字段用于筛选。
392    pub fn not_filterable(mut self) -> Self {
393        self.config.filterable = false;
394        self.config.permissions.filterable = Audience::Nobody;
395        self
396    }
397
398    /// 仅允许指定角色使用字段筛选。
399    pub fn filterable_by<I, S>(mut self, roles: I) -> Self
400    where
401        I: IntoIterator<Item = S>,
402        S: Into<String>,
403    {
404        self.config.filterable = true;
405        self.config.permissions.filterable = Audience::roles(roles);
406        self
407    }
408
409    /// 允许字段用于排序。
410    pub fn sortable(mut self) -> Self {
411        self.config.sortable = true;
412        self.config.permissions.sortable = Audience::Everyone;
413        self
414    }
415
416    /// 禁止字段用于排序。
417    pub fn not_sortable(mut self) -> Self {
418        self.config.sortable = false;
419        self.config.permissions.sortable = Audience::Nobody;
420        self
421    }
422
423    /// 仅允许指定角色使用字段排序。
424    pub fn sortable_by<I, S>(mut self, roles: I) -> Self
425    where
426        I: IntoIterator<Item = S>,
427        S: Into<String>,
428    {
429        self.config.sortable = true;
430        self.config.permissions.sortable = Audience::roles(roles);
431        self
432    }
433
434    /// 将字段标记为租户隔离键。
435    pub fn tenant_key(mut self) -> Self {
436        self.config.tenant_key = true;
437        self
438    }
439
440    /// 设置敏感字段预设。
441    ///
442    /// 敏感字段不会进入默认 Record 投影或表 JSON Schema,并默认禁止读取、写入、
443    /// 筛选和排序。内部服务若确实需要显式读取或写入,必须随后调用
444    /// [`Field::readable_by`] / [`Field::writable_by`] 指定专用角色和显式字段列表。
445    pub fn secret(mut self) -> Self {
446        self.config.hidden = true;
447        self.config.permissions = FieldPermissions {
448            readable: Audience::Nobody,
449            writable: Audience::Nobody,
450            filterable: Audience::Nobody,
451            sortable: Audience::Nobody,
452        };
453        self.config.searchable = false;
454        self.config.filterable = false;
455        self.config.sortable = false;
456        self
457    }
458
459    /// 设置关联关系。
460    pub fn relation(
461        mut self,
462        table: impl Into<String>,
463        field: impl Into<String>,
464        relation_type: RelationType,
465    ) -> Self {
466        self.config.relation = Some(RelationConfig {
467            table: table.into(),
468            field: field.into(),
469            display_fields: Vec::new(),
470            relation_type,
471        });
472        self
473    }
474
475    /// 设置关联展示字段。
476    pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
477    where
478        I: IntoIterator<Item = S>,
479        S: Into<String>,
480    {
481        self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
482        self
483    }
484}
485
486#[derive(Debug, Clone)]
487struct PendingIndex {
488    name: Option<String>,
489    fields: Vec<String>,
490    unique: bool,
491}
492
493#[derive(Debug, Clone)]
494struct PendingCheck {
495    name: String,
496    expression: String,
497}
498
499#[derive(Debug, Clone)]
500struct PendingForeignKey {
501    name: String,
502    columns: Vec<String>,
503    referenced_table: String,
504    referenced_columns: Vec<String>,
505}
506
507/// Schema-first 表构建器。
508#[derive(Debug, Clone)]
509#[must_use = "表构建器必须调用 build"]
510pub struct Table {
511    name: String,
512    label: Option<String>,
513    fields: Vec<Field>,
514    indexes: Vec<PendingIndex>,
515    checks: Vec<PendingCheck>,
516    foreign_keys: Vec<PendingForeignKey>,
517    default_order: Vec<Order>,
518}
519
520impl Table {
521    /// 创建表定义构建器。
522    pub fn new(name: impl Into<String>) -> Self {
523        Self {
524            name: name.into(),
525            label: None,
526            fields: Vec::new(),
527            indexes: Vec::new(),
528            checks: Vec::new(),
529            foreign_keys: Vec::new(),
530            default_order: Vec::new(),
531        }
532    }
533
534    /// 设置表展示名称。
535    pub fn label(mut self, label: impl Into<String>) -> Self {
536        self.label = Some(label.into());
537        self
538    }
539
540    /// 批量添加字段;支持数组、`Vec` 和任意字段迭代器。
541    pub fn fields<I>(mut self, fields: I) -> Self
542    where
543        I: IntoIterator<Item = Field>,
544    {
545        self.fields.extend(fields);
546        self
547    }
548
549    /// 添加复合唯一索引。
550    pub fn unique<I, C>(mut self, fields: I) -> Self
551    where
552        I: IntoIterator<Item = C>,
553        C: Into<ColumnName>,
554    {
555        self.indexes.push(PendingIndex {
556            name: None,
557            fields: fields
558                .into_iter()
559                .map(|field| field.into().into_name())
560                .collect(),
561            unique: true,
562        });
563        self
564    }
565
566    /// 添加指定名称的复合唯一索引。
567    pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
568    where
569        I: IntoIterator<Item = C>,
570        C: Into<ColumnName>,
571    {
572        self.indexes.push(PendingIndex {
573            name: Some(name.into()),
574            fields: fields
575                .into_iter()
576                .map(|field| field.into().into_name())
577                .collect(),
578            unique: true,
579        });
580        self
581    }
582
583    /// 添加复合普通索引。
584    pub fn index<I, C>(mut self, fields: I) -> Self
585    where
586        I: IntoIterator<Item = C>,
587        C: Into<ColumnName>,
588    {
589        self.indexes.push(PendingIndex {
590            name: None,
591            fields: fields
592                .into_iter()
593                .map(|field| field.into().into_name())
594                .collect(),
595            unique: false,
596        });
597        self
598    }
599
600    /// 添加指定名称的复合普通索引。
601    pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
602    where
603        I: IntoIterator<Item = C>,
604        C: Into<ColumnName>,
605    {
606        self.indexes.push(PendingIndex {
607            name: Some(name.into()),
608            fields: fields
609                .into_iter()
610                .map(|field| field.into().into_name())
611                .collect(),
612            unique: false,
613        });
614        self
615    }
616
617    /// 添加指定名称的 MySQL CHECK 约束。
618    ///
619    /// 表达式属于受信任的应用定义,不得来自请求或运行时配置。
620    pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
621        self.checks.push(PendingCheck {
622            name: name.into(),
623            expression: expression.into(),
624        });
625        self
626    }
627
628    /// 添加指定名称的复合外键;更新和删除规则固定为 `RESTRICT`。
629    pub fn foreign_key_named<I, C, R, RC>(
630        mut self,
631        name: impl Into<String>,
632        columns: I,
633        referenced_table: impl Into<String>,
634        referenced_columns: R,
635    ) -> Self
636    where
637        I: IntoIterator<Item = C>,
638        C: Into<ColumnName>,
639        R: IntoIterator<Item = RC>,
640        RC: Into<ColumnName>,
641    {
642        self.foreign_keys.push(PendingForeignKey {
643            name: name.into(),
644            columns: columns
645                .into_iter()
646                .map(|column| column.into().into_name())
647                .collect(),
648            referenced_table: referenced_table.into(),
649            referenced_columns: referenced_columns
650                .into_iter()
651                .map(|column| column.into().into_name())
652                .collect(),
653        });
654        self
655    }
656
657    /// 设置首个默认排序规则。
658    pub fn default_order(mut self, order: Order) -> Self {
659        self.default_order = vec![order];
660        self
661    }
662
663    /// 追加默认排序规则。
664    pub fn then_order(mut self, order: Order) -> Self {
665        self.default_order.push(order);
666        self
667    }
668
669    /// 校验并生成不可变表定义。
670    pub fn build(self) -> Result<TableDefinition, BaseError> {
671        validate_identifier("表", &self.name)?;
672        if self.fields.is_empty() {
673            return Err(BaseError::ConfigError(format!(
674                "表 {} 至少需要一个字段",
675                self.name
676            )));
677        }
678
679        let mut field_names = HashSet::with_capacity(self.fields.len());
680        let mut legacy_names = HashSet::new();
681        let mut configs = HashMap::with_capacity(self.fields.len());
682        let mut primary_key: Option<String> = None;
683        let mut created_at: Option<String> = None;
684        let mut updated_at: Option<String> = None;
685        let mut deleted_at: Option<String> = None;
686        let mut soft_delete: Option<String> = None;
687        let mut tenant_key: Option<String> = None;
688        let mut indexes = self.indexes;
689        let checks = self.checks;
690        let foreign_keys = self.foreign_keys;
691
692        for mut field in self.fields {
693            validate_identifier("字段", &field.config.name)?;
694            if !field_names.insert(field.config.name.clone()) {
695                return Err(BaseError::ConfigError(format!(
696                    "表 {} 存在重复字段: {}",
697                    self.name, field.config.name
698                )));
699            }
700            if let Some(legacy_name) = field.config.renamed_from.as_deref() {
701                validate_identifier("旧字段", legacy_name)?;
702                if legacy_name == field.config.name || !legacy_names.insert(legacy_name.to_string())
703                {
704                    return Err(BaseError::ConfigError(format!(
705                        "表 {} 的旧字段改名来源重复或未发生改名: {}",
706                        self.name, legacy_name
707                    )));
708                }
709            }
710            if field.config.display_name.is_empty() {
711                field.config.display_name = field.config.name.clone();
712            }
713            if let Some(display_fields) = field.relation_display_fields.take() {
714                let relation = field.config.relation.as_mut().ok_or_else(|| {
715                    BaseError::ConfigError(format!(
716                        "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
717                        self.name, field.config.name
718                    ))
719                })?;
720                relation.display_fields = display_fields;
721            }
722            validate_field_shape(&self.name, &field)?;
723
724            if field.primary_key && primary_key.replace(field.config.name.clone()).is_some() {
725                return Err(BaseError::ConfigError(format!(
726                    "表 {} 只能定义一个主键",
727                    self.name
728                )));
729            }
730            if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
731                return Err(BaseError::ConfigError(format!(
732                    "表 {} 只能定义一个租户隔离字段",
733                    self.name
734                )));
735            }
736            set_unique_role(
737                &self.name,
738                "created_at",
739                field.created_at,
740                &field.config.name,
741                &mut created_at,
742            )?;
743            set_unique_role(
744                &self.name,
745                "updated_at",
746                field.updated_at,
747                &field.config.name,
748                &mut updated_at,
749            )?;
750            set_unique_role(
751                &self.name,
752                "deleted_at",
753                field.deleted_at,
754                &field.config.name,
755                &mut deleted_at,
756            )?;
757            set_unique_role(
758                &self.name,
759                "soft_delete",
760                field.soft_delete,
761                &field.config.name,
762                &mut soft_delete,
763            )?;
764
765            if field.unique {
766                indexes.push(PendingIndex {
767                    name: field.unique_name.take(),
768                    fields: vec![field.config.name.clone()],
769                    unique: true,
770                });
771            }
772            if field.index {
773                indexes.push(PendingIndex {
774                    name: field.index_name.take(),
775                    fields: vec![field.config.name.clone()],
776                    unique: false,
777                });
778            }
779            configs.insert(field.config.name.clone(), field.config);
780        }
781
782        if let Some(legacy_name) = legacy_names
783            .iter()
784            .find(|legacy_name| field_names.contains(legacy_name.as_str()))
785        {
786            return Err(BaseError::ConfigError(format!(
787                "表 {} 同时声明旧字段与改名后字段: {}",
788                self.name, legacy_name
789            )));
790        }
791
792        let primary_key = primary_key
793            .ok_or_else(|| BaseError::ConfigError(format!("表 {} 必须定义一个主键", self.name)))?;
794
795        let mut unique_indexes = Vec::new();
796        let mut normal_indexes = Vec::new();
797        let mut index_names = HashSet::new();
798        for index in indexes {
799            validate_index(&self.name, &field_names, &index, &mut index_names)?;
800            let config = IndexConfig::new(index.name, index.fields);
801            if index.unique {
802                unique_indexes.push(config);
803            } else {
804                normal_indexes.push(config);
805            }
806        }
807
808        let mut constraint_names = HashSet::new();
809        let checks = checks
810            .into_iter()
811            .map(|check| {
812                validate_constraint_name(&self.name, &check.name, &mut constraint_names)?;
813                validate_check_expression(&self.name, &check.name, &check.expression)?;
814                Ok(CheckConfig {
815                    name: check.name,
816                    expression: check.expression,
817                })
818            })
819            .collect::<Result<Vec<_>, BaseError>>()?;
820        let foreign_keys = foreign_keys
821            .into_iter()
822            .map(|foreign_key| {
823                validate_constraint_name(&self.name, &foreign_key.name, &mut constraint_names)?;
824                validate_foreign_key(&self.name, &field_names, &foreign_key)?;
825                Ok(ForeignKeyConfig {
826                    name: foreign_key.name,
827                    columns: foreign_key.columns,
828                    referenced_table: foreign_key.referenced_table,
829                    referenced_columns: foreign_key.referenced_columns,
830                })
831            })
832            .collect::<Result<Vec<_>, BaseError>>()?;
833
834        let mut orders = Vec::with_capacity(self.default_order.len());
835        for order in self.default_order {
836            if !field_names.contains(&order.field) {
837                return Err(BaseError::ConfigError(format!(
838                    "表 {} 的默认排序字段不存在: {}",
839                    self.name, order.field
840                )));
841            }
842            orders.push((order.field, order.direction));
843        }
844
845        let timestamp_fields =
846            if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
847                Some(TimestampFields::new(created_at, updated_at, deleted_at))
848            } else {
849                None
850            };
851        let table_ref = yang_db::TableRef::new(self.name.clone())
852            .map_err(|error| BaseError::ConfigError(error.to_string()))?;
853        let field_refs = field_names
854            .iter()
855            .map(|name| {
856                yang_db::FieldRef::new(name.clone())
857                    .map(|field| (name.clone(), field))
858                    .map_err(|error| BaseError::ConfigError(error.to_string()))
859            })
860            .collect::<Result<HashMap<_, _>, _>>()?;
861
862        Ok(TableDefinition {
863            config: Arc::new(TableConfig {
864                table_name: self.name.clone(),
865                table_ref,
866                display_name: self.label.unwrap_or(self.name),
867                primary_key,
868                fields: configs,
869                field_refs,
870                unique_indexes,
871                indexes: normal_indexes,
872                checks,
873                foreign_keys,
874                default_order: orders,
875                soft_delete_field: soft_delete,
876                timestamp_fields,
877            }),
878        })
879    }
880}
881
882/// 不可变的数据表定义。
883#[derive(Debug, Clone)]
884pub struct TableDefinition {
885    pub(crate) config: Arc<TableConfig>,
886}
887
888impl TableDefinition {
889    /// 返回数据库表名。
890    pub fn name(&self) -> &str {
891        &self.config.table_name
892    }
893
894    /// 返回展示名称。
895    pub fn label(&self) -> &str {
896        &self.config.display_name
897    }
898
899    /// 返回主键字段名。
900    pub fn primary_key(&self) -> &str {
901        &self.config.primary_key
902    }
903
904    /// 返回字段数量。
905    pub fn field_count(&self) -> usize {
906        self.config.fields.len()
907    }
908
909    /// 按数据库字段名读取元数据。
910    pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
911        self.config
912            .fields
913            .get(name)
914            .map(|config| FieldMetadata { config })
915    }
916
917    /// 按字段名排序返回全部字段元数据。
918    pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
919        let mut fields: Vec<_> = self
920            .config
921            .fields
922            .values()
923            .map(|config| FieldMetadata { config })
924            .collect();
925        fields.sort_by(|left, right| left.name().cmp(right.name()));
926        fields
927    }
928
929    /// 返回软删除字段名。
930    pub fn soft_delete_field(&self) -> Option<&str> {
931        self.config.soft_delete_field.as_deref()
932    }
933
934    /// 返回唯一租户隔离字段;表未声明租户字段时返回 `None`。
935    pub fn tenant_key_field(&self) -> Option<&str> {
936        self.config
937            .fields
938            .values()
939            .find(|field| field.tenant_key)
940            .map(|field| field.name.as_str())
941    }
942
943    /// 生成供 API catalog 使用的全局写入侧 JSON Schema。
944    ///
945    /// 该 schema 是所有角色可写字段的并集;面向当前请求返回结构时应使用
946    /// `Self::input_schema_for_roles`。
947    pub fn input_schema(&self) -> Value {
948        self.json_schema(false, None)
949    }
950
951    /// 生成供 API catalog 使用的全局读取侧 JSON Schema。
952    ///
953    /// 该 schema 是所有角色可读字段的并集;面向当前请求返回结构时应使用
954    /// `Self::output_schema_for_roles`。
955    pub fn output_schema(&self) -> Value {
956        self.json_schema(true, None)
957    }
958
959    /// 按当前用户角色生成写入侧 JSON Schema。
960    pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
961        self.json_schema(false, Some(roles))
962    }
963
964    /// 按当前用户角色生成读取侧 JSON Schema。
965    pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
966        self.json_schema(true, Some(roles))
967    }
968
969    /// 返回指定数据库字段的底层 JSON Schema,供内置 API 描述投影使用。
970    #[cfg(feature = "mysql")]
971    pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
972        self.config.fields.get(name).map(field_json_schema)
973    }
974
975    fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
976        let mut properties = Map::new();
977        let mut required = Vec::new();
978        let mut names: Vec<_> = self.config.fields.keys().collect();
979        names.sort();
980        for name in names {
981            let field = &self.config.fields[name];
982            let generated = field.auto_increment
983                || self
984                    .config
985                    .timestamp_fields
986                    .as_ref()
987                    .is_some_and(|timestamps| {
988                        timestamps.created_at.as_deref() == Some(name.as_str())
989                            || timestamps.updated_at.as_deref() == Some(name.as_str())
990                            || timestamps.deleted_at.as_deref() == Some(name.as_str())
991                    })
992                || self.config.soft_delete_field.as_deref() == Some(name.as_str());
993            let audience = if output {
994                &field.permissions.readable
995            } else {
996                &field.permissions.writable
997            };
998            let audience_allows = roles.map_or_else(
999                || !matches!(audience, Audience::Nobody),
1000                |roles| audience.allows(roles),
1001            );
1002            if field.hidden || !audience_allows || (!output && generated) {
1003                continue;
1004            }
1005            properties.insert(name.clone(), field_json_schema(field));
1006            if field.required && (output || (!generated && field.default_value.is_none())) {
1007                required.push(Value::String(name.clone()));
1008            }
1009        }
1010        json!({
1011            "type": "object",
1012            "title": self.config.display_name,
1013            "properties": properties,
1014            "required": required,
1015            "additionalProperties": false,
1016        })
1017    }
1018
1019    #[cfg(feature = "mysql")]
1020    pub(crate) fn config(&self) -> &TableConfig {
1021        &self.config
1022    }
1023
1024    pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
1025        Arc::clone(&self.config)
1026    }
1027
1028    /// 校验实际数据库列是否兼容当前表定义。
1029    pub fn validate_schema(
1030        &self,
1031        columns: &[super::SchemaColumn],
1032    ) -> super::SchemaValidationReport {
1033        self.config.validate_schema(columns)
1034    }
1035
1036    /// 将表定义绑定到 MySQL 连接池。
1037    #[cfg(feature = "mysql")]
1038    pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
1039        TableHandle {
1040            definition: self.clone(),
1041            pool,
1042        }
1043    }
1044}
1045
1046/// 只读字段元数据视图。
1047#[derive(Debug, Clone, Copy)]
1048pub struct FieldMetadata<'a> {
1049    config: &'a FieldConfig,
1050}
1051
1052impl<'a> FieldMetadata<'a> {
1053    /// 返回数据库字段名。
1054    pub fn name(self) -> &'a str {
1055        &self.config.name
1056    }
1057
1058    /// 返回展示名称。
1059    pub fn label(self) -> &'a str {
1060        &self.config.display_name
1061    }
1062
1063    /// 返回字段是否承担租户隔离键语义。
1064    pub fn is_tenant_key(self) -> bool {
1065        self.config.tenant_key
1066    }
1067
1068    /// 返回字段类型。
1069    pub fn field_type(self) -> &'a FieldType {
1070        &self.config.field_type
1071    }
1072
1073    /// 返回字段是否必填。
1074    pub fn is_required(self) -> bool {
1075        self.config.required
1076    }
1077
1078    /// 返回字段默认值。
1079    pub fn default_value(self) -> Option<&'a Value> {
1080        self.config.default_value.as_ref()
1081    }
1082
1083    /// 返回字段是否由数据库自增生成。
1084    pub fn is_auto_increment(self) -> bool {
1085        self.config.auto_increment
1086    }
1087
1088    /// 返回字段是否允许关键词搜索。
1089    pub fn is_searchable(self) -> bool {
1090        self.config.searchable
1091    }
1092
1093    /// 返回字段是否允许筛选。
1094    pub fn is_filterable(self) -> bool {
1095        self.config.filterable
1096    }
1097
1098    /// 返回字段是否允许排序。
1099    pub fn is_sortable(self) -> bool {
1100        self.config.sortable
1101    }
1102
1103    /// 返回字段是否从通用记录投影和表 JSON Schema 中隐藏。
1104    pub fn is_secret(self) -> bool {
1105        self.config.hidden
1106    }
1107}
1108
1109/// 绑定数据库连接池后的表句柄。
1110#[cfg(feature = "mysql")]
1111#[derive(Debug, Clone)]
1112pub struct TableHandle {
1113    definition: TableDefinition,
1114    pool: Arc<sqlx::MySqlPool>,
1115}
1116
1117#[cfg(feature = "mysql")]
1118impl TableHandle {
1119    /// 返回不可变表定义。
1120    pub fn definition(&self) -> &TableDefinition {
1121        &self.definition
1122    }
1123
1124    /// 创建带字段权限保护的查询构建器。
1125    pub fn query<I, S>(&self, roles: I) -> TableQuery
1126    where
1127        I: IntoIterator<Item = S>,
1128        S: Into<String>,
1129    {
1130        let roles: Arc<[String]> =
1131            Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1132        TableQuery::new(
1133            self.definition.shared_config(),
1134            roles,
1135            Some(Arc::clone(&self.pool)),
1136        )
1137    }
1138}
1139
1140fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1141    let mut chars = value.chars();
1142    let first = chars
1143        .next()
1144        .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1145    if value.len() > 64
1146        || !(first == '_' || first.is_ascii_alphabetic())
1147        || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1148    {
1149        return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1150    }
1151    Ok(())
1152}
1153
1154fn validate_field_shape(table: &str, field: &Field) -> Result<(), BaseError> {
1155    match &field.config.field_type {
1156        FieldType::String { max_length } if *max_length == 0 => {
1157            return Err(BaseError::ConfigError(format!(
1158                "表 {table} 的字符串字段 {} 长度必须大于 0",
1159                field.config.name
1160            )));
1161        }
1162        FieldType::Enum { values } => {
1163            let unique: HashSet<_> = values.iter().collect();
1164            if values.is_empty() || unique.len() != values.len() {
1165                return Err(BaseError::ConfigError(format!(
1166                    "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1167                    field.config.name
1168                )));
1169            }
1170        }
1171        FieldType::Decimal { precision, scale }
1172            if *precision == 0 || *precision > 65 || *scale > *precision =>
1173        {
1174            return Err(BaseError::ConfigError(format!(
1175                "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1176                field.config.name
1177            )));
1178        }
1179        _ => {}
1180    }
1181
1182    if field.config.auto_increment
1183        && (!field.primary_key
1184            || !matches!(
1185                field.config.field_type,
1186                FieldType::Integer | FieldType::BigInt
1187            ))
1188    {
1189        return Err(BaseError::ConfigError(format!(
1190            "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1191            field.config.name
1192        )));
1193    }
1194    if field.primary_key && !field.config.required {
1195        return Err(BaseError::ConfigError(format!(
1196            "表 {table} 的主键必须为必填字段: {}",
1197            field.config.name
1198        )));
1199    }
1200    if field.config.auto_increment && field.config.default_value.is_some() {
1201        return Err(BaseError::ConfigError(format!(
1202            "表 {table} 的自增字段不能配置默认值: {}",
1203            field.config.name
1204        )));
1205    }
1206    validate_validator_configuration(table, &field.config)?;
1207    if let Some(default) = &field.config.default_value {
1208        if matches!(field.config.field_type, FieldType::Text | FieldType::Json) {
1209            return Err(BaseError::ConfigError(format!(
1210                "表 {table} 的 TEXT/JSON 字段不能配置数据库默认值: {}",
1211                field.config.name
1212            )));
1213        }
1214        field.config.validate(default)?;
1215    }
1216    validate_audience(
1217        table,
1218        &field.config.name,
1219        "读取",
1220        &field.config.permissions.readable,
1221    )?;
1222    validate_audience(
1223        table,
1224        &field.config.name,
1225        "写入",
1226        &field.config.permissions.writable,
1227    )?;
1228    validate_audience(
1229        table,
1230        &field.config.name,
1231        "筛选",
1232        &field.config.permissions.filterable,
1233    )?;
1234    validate_audience(
1235        table,
1236        &field.config.name,
1237        "排序",
1238        &field.config.permissions.sortable,
1239    )?;
1240    if let Some(relation) = &field.config.relation {
1241        validate_identifier("关联表", &relation.table)?;
1242        validate_identifier("关联字段", &relation.field)?;
1243        for display_field in &relation.display_fields {
1244            validate_identifier("关联展示字段", display_field)?;
1245        }
1246    }
1247    if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1248        && !matches!(
1249            field.config.field_type,
1250            FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1251        )
1252    {
1253        return Err(BaseError::ConfigError(format!(
1254            "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1255            field.config.name
1256        )));
1257    }
1258    Ok(())
1259}
1260
1261fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1262    let string_compatible = matches!(
1263        field.field_type,
1264        FieldType::String { .. }
1265            | FieldType::Text
1266            | FieldType::Enum { .. }
1267            | FieldType::Date
1268            | FieldType::DateTime
1269    );
1270    let numeric_compatible = matches!(
1271        field.field_type,
1272        FieldType::Integer
1273            | FieldType::BigInt
1274            | FieldType::Float
1275            | FieldType::Double
1276            | FieldType::Decimal { .. }
1277            | FieldType::Timestamp
1278    );
1279    let mut min_length: Option<usize> = None;
1280    let mut max_length: Option<usize> = None;
1281    let mut minimum: Option<f64> = None;
1282    let mut maximum: Option<f64> = None;
1283
1284    for validator in &field.validators {
1285        match validator {
1286            Validator::MinLength(value) => {
1287                ensure_validator_type(table, field, validator, string_compatible)?;
1288                min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1289            }
1290            Validator::MaxLength(value) => {
1291                ensure_validator_type(table, field, validator, string_compatible)?;
1292                max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1293            }
1294            Validator::Min(value) => {
1295                ensure_validator_type(table, field, validator, numeric_compatible)?;
1296                if !value.is_finite() {
1297                    return Err(BaseError::ConfigError(format!(
1298                        "表 {table} 的字段 {} 数值下限必须是有限数值",
1299                        field.name
1300                    )));
1301                }
1302                minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1303            }
1304            Validator::Max(value) => {
1305                ensure_validator_type(table, field, validator, numeric_compatible)?;
1306                if !value.is_finite() {
1307                    return Err(BaseError::ConfigError(format!(
1308                        "表 {table} 的字段 {} 数值上限必须是有限数值",
1309                        field.name
1310                    )));
1311                }
1312                maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1313            }
1314            Validator::Email
1315            | Validator::EmailLoose
1316            | Validator::Phone
1317            | Validator::PhoneLoose
1318            | Validator::Url => {
1319                ensure_validator_type(table, field, validator, string_compatible)?;
1320            }
1321            Validator::Regex(pattern) => {
1322                ensure_validator_type(table, field, validator, string_compatible)?;
1323                #[cfg(feature = "validator")]
1324                regex::Regex::new(pattern).map_err(|error| {
1325                    BaseError::ConfigError(format!(
1326                        "表 {table} 的字段 {} 正则表达式无效: {error}",
1327                        field.name
1328                    ))
1329                })?;
1330                #[cfg(not(feature = "validator"))]
1331                return Err(BaseError::ConfigError(format!(
1332                    "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1333                    field.name,
1334                )));
1335            }
1336            Validator::Custom(_) => {}
1337        }
1338    }
1339
1340    if let (Some(min), Some(max)) = (min_length, max_length) {
1341        if min > max {
1342            return Err(BaseError::ConfigError(format!(
1343                "表 {table} 的字段 {} 最小长度不能大于最大长度",
1344                field.name
1345            )));
1346        }
1347    }
1348    if let (
1349        FieldType::String {
1350            max_length: storage_max,
1351        },
1352        Some(min),
1353    ) = (&field.field_type, min_length)
1354    {
1355        if min > *storage_max {
1356            return Err(BaseError::ConfigError(format!(
1357                "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1358                field.name
1359            )));
1360        }
1361    }
1362    if let (Some(min), Some(max)) = (minimum, maximum) {
1363        if min > max {
1364            return Err(BaseError::ConfigError(format!(
1365                "表 {table} 的字段 {} 数值下限不能大于上限",
1366                field.name
1367            )));
1368        }
1369    }
1370    Ok(())
1371}
1372
1373fn ensure_validator_type(
1374    table: &str,
1375    field: &FieldConfig,
1376    validator: &Validator,
1377    compatible: bool,
1378) -> Result<(), BaseError> {
1379    if compatible {
1380        return Ok(());
1381    }
1382    Err(BaseError::ConfigError(format!(
1383        "表 {table} 的字段 {} 类型不能使用{}验证器",
1384        field.name,
1385        validator.display_name()
1386    )))
1387}
1388
1389fn validate_audience(
1390    table: &str,
1391    field: &str,
1392    operation: &str,
1393    audience: &Audience,
1394) -> Result<(), BaseError> {
1395    if let Audience::Roles(roles) = audience {
1396        if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1397            return Err(BaseError::ConfigError(format!(
1398                "表 {table} 的字段 {field} 的{operation}角色不能为空"
1399            )));
1400        }
1401    }
1402    Ok(())
1403}
1404
1405fn set_unique_role(
1406    table: &str,
1407    role: &str,
1408    enabled: bool,
1409    field: &str,
1410    target: &mut Option<String>,
1411) -> Result<(), BaseError> {
1412    if !enabled {
1413        return Ok(());
1414    }
1415    if let Some(existing) = target {
1416        return Err(BaseError::ConfigError(format!(
1417            "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1418        )));
1419    }
1420    *target = Some(field.to_string());
1421    Ok(())
1422}
1423
1424fn validate_index(
1425    table: &str,
1426    field_names: &HashSet<String>,
1427    index: &PendingIndex,
1428    index_names: &mut HashSet<String>,
1429) -> Result<(), BaseError> {
1430    if index.fields.is_empty() {
1431        return Err(BaseError::ConfigError(format!(
1432            "表 {table} 的索引字段不能为空"
1433        )));
1434    }
1435    let mut seen = HashSet::new();
1436    for field in &index.fields {
1437        if !field_names.contains(field) {
1438            return Err(BaseError::ConfigError(format!(
1439                "表 {table} 的索引字段不存在: {field}"
1440            )));
1441        }
1442        if !seen.insert(field) {
1443            return Err(BaseError::ConfigError(format!(
1444                "表 {table} 的索引重复引用字段: {field}"
1445            )));
1446        }
1447    }
1448    let prefix = if index.unique { "uk" } else { "idx" };
1449    let effective_name = index
1450        .name
1451        .clone()
1452        .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
1453    validate_identifier("索引", &effective_name)?;
1454    if !index_names.insert(effective_name.clone()) {
1455        return Err(BaseError::ConfigError(format!(
1456            "表 {table} 存在重复索引名: {effective_name}"
1457        )));
1458    }
1459    Ok(())
1460}
1461
1462fn validate_constraint_name(
1463    table: &str,
1464    name: &str,
1465    names: &mut HashSet<String>,
1466) -> Result<(), BaseError> {
1467    validate_identifier("约束", name)?;
1468    if !names.insert(name.to_string()) {
1469        return Err(BaseError::ConfigError(format!(
1470            "表 {table} 存在重复约束名: {name}"
1471        )));
1472    }
1473    Ok(())
1474}
1475
1476fn validate_check_expression(table: &str, name: &str, expression: &str) -> Result<(), BaseError> {
1477    let expression = expression.trim();
1478    if expression.is_empty()
1479        || expression.chars().count() > 2_048
1480        || [";", "--", "/*", "*/"]
1481            .iter()
1482            .any(|marker| expression.contains(marker))
1483    {
1484        return Err(BaseError::ConfigError(format!(
1485            "表 {table} 的 CHECK {name} 必须是单条、非空且长度受限的受信表达式"
1486        )));
1487    }
1488    Ok(())
1489}
1490
1491fn validate_foreign_key(
1492    table: &str,
1493    field_names: &HashSet<String>,
1494    foreign_key: &PendingForeignKey,
1495) -> Result<(), BaseError> {
1496    validate_identifier("外键目标表", &foreign_key.referenced_table)?;
1497    if foreign_key.columns.is_empty()
1498        || foreign_key.columns.len() != foreign_key.referenced_columns.len()
1499    {
1500        return Err(BaseError::ConfigError(format!(
1501            "表 {table} 的外键 {} 本地列与目标列必须非空且数量一致",
1502            foreign_key.name
1503        )));
1504    }
1505    let mut local = HashSet::new();
1506    let mut referenced = HashSet::new();
1507    for column in &foreign_key.columns {
1508        validate_identifier("外键列", column)?;
1509        if !field_names.contains(column) || !local.insert(column) {
1510            return Err(BaseError::ConfigError(format!(
1511                "表 {table} 的外键 {} 引用了缺失或重复的本地列 {column}",
1512                foreign_key.name
1513            )));
1514        }
1515    }
1516    for column in &foreign_key.referenced_columns {
1517        validate_identifier("外键目标列", column)?;
1518        if !referenced.insert(column) {
1519            return Err(BaseError::ConfigError(format!(
1520                "表 {table} 的外键 {} 重复引用目标列 {column}",
1521                foreign_key.name
1522            )));
1523        }
1524    }
1525    Ok(())
1526}
1527
1528fn field_json_schema(field: &FieldConfig) -> Value {
1529    let mut schema = Map::new();
1530    let mut min_length: Option<usize> = None;
1531    let mut max_length: Option<usize> = None;
1532    let mut minimum: Option<f64> = None;
1533    let mut maximum: Option<f64> = None;
1534    let mut patterns = Vec::new();
1535    let mut runtime_validators = Vec::new();
1536    match &field.field_type {
1537        FieldType::String {
1538            max_length: storage_max,
1539        } => {
1540            schema.insert("type".into(), json!("string"));
1541            max_length = Some(*storage_max);
1542        }
1543        FieldType::Text => {
1544            schema.insert("type".into(), json!("string"));
1545        }
1546        FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
1547            schema.insert("type".into(), json!("integer"));
1548        }
1549        FieldType::Float | FieldType::Double => {
1550            schema.insert("type".into(), json!("number"));
1551        }
1552        FieldType::Decimal { precision, scale } => {
1553            schema.insert("type".into(), json!("string"));
1554            schema.insert("format".into(), json!("decimal"));
1555            schema.insert("x-precision".into(), json!(precision));
1556            schema.insert("x-scale".into(), json!(scale));
1557        }
1558        FieldType::Boolean => {
1559            schema.insert("type".into(), json!("boolean"));
1560        }
1561        FieldType::Date => {
1562            schema.insert("type".into(), json!("string"));
1563            schema.insert("format".into(), json!("date"));
1564        }
1565        FieldType::DateTime => {
1566            schema.insert("type".into(), json!("string"));
1567            schema.insert("format".into(), json!("date-time"));
1568        }
1569        FieldType::Json => {
1570            schema.insert("type".into(), json!(["object", "array"]));
1571        }
1572        FieldType::Enum { values } => {
1573            schema.insert("type".into(), json!("string"));
1574            schema.insert("enum".into(), json!(values));
1575        }
1576    }
1577
1578    for validator in &field.validators {
1579        match validator {
1580            Validator::MinLength(value) => {
1581                min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1582            }
1583            Validator::MaxLength(value) => {
1584                max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1585            }
1586            Validator::Min(value) => {
1587                minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1588            }
1589            Validator::Max(value) => {
1590                maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1591            }
1592            Validator::Email => {
1593                #[cfg(feature = "validator")]
1594                patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
1595                #[cfg(not(feature = "validator"))]
1596                patterns.push("@".to_string());
1597            }
1598            Validator::EmailLoose => patterns.push("@".to_string()),
1599            Validator::Phone => {
1600                #[cfg(feature = "validator")]
1601                patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
1602                #[cfg(not(feature = "validator"))]
1603                patterns.push(r"^[0-9+\-]*$".to_string());
1604            }
1605            Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
1606            Validator::Url => patterns.push(r"^https?://".to_string()),
1607            Validator::Regex(pattern) => patterns.push(pattern.clone()),
1608            Validator::Custom(_) => runtime_validators.push("custom"),
1609        }
1610    }
1611
1612    if let Some(value) = min_length {
1613        schema.insert("minLength".into(), json!(value));
1614    }
1615    if let Some(value) = max_length {
1616        schema.insert("maxLength".into(), json!(value));
1617    }
1618    if let Some(value) = minimum {
1619        schema.insert("minimum".into(), json!(value));
1620    }
1621    if let Some(value) = maximum {
1622        schema.insert("maximum".into(), json!(value));
1623    }
1624    match patterns.as_slice() {
1625        [] => {}
1626        [pattern] => {
1627            schema.insert("pattern".into(), json!(pattern));
1628        }
1629        patterns => {
1630            schema.insert(
1631                "allOf".into(),
1632                Value::Array(
1633                    patterns
1634                        .iter()
1635                        .map(|pattern| json!({ "pattern": pattern }))
1636                        .collect(),
1637                ),
1638            );
1639        }
1640    }
1641    if !runtime_validators.is_empty() {
1642        schema.insert(
1643            "x-yang-runtime-validators".into(),
1644            json!(runtime_validators),
1645        );
1646    }
1647    if let Some(relation) = &field.relation {
1648        let relation_type = match relation.relation_type {
1649            RelationType::OneToOne => "one_to_one",
1650            RelationType::OneToMany => "one_to_many",
1651            RelationType::ManyToOne => "many_to_one",
1652            RelationType::ManyToMany => "many_to_many",
1653        };
1654        schema.insert(
1655            "x-yang-relation".into(),
1656            json!({
1657                "table": relation.table,
1658                "field": relation.field,
1659                "displayFields": relation.display_fields,
1660                "type": relation_type,
1661            }),
1662        );
1663    }
1664
1665    if !field.required {
1666        if let Some(field_types) = schema.get_mut("type") {
1667            match field_types {
1668                Value::String(field_type) => {
1669                    *field_types = json!([field_type.clone(), "null"]);
1670                }
1671                Value::Array(types) if !types.iter().any(|value| value == "null") => {
1672                    types.push(json!("null"));
1673                }
1674                _ => {}
1675            }
1676        }
1677        if let Some(Value::Array(values)) = schema.get_mut("enum") {
1678            values.push(Value::Null);
1679        }
1680    }
1681    if !field.display_name.is_empty() {
1682        schema.insert("title".into(), json!(field.display_name));
1683    }
1684    if let Some(default) = &field.default_value {
1685        schema.insert("default".into(), default.clone());
1686    }
1687    Value::Object(schema)
1688}