Skip to main content

yang_base/definition/
field.rs

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