Skip to main content

yang_base/definition/
field.rs

1//! BR 风格 Fields 定义及其原生 YANG 投影。
2
3use super::{ActionRef, FieldKind, FieldName, FieldRef, TableName, WidgetHint};
4use crate::error::BaseError;
5use crate::table::{Field, RelationType, Table as SchemaTable, TableDefinition, Validator};
6use serde_json::Value;
7use std::collections::BTreeSet;
8use std::marker::PhantomData;
9use std::sync::Arc;
10
11/// 字段的数据库存储语义。
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
13pub struct StorageSpec {
14    /// 是否允许缺失/NULL。
15    pub required: bool,
16    /// 字符串存储上限。
17    pub max_length: Option<usize>,
18    /// DECIMAL 精度。
19    pub precision: Option<u8>,
20    /// DECIMAL 小数位数。
21    pub scale: Option<u8>,
22    /// 数据库默认值。
23    pub default: Option<Value>,
24    /// 是否建立唯一索引。
25    pub unique: bool,
26    /// 是否建立普通索引。
27    pub indexed: bool,
28    /// 显式声明该字段由哪个旧列原位改名而来。
29    pub renamed_from: Option<String>,
30}
31
32/// 字段的输入验证语义。
33#[derive(Debug, Clone, PartialEq, Eq, Default)]
34pub struct ValidationSpec {
35    /// 字符最小长度。
36    pub min_length: Option<usize>,
37    /// 字符最大长度。
38    pub max_length: Option<usize>,
39    /// 数值下限,使用十进制文本避免元数据中的浮点漂移。
40    pub minimum: Option<String>,
41    /// 数值上限,使用十进制文本避免元数据中的浮点漂移。
42    pub maximum: Option<String>,
43    /// 可选正则表达式。
44    pub pattern: Option<String>,
45}
46
47/// 字段读写与查询权限。
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum AccessRule {
50    /// 所有调用者。
51    Everyone,
52    /// 不允许普通调用者。
53    Nobody,
54    /// 仅指定角色。
55    Roles(Vec<String>),
56}
57
58/// 字段的访问控制语义。
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct AccessSpec {
61    /// 读取规则。
62    pub readable: AccessRule,
63    /// 写入规则。
64    pub writable: AccessRule,
65    /// 是否允许全文关键词搜索。
66    pub searchable: bool,
67    /// 是否允许结构化条件筛选。
68    pub filterable: bool,
69    /// 是否允许排序。
70    pub sortable: bool,
71    /// 是否为敏感字段。
72    pub secret: bool,
73}
74
75impl Default for AccessSpec {
76    fn default() -> Self {
77        Self {
78            readable: AccessRule::Everyone,
79            writable: AccessRule::Everyone,
80            searchable: false,
81            filterable: false,
82            sortable: false,
83            secret: false,
84        }
85    }
86}
87
88/// 字段的默认展示语义。
89#[derive(Debug, Clone, PartialEq, Eq, Default)]
90pub struct PresentationSpec {
91    /// 用户可见标题。
92    pub title: String,
93    /// 帮助说明。
94    pub description: String,
95    /// 关系字段的默认展示列。
96    pub display: Vec<FieldRef>,
97    /// 可选前端控件提示;不改变字段数据和权限语义。
98    pub widget: Option<WidgetHint>,
99}
100
101/// 时间戳字段的自动写入语义。
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum TimestampMode {
104    /// 普通时间戳。
105    Value,
106    /// 插入时自动写入。
107    CreatedAt,
108    /// 更新时自动写入。
109    UpdatedAt,
110    /// 软删除标记。
111    SoftDelete,
112}
113
114/// 单个字段的共享语义核心。
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct FieldSpec {
117    /// 字段名。
118    pub name: FieldName,
119    /// 字段语义种类。
120    pub kind: FieldKind,
121    /// 数据库存储语义。
122    pub storage: StorageSpec,
123    /// 输入验证语义。
124    pub validation: ValidationSpec,
125    /// 访问控制语义。
126    pub access: AccessSpec,
127    /// 默认展示语义。
128    pub presentation: PresentationSpec,
129    /// 可选关系目标。
130    pub relation: Option<FieldRef>,
131    /// 可选选择器 Action。
132    pub select: Option<ActionRef>,
133    /// Radio 的值与标题。
134    pub options: Vec<(String, String)>,
135    /// 时间戳自动写入模式。
136    pub timestamp_mode: TimestampMode,
137    /// 是否为租户隔离键。
138    pub tenant_key: bool,
139}
140
141impl FieldSpec {
142    /// 创建最小字段定义。
143    pub fn new(name: FieldName, kind: FieldKind) -> Self {
144        Self {
145            name,
146            kind,
147            storage: StorageSpec::default(),
148            validation: ValidationSpec::default(),
149            access: AccessSpec::default(),
150            presentation: PresentationSpec::default(),
151            relation: None,
152            select: None,
153            options: Vec::new(),
154            timestamp_mode: TimestampMode::Value,
155            tenant_key: false,
156        }
157    }
158
159    /// 设置必填语义。
160    pub fn required(mut self, required: bool) -> Self {
161        self.storage.required = required;
162        self
163    }
164
165    /// 返回字段是否必填。
166    pub fn is_required(&self) -> bool {
167        self.storage.required
168    }
169
170    /// 设置关系目标。
171    pub fn relation(mut self, target: FieldRef) -> Self {
172        self.relation = Some(target);
173        self
174    }
175
176    /// 设置选择器 Action。
177    pub fn select(mut self, action: ActionRef) -> Self {
178        self.select = Some(action);
179        self
180    }
181
182    /// 将字段标记为租户隔离键。
183    pub fn tenant_key(mut self, tenant_key: bool) -> Self {
184        self.tenant_key = tenant_key;
185        self
186    }
187
188    /// 返回字段的前端控件提示。
189    ///
190    /// 显式 [`PresentationSpec::widget`] 优先;未设置时按字段数据语义确定性映射。
191    /// secret 字符串默认使用密码控件,但该展示提示不改变服务端读写权限。
192    pub fn widget_hint(&self) -> WidgetHint {
193        if let Some(widget) = self.presentation.widget {
194            return widget;
195        }
196        match self.kind {
197            FieldKind::Key | FieldKind::Int => WidgetHint::Integer,
198            FieldKind::Str if self.access.secret => WidgetHint::Password,
199            FieldKind::Str => WidgetHint::Text,
200            FieldKind::Text => WidgetHint::Textarea,
201            FieldKind::Decimal => WidgetHint::Decimal,
202            FieldKind::Switch => WidgetHint::Switch,
203            FieldKind::Radio => WidgetHint::Radio,
204            FieldKind::Table => WidgetHint::RelationSelect,
205            FieldKind::Tree => WidgetHint::TreeSelect,
206            FieldKind::Timestamp => WidgetHint::DateTime,
207        }
208    }
209
210    fn into_schema_field(self) -> Result<Field, BaseError> {
211        let name = self.name.to_string();
212        let mut field = match self.kind {
213            FieldKind::Key => Field::id(name),
214            FieldKind::Str => Field::string(name, self.storage.max_length.unwrap_or(255)),
215            FieldKind::Text => Field::text(name),
216            FieldKind::Int => Field::bigint(name),
217            FieldKind::Decimal => Field::decimal(
218                name,
219                self.storage.precision.unwrap_or(18),
220                self.storage.scale.unwrap_or(2),
221            ),
222            FieldKind::Switch => Field::boolean(name),
223            FieldKind::Radio => {
224                let values = self
225                    .options
226                    .iter()
227                    .map(|(value, _)| value.clone())
228                    .collect::<Vec<_>>();
229                if let Some(max_length) = self.storage.max_length {
230                    let unique = values.iter().collect::<BTreeSet<_>>();
231                    let longest = values
232                        .iter()
233                        .map(|value| value.chars().count())
234                        .max()
235                        .unwrap_or(0);
236                    if values.is_empty() || unique.len() != values.len() || longest > max_length {
237                        return Err(BaseError::ConfigError(format!(
238                            "VARCHAR Radio 字段 {name} 必须提供非空、不重复且不超过 {max_length} 字符的候选值"
239                        )));
240                    }
241                    let allowed = Arc::new(values);
242                    Field::string(name, max_length).validator(Validator::Custom(Arc::new(
243                        move |field_name, value| match value.as_str() {
244                            Some(value) if allowed.iter().any(|candidate| candidate == value) => {
245                                Ok(())
246                            }
247                            Some(value) => Err(BaseError::InvalidEnumValue(
248                                field_name.to_string(),
249                                value.to_string(),
250                            )),
251                            None => Err(BaseError::InvalidFieldType(
252                                field_name.to_string(),
253                                "期望字符串类型的枚举值".to_string(),
254                            )),
255                        },
256                    )))
257                } else {
258                    Field::enumeration(name, values)
259                }
260            }
261            FieldKind::Table | FieldKind::Tree => Field::bigint(name),
262            FieldKind::Timestamp => match self.timestamp_mode {
263                TimestampMode::Value => Field::timestamp(name),
264                TimestampMode::CreatedAt => Field::created_at(name),
265                TimestampMode::UpdatedAt => Field::updated_at(name),
266                TimestampMode::SoftDelete => Field::soft_delete(name),
267            },
268        };
269
270        if self.kind != FieldKind::Key && self.storage.required {
271            field = field.required();
272        }
273        if let Some(default) = self.storage.default {
274            field = field.default(default);
275        }
276        if self.storage.unique {
277            field = field.unique();
278        }
279        if self.storage.indexed {
280            field = field.index();
281        }
282        if let Some(legacy_name) = self.storage.renamed_from {
283            field = field.renamed_from(legacy_name);
284        }
285        if let Some(value) = self.validation.min_length {
286            field = field.min_length(value);
287        }
288        if let Some(value) = self.validation.max_length {
289            field = field.max_length(value);
290        }
291        if let Some(pattern) = self.validation.pattern {
292            field = field.regex(pattern);
293        }
294        if self.access.secret {
295            field = field.secret();
296        }
297        field = apply_read_rule(field, self.access.readable);
298        field = apply_write_rule(field, self.access.writable);
299        if self.access.searchable {
300            field = field.searchable();
301        }
302        // searchable、filterable 与 sortable 是独立位,各自精确映射 AccessSpec 声明;
303        // 未声明的查询能力必须显式关闭 table 层的宽松默认值(fail-closed),
304        // 保证 UI 投影与服务端 where/order 校验点对点对齐。
305        if self.access.filterable {
306            field = field.filterable();
307        } else {
308            field = field.not_filterable();
309        }
310        if self.access.sortable {
311            field = field.sortable();
312        } else {
313            field = field.not_sortable();
314        }
315        if self.tenant_key {
316            field = field.tenant_key();
317        }
318        if !self.presentation.title.is_empty() {
319            field = field.label(self.presentation.title);
320        }
321        if let Some(target) = self.relation {
322            let relation_type = if self.kind == FieldKind::Tree {
323                RelationType::OneToMany
324            } else {
325                RelationType::ManyToOne
326            };
327            field = field.relation(
328                target.table().to_string(),
329                target.field().to_string(),
330                relation_type,
331            );
332        }
333        Ok(field)
334    }
335}
336
337fn apply_read_rule(field: Field, rule: AccessRule) -> Field {
338    match rule {
339        AccessRule::Everyone => field.readable(),
340        AccessRule::Nobody => field.not_readable(),
341        AccessRule::Roles(roles) => field.readable_by(roles),
342    }
343}
344
345fn apply_write_rule(field: Field, rule: AccessRule) -> Field {
346    match rule {
347        AccessRule::Everyone => field.writable(),
348        AccessRule::Nobody => field.not_writable(),
349        AccessRule::Roles(roles) => field.writable_by(roles),
350    }
351}
352
353/// 有序、强类型字段集合。
354#[derive(Debug, Clone, PartialEq, Eq, Default)]
355pub struct Fields(Vec<FieldSpec>);
356
357impl Fields {
358    /// 创建空字段集合。
359    pub const fn new() -> Self {
360        Self(Vec::new())
361    }
362
363    /// 增加一个有名称的字段 Builder。
364    pub fn field<B>(mut self, name: FieldName, builder: B) -> Self
365    where
366        B: IntoFieldSpec,
367    {
368        self.0.push(builder.into_field_spec(name));
369        self
370    }
371
372    /// 返回字段定义。
373    pub fn as_slice(&self) -> &[FieldSpec] {
374        &self.0
375    }
376
377    pub(crate) fn into_vec(self) -> Vec<FieldSpec> {
378        self.0
379    }
380}
381
382/// 可转换为最终 FieldSpec 的类型化 Builder。
383pub trait IntoFieldSpec {
384    /// 绑定字段名并生成唯一原生定义。
385    fn into_field_spec(self, name: FieldName) -> FieldSpec;
386}
387
388#[derive(Debug, Clone)]
389struct FieldBuilder {
390    kind: FieldKind,
391    storage: StorageSpec,
392    validation: ValidationSpec,
393    access: AccessSpec,
394    presentation: PresentationSpec,
395    relation: Option<FieldRef>,
396    select: Option<ActionRef>,
397    options: Vec<(String, String)>,
398    timestamp_mode: TimestampMode,
399    tenant_key: bool,
400}
401
402impl FieldBuilder {
403    fn new(kind: FieldKind) -> Self {
404        Self {
405            kind,
406            storage: StorageSpec::default(),
407            validation: ValidationSpec::default(),
408            access: AccessSpec::default(),
409            presentation: PresentationSpec::default(),
410            relation: None,
411            select: None,
412            options: Vec::new(),
413            timestamp_mode: TimestampMode::Value,
414            tenant_key: false,
415        }
416    }
417
418    fn build(self, name: FieldName) -> FieldSpec {
419        FieldSpec {
420            name,
421            kind: self.kind,
422            storage: self.storage,
423            validation: self.validation,
424            access: self.access,
425            presentation: self.presentation,
426            relation: self.relation,
427            select: self.select,
428            options: self.options,
429            timestamp_mode: self.timestamp_mode,
430            tenant_key: self.tenant_key,
431        }
432    }
433}
434
435macro_rules! simple_builder {
436    ($name:ident, $kind:expr) => {
437        #[doc = concat!(stringify!($name), " 字段 Builder。")]
438        #[derive(Debug, Clone)]
439        pub struct $name(FieldBuilder);
440
441        impl Default for $name {
442            fn default() -> Self {
443                Self::new()
444            }
445        }
446
447        impl $name {
448            /// 创建字段 Builder。
449            pub fn new() -> Self {
450                Self(FieldBuilder::new($kind))
451            }
452
453            /// 设置展示标题。
454            pub fn title(mut self, value: impl Into<String>) -> Self {
455                self.0.presentation.title = value.into();
456                self
457            }
458
459            /// 设置帮助说明。
460            pub fn description(mut self, value: impl Into<String>) -> Self {
461                self.0.presentation.description = value.into();
462                self
463            }
464
465            /// 设置前端控件提示;不改变字段存储和权限语义。
466            pub fn widget(mut self, value: WidgetHint) -> Self {
467                self.0.presentation.widget = Some(value);
468                self
469            }
470
471            /// 设置必填。
472            pub fn require(mut self, value: bool) -> Self {
473                self.0.storage.required = value;
474                self
475            }
476
477            /// 设置数据库默认值。
478            pub fn default(mut self, value: impl Into<Value>) -> Self {
479                self.0.storage.default = Some(value.into());
480                self
481            }
482
483            /// 设置唯一索引。
484            pub fn unique(mut self, value: bool) -> Self {
485                self.0.storage.unique = value;
486                self
487            }
488
489            /// 设置普通索引。
490            pub fn indexed(mut self, value: bool) -> Self {
491                self.0.storage.indexed = value;
492                self
493            }
494
495            /// 声明当前字段由旧列原位改名而来。
496            pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
497                self.0.storage.renamed_from = Some(legacy_name.into());
498                self
499            }
500
501            /// 设置是否允许全文关键词搜索。
502            pub fn searchable(mut self, value: bool) -> Self {
503                self.0.access.searchable = value;
504                self
505            }
506
507            /// 设置是否允许结构化条件筛选。
508            pub fn filterable(mut self, value: bool) -> Self {
509                self.0.access.filterable = value;
510                self
511            }
512
513            /// 设置是否允许排序。
514            pub fn sortable(mut self, value: bool) -> Self {
515                self.0.access.sortable = value;
516                self
517            }
518
519            /// 设置敏感字段语义。
520            pub fn secret(mut self, value: bool) -> Self {
521                self.0.access.secret = value;
522                if value {
523                    self.0.access.readable = AccessRule::Nobody;
524                    self.0.access.writable = AccessRule::Nobody;
525                }
526                self
527            }
528
529            /// 设置是否可读。
530            pub fn readable(mut self, value: bool) -> Self {
531                self.0.access.readable = if value {
532                    AccessRule::Everyone
533                } else {
534                    AccessRule::Nobody
535                };
536                self
537            }
538
539            /// 限制可读角色。
540            pub fn readable_by<I, S>(mut self, roles: I) -> Self
541            where
542                I: IntoIterator<Item = S>,
543                S: Into<String>,
544            {
545                self.0.access.readable =
546                    AccessRule::Roles(roles.into_iter().map(Into::into).collect());
547                self
548            }
549
550            /// 限制可写角色。
551            pub fn writable_by<I, S>(mut self, roles: I) -> Self
552            where
553                I: IntoIterator<Item = S>,
554                S: Into<String>,
555            {
556                self.0.access.writable =
557                    AccessRule::Roles(roles.into_iter().map(Into::into).collect());
558                self
559            }
560
561            /// 标记租户隔离键。
562            pub fn tenant_key(mut self, value: bool) -> Self {
563                self.0.tenant_key = value;
564                self
565            }
566        }
567
568        impl IntoFieldSpec for $name {
569            fn into_field_spec(self, name: FieldName) -> FieldSpec {
570                self.0.build(name)
571            }
572        }
573    };
574}
575
576simple_builder!(Key, FieldKind::Key);
577simple_builder!(Str, FieldKind::Str);
578simple_builder!(Text, FieldKind::Text);
579simple_builder!(Int, FieldKind::Int);
580simple_builder!(Decimal, FieldKind::Decimal);
581simple_builder!(Switch, FieldKind::Switch);
582simple_builder!(Table, FieldKind::Table);
583simple_builder!(Tree, FieldKind::Tree);
584simple_builder!(Timestamp, FieldKind::Timestamp);
585
586/// 密码参数 Builder;默认标记 secret 且不投影为可读字段。
587#[derive(Debug, Clone)]
588pub struct Password(FieldBuilder);
589
590impl Default for Password {
591    fn default() -> Self {
592        Self::new()
593    }
594}
595
596impl Password {
597    /// 创建密码参数 Builder。
598    pub fn new() -> Self {
599        let mut inner = FieldBuilder::new(FieldKind::Str);
600        inner.access.secret = true;
601        inner.access.readable = AccessRule::Nobody;
602        inner.presentation.widget = Some(WidgetHint::Password);
603        Self(inner)
604    }
605
606    /// 设置展示标题。
607    pub fn title(mut self, value: impl Into<String>) -> Self {
608        self.0.presentation.title = value.into();
609        self
610    }
611
612    /// 设置前端控件提示;不改变密码字段的 secret 访问语义。
613    pub fn widget(mut self, value: WidgetHint) -> Self {
614        self.0.presentation.widget = Some(value);
615        self
616    }
617
618    /// 设置必填。
619    pub fn require(mut self, value: bool) -> Self {
620        self.0.storage.required = value;
621        self
622    }
623
624    /// 设置最小长度。
625    pub fn min_length(mut self, value: usize) -> Self {
626        self.0.validation.min_length = Some(value);
627        self
628    }
629
630    /// 设置最大长度。
631    pub fn max_length(mut self, value: usize) -> Self {
632        self.0.storage.max_length = Some(value);
633        self.0.validation.max_length = Some(value);
634        self
635    }
636}
637
638impl IntoFieldSpec for Password {
639    fn into_field_spec(self, name: FieldName) -> FieldSpec {
640        self.0.build(name)
641    }
642}
643
644impl Str {
645    /// 同时设置 VARCHAR 与输入校验上限。
646    pub fn max_length(mut self, value: usize) -> Self {
647        self.0.storage.max_length = Some(value);
648        self.0.validation.max_length = Some(value);
649        self
650    }
651
652    /// 设置输入最小长度。
653    pub fn min_length(mut self, value: usize) -> Self {
654        self.0.validation.min_length = Some(value);
655        self
656    }
657
658    /// 设置正则校验。
659    pub fn pattern(mut self, value: impl Into<String>) -> Self {
660        self.0.validation.pattern = Some(value.into());
661        self
662    }
663
664    /// 设置严格 ASCII 邮箱格式,并提示前端使用 email 控件。
665    pub fn email(mut self) -> Self {
666        self.0.validation.pattern =
667            Some(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
668        self.0.presentation.widget = Some(WidgetHint::Email);
669        self
670    }
671}
672
673impl Decimal {
674    /// 设置 DECIMAL 精度和小数位。
675    pub fn precision(mut self, precision: u8, scale: u8) -> Self {
676        self.0.storage.precision = Some(precision);
677        self.0.storage.scale = Some(scale);
678        self
679    }
680}
681
682impl Timestamp {
683    /// 标记为插入时自动写入的创建时间。
684    pub fn created_at(mut self) -> Self {
685        self.0.timestamp_mode = TimestampMode::CreatedAt;
686        self
687    }
688
689    /// 标记为更新时自动写入的更新时间。
690    pub fn updated_at(mut self) -> Self {
691        self.0.timestamp_mode = TimestampMode::UpdatedAt;
692        self
693    }
694
695    /// 标记为软删除时间。
696    pub fn soft_delete(mut self) -> Self {
697        self.0.timestamp_mode = TimestampMode::SoftDelete;
698        self
699    }
700}
701
702macro_rules! relation_builder {
703    ($name:ident) => {
704        impl $name {
705            /// 设置关系目标表主键。
706            pub fn target(mut self, value: FieldRef) -> Self {
707                self.0.relation = Some(value);
708                self
709            }
710
711            /// 设置默认选择器 Action。
712            pub fn select(mut self, value: ActionRef) -> Self {
713                self.0.select = Some(value);
714                self
715            }
716
717            /// 设置关系展示字段。
718            pub fn display<I>(mut self, values: I) -> Self
719            where
720                I: IntoIterator<Item = FieldRef>,
721            {
722                self.0.presentation.display = values.into_iter().collect();
723                self
724            }
725        }
726    };
727}
728
729relation_builder!(Table);
730relation_builder!(Tree);
731
732/// 保留 Rust 值类型信息的 Radio Builder;运行时 Catalog 存储稳定字符串值。
733#[derive(Debug, Clone)]
734pub struct Radio<T> {
735    inner: FieldBuilder,
736    marker: PhantomData<fn() -> T>,
737}
738
739impl<T> Default for Radio<T> {
740    fn default() -> Self {
741        Self::new()
742    }
743}
744
745impl<T> Radio<T> {
746    /// 创建 Radio Builder。
747    pub fn new() -> Self {
748        Self {
749            inner: FieldBuilder::new(FieldKind::Radio),
750            marker: PhantomData,
751        }
752    }
753
754    /// 设置展示标题。
755    pub fn title(mut self, value: impl Into<String>) -> Self {
756        self.inner.presentation.title = value.into();
757        self
758    }
759
760    /// 设置前端控件提示;不改变枚举值集合。
761    pub fn widget(mut self, value: WidgetHint) -> Self {
762        self.inner.presentation.widget = Some(value);
763        self
764    }
765
766    /// 设置必填。
767    pub fn require(mut self, value: bool) -> Self {
768        self.inner.storage.required = value;
769        self
770    }
771
772    /// 使用 VARCHAR 作为物理存储,同时保留 Radio 候选值的应用层校验。
773    ///
774    /// 适用于需要通过前向 CHECK 迁移约束既有 VARCHAR 列的场景;未调用时仍使用
775    /// 数据库原生 ENUM。`max_length` 必须覆盖所有候选值。
776    pub fn varchar(mut self, max_length: usize) -> Self {
777        self.inner.storage.max_length = Some(max_length);
778        self
779    }
780
781    /// 设置候选值和标题。
782    pub fn options<I, V, S>(mut self, values: I) -> Self
783    where
784        I: IntoIterator<Item = (V, S)>,
785        V: ToString,
786        S: Into<String>,
787    {
788        self.inner.options = values
789            .into_iter()
790            .map(|(value, title)| (value.to_string(), title.into()))
791            .collect();
792        self
793    }
794
795    /// 设置默认值。
796    pub fn default<V>(mut self, value: V) -> Self
797    where
798        V: ToString,
799    {
800        self.inner.storage.default = Some(Value::String(value.to_string()));
801        self
802    }
803
804    /// 设置是否允许结构化条件筛选。
805    pub fn filterable(mut self, value: bool) -> Self {
806        self.inner.access.filterable = value;
807        self
808    }
809
810    /// 设置是否允许排序。
811    pub fn sortable(mut self, value: bool) -> Self {
812        self.inner.access.sortable = value;
813        self
814    }
815}
816
817impl<T> IntoFieldSpec for Radio<T> {
818    fn into_field_spec(self, name: FieldName) -> FieldSpec {
819        self.inner.build(name)
820    }
821}
822
823/// 表级复合索引声明。
824#[derive(Debug, Clone, PartialEq, Eq)]
825pub struct TableIndexSpec {
826    /// 可选的显式索引名。
827    pub name: Option<String>,
828    /// 当前表中的受控字段引用。
829    pub fields: Vec<FieldRef>,
830    /// 是否为唯一索引。
831    pub unique: bool,
832}
833
834/// 表级 CHECK 约束声明。
835#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct TableCheckSpec {
837    /// 约束名。
838    pub name: String,
839    /// 受信任的 MySQL 布尔表达式。
840    pub expression: String,
841}
842
843/// 表级复合外键声明。
844#[derive(Debug, Clone, PartialEq, Eq)]
845pub struct TableForeignKeySpec {
846    /// 约束名。
847    pub name: String,
848    /// 当前表字段。
849    pub fields: Vec<FieldRef>,
850    /// 目标表字段;必须全部来自同一张表。
851    pub referenced_fields: Vec<FieldRef>,
852}
853
854/// 表及其唯一字段定义。
855#[derive(Debug, Clone, PartialEq, Eq)]
856pub struct TableSpec {
857    /// 表名。
858    pub name: TableName,
859    /// 用户可见名称。
860    pub title: String,
861    /// 字段集合。
862    pub fields: Vec<FieldSpec>,
863    /// 表级复合索引。
864    pub indexes: Vec<TableIndexSpec>,
865    /// 表级 CHECK 约束。
866    pub checks: Vec<TableCheckSpec>,
867    /// 表级外键约束。
868    pub foreign_keys: Vec<TableForeignKeySpec>,
869}
870
871impl TableSpec {
872    /// 创建空表定义。
873    pub fn new(name: TableName) -> Self {
874        Self {
875            name,
876            title: String::new(),
877            fields: Vec::new(),
878            indexes: Vec::new(),
879            checks: Vec::new(),
880            foreign_keys: Vec::new(),
881        }
882    }
883
884    /// 设置表标题。
885    pub fn title(mut self, value: impl Into<String>) -> Self {
886        self.title = value.into();
887        self
888    }
889
890    /// 使用 Fields 作为唯一字段来源。
891    pub fn fields(mut self, fields: Fields) -> Self {
892        self.fields = fields.into_vec();
893        self
894    }
895
896    /// 增加一个已经命名的字段定义。
897    #[must_use]
898    pub fn field(mut self, field: FieldSpec) -> Self {
899        self.fields.push(field);
900        self
901    }
902
903    /// 添加复合唯一索引。
904    pub fn unique(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
905        self.indexes.push(TableIndexSpec {
906            name: None,
907            fields: fields.into_iter().collect(),
908            unique: true,
909        });
910        self
911    }
912
913    /// 添加指定名称的复合唯一索引。
914    pub fn unique_named(
915        mut self,
916        name: impl Into<String>,
917        fields: impl IntoIterator<Item = FieldRef>,
918    ) -> Self {
919        self.indexes.push(TableIndexSpec {
920            name: Some(name.into()),
921            fields: fields.into_iter().collect(),
922            unique: true,
923        });
924        self
925    }
926
927    /// 添加复合普通索引。
928    pub fn index(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
929        self.indexes.push(TableIndexSpec {
930            name: None,
931            fields: fields.into_iter().collect(),
932            unique: false,
933        });
934        self
935    }
936
937    /// 添加指定名称的复合普通索引。
938    pub fn index_named(
939        mut self,
940        name: impl Into<String>,
941        fields: impl IntoIterator<Item = FieldRef>,
942    ) -> Self {
943        self.indexes.push(TableIndexSpec {
944            name: Some(name.into()),
945            fields: fields.into_iter().collect(),
946            unique: false,
947        });
948        self
949    }
950
951    /// 添加指定名称的 CHECK 约束。
952    pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
953        self.checks.push(TableCheckSpec {
954            name: name.into(),
955            expression: expression.into(),
956        });
957        self
958    }
959
960    /// 添加指定名称的复合外键;更新和删除规则固定为 `RESTRICT`。
961    pub fn foreign_key_named(
962        mut self,
963        name: impl Into<String>,
964        fields: impl IntoIterator<Item = FieldRef>,
965        referenced_fields: impl IntoIterator<Item = FieldRef>,
966    ) -> Self {
967        self.foreign_keys.push(TableForeignKeySpec {
968            name: name.into(),
969            fields: fields.into_iter().collect(),
970            referenced_fields: referenced_fields.into_iter().collect(),
971        });
972        self
973    }
974
975    /// 生成 schema 同步和 TableQuery 使用的不可变执行产物。
976    pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
977        let mut table = SchemaTable::new(self.name.to_string());
978        if !self.title.is_empty() {
979            table = table.label(self.title.clone());
980        }
981        for index in &self.indexes {
982            let fields = self.validate_index(index)?;
983            table = match (&index.name, index.unique) {
984                (Some(name), true) => table.unique_named(name.clone(), fields),
985                (None, true) => table.unique(fields),
986                (Some(name), false) => table.index_named(name.clone(), fields),
987                (None, false) => table.index(fields),
988            };
989        }
990        for check in &self.checks {
991            table = table.check_named(check.name.clone(), check.expression.clone());
992        }
993        for foreign_key in &self.foreign_keys {
994            let (columns, referenced_table, referenced_columns) =
995                self.validate_foreign_key(foreign_key)?;
996            table = table.foreign_key_named(
997                foreign_key.name.clone(),
998                columns,
999                referenced_table,
1000                referenced_columns,
1001            );
1002        }
1003        let fields = self
1004            .fields
1005            .clone()
1006            .into_iter()
1007            .map(FieldSpec::into_schema_field)
1008            .collect::<Result<Vec<_>, _>>()?;
1009        table.fields(fields).build()
1010    }
1011
1012    fn validate_index(&self, index: &TableIndexSpec) -> Result<Vec<String>, BaseError> {
1013        if index.fields.is_empty() {
1014            return Err(BaseError::ConfigError(format!(
1015                "表 {} 的复合索引至少需要一个字段",
1016                self.name
1017            )));
1018        }
1019        let declared = self
1020            .fields
1021            .iter()
1022            .map(|field| field.name.as_str())
1023            .collect::<BTreeSet<_>>();
1024        let mut seen = BTreeSet::new();
1025        let mut fields = Vec::with_capacity(index.fields.len());
1026        for reference in &index.fields {
1027            if reference.table() != &self.name {
1028                return Err(BaseError::ConfigError(format!(
1029                    "表 {} 的索引不能引用其他表字段 {}",
1030                    self.name, reference
1031                )));
1032            }
1033            let field = reference.field().as_str();
1034            if !declared.contains(field) {
1035                return Err(BaseError::ConfigError(format!(
1036                    "表 {} 的索引引用了未声明字段 {}",
1037                    self.name, field
1038                )));
1039            }
1040            if !seen.insert(field) {
1041                return Err(BaseError::ConfigError(format!(
1042                    "表 {} 的索引重复引用字段 {}",
1043                    self.name, field
1044                )));
1045            }
1046            fields.push(field.to_string());
1047        }
1048        Ok(fields)
1049    }
1050
1051    fn validate_foreign_key(
1052        &self,
1053        foreign_key: &TableForeignKeySpec,
1054    ) -> Result<(Vec<String>, String, Vec<String>), BaseError> {
1055        if foreign_key.fields.is_empty()
1056            || foreign_key.fields.len() != foreign_key.referenced_fields.len()
1057        {
1058            return Err(BaseError::ConfigError(format!(
1059                "表 {} 的外键 {} 本地字段与目标字段必须非空且数量一致",
1060                self.name, foreign_key.name
1061            )));
1062        }
1063        let declared = self
1064            .fields
1065            .iter()
1066            .map(|field| field.name.as_str())
1067            .collect::<BTreeSet<_>>();
1068        let mut columns = Vec::with_capacity(foreign_key.fields.len());
1069        for field in &foreign_key.fields {
1070            if field.table() != &self.name || !declared.contains(field.field().as_str()) {
1071                return Err(BaseError::ConfigError(format!(
1072                    "表 {} 的外键 {} 引用了未声明的本地字段 {}",
1073                    self.name, foreign_key.name, field
1074                )));
1075            }
1076            columns.push(field.field().to_string());
1077        }
1078        let referenced_table = foreign_key.referenced_fields[0].table().clone();
1079        if foreign_key
1080            .referenced_fields
1081            .iter()
1082            .any(|field| field.table() != &referenced_table)
1083        {
1084            return Err(BaseError::ConfigError(format!(
1085                "表 {} 的外键 {} 目标字段必须来自同一张表",
1086                self.name, foreign_key.name
1087            )));
1088        }
1089        Ok((
1090            columns,
1091            referenced_table.to_string(),
1092            foreign_key
1093                .referenced_fields
1094                .iter()
1095                .map(|field| field.field().to_string())
1096                .collect(),
1097        ))
1098    }
1099}