yang-base 0.6.0

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! BR 风格 Fields 定义及其原生 YANG 投影。

use super::{ActionRef, FieldKind, FieldName, FieldRef, TableName, WidgetHint};
use crate::datasource::DatasourceId;
use crate::error::BaseError;
use crate::table::{Field, RelationType, Table as SchemaTable, TableDefinition, Validator};
use serde_json::Value;
use std::collections::BTreeSet;
use std::marker::PhantomData;
use std::sync::Arc;

/// 字段的数据库存储语义。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StorageSpec {
    /// 是否允许缺失/NULL。
    pub required: bool,
    /// 字符串存储上限。
    pub max_length: Option<usize>,
    /// DECIMAL 精度。
    pub precision: Option<u8>,
    /// DECIMAL 小数位数。
    pub scale: Option<u8>,
    /// 数据库默认值。
    pub default: Option<Value>,
    /// 是否建立唯一索引。
    pub unique: bool,
    /// 是否建立普通索引。
    pub indexed: bool,
    /// 显式声明该字段由哪个旧列原位改名而来。
    pub renamed_from: Option<String>,
    /// PostgreSQL 原生枚举类型名;仅 Radio 字段可声明。
    pub native_enum: Option<String>,
}

/// 字段的输入验证语义。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ValidationSpec {
    /// 字符最小长度。
    pub min_length: Option<usize>,
    /// 字符最大长度。
    pub max_length: Option<usize>,
    /// 数值下限,使用十进制文本避免元数据中的浮点漂移。
    pub minimum: Option<String>,
    /// 数值上限,使用十进制文本避免元数据中的浮点漂移。
    pub maximum: Option<String>,
    /// 可选正则表达式。
    pub pattern: Option<String>,
}

/// 字段读写与查询权限。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessRule {
    /// 所有调用者。
    Everyone,
    /// 不允许普通调用者。
    Nobody,
    /// 仅指定角色。
    Roles(Vec<String>),
}

/// 字段的访问控制语义。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessSpec {
    /// 读取规则。
    pub readable: AccessRule,
    /// 写入规则。
    pub writable: AccessRule,
    /// 是否允许全文关键词搜索。
    pub searchable: bool,
    /// 是否允许结构化条件筛选。
    pub filterable: bool,
    /// 是否允许排序。
    pub sortable: bool,
    /// 是否为敏感字段。
    pub secret: bool,
}

impl Default for AccessSpec {
    fn default() -> Self {
        Self {
            readable: AccessRule::Everyone,
            writable: AccessRule::Everyone,
            searchable: false,
            filterable: false,
            sortable: false,
            secret: false,
        }
    }
}

/// 字段的默认展示语义。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PresentationSpec {
    /// 用户可见标题。
    pub title: String,
    /// 帮助说明。
    pub description: String,
    /// 关系字段的默认展示列。
    pub display: Vec<FieldRef>,
    /// 可选前端控件提示;不改变字段数据和权限语义。
    pub widget: Option<WidgetHint>,
}

/// 时间戳字段的自动写入语义。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimestampMode {
    /// 普通时间戳。
    Value,
    /// 插入时自动写入。
    CreatedAt,
    /// 更新时自动写入。
    UpdatedAt,
    /// 软删除标记。
    SoftDelete,
}

/// 单个字段的共享语义核心。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldSpec {
    /// 字段名。
    pub name: FieldName,
    /// 字段语义种类。
    pub kind: FieldKind,
    /// 数据库存储语义。
    pub storage: StorageSpec,
    /// 输入验证语义。
    pub validation: ValidationSpec,
    /// 访问控制语义。
    pub access: AccessSpec,
    /// 默认展示语义。
    pub presentation: PresentationSpec,
    /// 可选关系目标。
    pub relation: Option<FieldRef>,
    /// 可选选择器 Action。
    pub select: Option<ActionRef>,
    /// Radio 的值与标题。
    pub options: Vec<(String, String)>,
    /// 时间戳自动写入模式。
    pub timestamp_mode: TimestampMode,
    /// 是否为租户隔离键。
    pub tenant_key: bool,
}

impl FieldSpec {
    /// 创建最小字段定义。
    pub fn new(name: FieldName, kind: FieldKind) -> Self {
        Self {
            name,
            kind,
            storage: StorageSpec::default(),
            validation: ValidationSpec::default(),
            access: AccessSpec::default(),
            presentation: PresentationSpec::default(),
            relation: None,
            select: None,
            options: Vec::new(),
            timestamp_mode: TimestampMode::Value,
            tenant_key: false,
        }
    }

    /// 设置必填语义。
    pub fn required(mut self, required: bool) -> Self {
        self.storage.required = required;
        self
    }

    /// 返回字段是否必填。
    pub fn is_required(&self) -> bool {
        self.storage.required
    }

    /// 设置关系目标。
    pub fn relation(mut self, target: FieldRef) -> Self {
        self.relation = Some(target);
        self
    }

    /// 设置选择器 Action。
    pub fn select(mut self, action: ActionRef) -> Self {
        self.select = Some(action);
        self
    }

    /// 将字段标记为租户隔离键。
    pub fn tenant_key(mut self, tenant_key: bool) -> Self {
        self.tenant_key = tenant_key;
        self
    }

    /// 返回字段的前端控件提示。
    ///
    /// 显式 [`PresentationSpec::widget`] 优先;未设置时按字段数据语义确定性映射。
    /// secret 字符串默认使用密码控件,但该展示提示不改变服务端读写权限。
    pub fn widget_hint(&self) -> WidgetHint {
        if let Some(widget) = self.presentation.widget {
            return widget;
        }
        match self.kind {
            FieldKind::Key | FieldKind::Int => WidgetHint::Integer,
            FieldKind::Str if self.access.secret => WidgetHint::Password,
            FieldKind::Str => WidgetHint::Text,
            FieldKind::Text => WidgetHint::Textarea,
            FieldKind::Decimal => WidgetHint::Decimal,
            FieldKind::Switch => WidgetHint::Switch,
            FieldKind::Radio => WidgetHint::Radio,
            FieldKind::Table => WidgetHint::RelationSelect,
            FieldKind::Tree => WidgetHint::TreeSelect,
            FieldKind::Timestamp => WidgetHint::DateTime,
        }
    }

    fn into_schema_field(self) -> Result<Field, BaseError> {
        let name = self.name.to_string();
        let mut field = match self.kind {
            FieldKind::Key => Field::id(name),
            FieldKind::Str => Field::string(name, self.storage.max_length.unwrap_or(255)),
            FieldKind::Text => Field::text(name),
            FieldKind::Int => Field::bigint(name),
            FieldKind::Decimal => Field::decimal(
                name,
                self.storage.precision.unwrap_or(18),
                self.storage.scale.unwrap_or(2),
            ),
            FieldKind::Switch => Field::boolean(name),
            FieldKind::Radio => {
                let values = self
                    .options
                    .iter()
                    .map(|(value, _)| value.clone())
                    .collect::<Vec<_>>();
                if self.storage.native_enum.is_some() && self.storage.max_length.is_some() {
                    return Err(BaseError::ConfigError(format!(
                        "Radio 字段 {name} 不能同时声明 native_enum 与 varchar 存储"
                    )));
                }
                if let Some(max_length) = self.storage.max_length {
                    let unique = values.iter().collect::<BTreeSet<_>>();
                    let longest = values
                        .iter()
                        .map(|value| value.chars().count())
                        .max()
                        .unwrap_or(0);
                    if values.is_empty() || unique.len() != values.len() || longest > max_length {
                        return Err(BaseError::ConfigError(format!(
                            "VARCHAR Radio 字段 {name} 必须提供非空、不重复且不超过 {max_length} 字符的候选值"
                        )));
                    }
                    let allowed = Arc::new(values);
                    Field::string(name, max_length).validator(Validator::Custom(Arc::new(
                        move |field_name, value| match value.as_str() {
                            Some(value) if allowed.iter().any(|candidate| candidate == value) => {
                                Ok(())
                            }
                            Some(value) => Err(BaseError::InvalidEnumValue(
                                field_name.to_string(),
                                value.to_string(),
                            )),
                            None => Err(BaseError::InvalidFieldType(
                                field_name.to_string(),
                                "期望字符串类型的枚举值".to_string(),
                            )),
                        },
                    )))
                } else {
                    let field = Field::enumeration(name, values);
                    match self.storage.native_enum {
                        Some(type_name) => field.native_enum(type_name),
                        None => field,
                    }
                }
            }
            FieldKind::Table | FieldKind::Tree => Field::bigint(name),
            FieldKind::Timestamp => match self.timestamp_mode {
                TimestampMode::Value => Field::timestamp(name),
                TimestampMode::CreatedAt => Field::created_at(name),
                TimestampMode::UpdatedAt => Field::updated_at(name),
                TimestampMode::SoftDelete => Field::soft_delete(name),
            },
        };

        if self.kind != FieldKind::Key && self.storage.required {
            field = field.required();
        }
        if let Some(default) = self.storage.default {
            field = field.default(default);
        }
        if self.storage.unique {
            field = field.unique();
        }
        if self.storage.indexed {
            field = field.index();
        }
        if let Some(legacy_name) = self.storage.renamed_from {
            field = field.renamed_from(legacy_name);
        }
        if let Some(value) = self.validation.min_length {
            field = field.min_length(value);
        }
        if let Some(value) = self.validation.max_length {
            field = field.max_length(value);
        }
        if let Some(pattern) = self.validation.pattern {
            field = field.regex(pattern);
        }
        if let Some(value) = self.validation.minimum.as_deref() {
            field = field.min(parse_numeric_bound(self.name.as_str(), "minimum", value)?);
        }
        if let Some(value) = self.validation.maximum.as_deref() {
            field = field.max(parse_numeric_bound(self.name.as_str(), "maximum", value)?);
        }
        if self.access.secret {
            field = field.secret();
        }
        field = apply_read_rule(field, self.access.readable);
        // 服务端托管列(自增主键、自动创建/更新时间、软删标记)的 table 层
        // 构造器已声明 `not_writable`;DSL 的默认 Everyone 只代表“未显式
        // 声明”,不能把托管列重新打开为客户端可写。显式 writable_by(Roles)
        // 必须保留:yang-system 依赖系统角色写入 occurred_at 等业务时间戳。
        let managed_write_default = self.access.writable == AccessRule::Everyone
            && (self.kind == FieldKind::Key
                || (self.kind == FieldKind::Timestamp
                    && self.timestamp_mode != TimestampMode::Value));
        field = apply_write_rule(field, self.access.writable);
        if managed_write_default {
            field = field.not_writable();
        }
        if self.access.searchable {
            field = field.searchable();
        }
        // searchable、filterable 与 sortable 是独立位,各自精确映射 AccessSpec 声明;
        // 未声明的查询能力必须显式关闭 table 层的宽松默认值(fail-closed),
        // 保证 UI 投影与服务端 where/order 校验点对点对齐。
        if self.access.filterable {
            field = field.filterable();
        } else {
            field = field.not_filterable();
        }
        if self.access.sortable {
            field = field.sortable();
        } else {
            field = field.not_sortable();
        }
        if self.tenant_key {
            field = field.tenant_key();
        }
        if !self.presentation.title.is_empty() {
            field = field.label(self.presentation.title);
        }
        if let Some(target) = self.relation {
            let relation_type = if self.kind == FieldKind::Tree {
                RelationType::OneToMany
            } else {
                RelationType::ManyToOne
            };
            field = field.relation(
                target.table().to_string(),
                target.field().to_string(),
                relation_type,
            );
        }
        Ok(field)
    }
}

fn apply_read_rule(field: Field, rule: AccessRule) -> Field {
    match rule {
        AccessRule::Everyone => field.readable(),
        AccessRule::Nobody => field.not_readable(),
        AccessRule::Roles(roles) => field.readable_by(roles),
    }
}

fn apply_write_rule(field: Field, rule: AccessRule) -> Field {
    match rule {
        AccessRule::Everyone => field.writable(),
        AccessRule::Nobody => field.not_writable(),
        AccessRule::Roles(roles) => field.writable_by(roles),
    }
}

/// 把十进制文本边界解析为有限 f64;与 table 层数值校验器同语义。
fn parse_numeric_bound(name: &str, label: &str, raw: &str) -> Result<f64, BaseError> {
    let parsed = raw.trim().parse::<f64>().map_err(|_| {
        BaseError::ConfigError(format!("字段 {name} 的 {label} 必须是十进制数值: {raw:?}"))
    })?;
    if !parsed.is_finite() {
        return Err(BaseError::ConfigError(format!(
            "字段 {name} 的 {label} 必须是有限数值"
        )));
    }
    Ok(parsed)
}

/// 有序、强类型字段集合。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Fields(Vec<FieldSpec>);

impl Fields {
    /// 创建空字段集合。
    pub const fn new() -> Self {
        Self(Vec::new())
    }

    /// 增加一个有名称的字段 Builder。
    pub fn field<B>(mut self, name: FieldName, builder: B) -> Self
    where
        B: IntoFieldSpec,
    {
        self.0.push(builder.into_field_spec(name));
        self
    }

    /// 返回字段定义。
    pub fn as_slice(&self) -> &[FieldSpec] {
        &self.0
    }

    pub(crate) fn into_vec(self) -> Vec<FieldSpec> {
        self.0
    }
}

/// 可转换为最终 FieldSpec 的类型化 Builder。
pub trait IntoFieldSpec {
    /// 绑定字段名并生成唯一原生定义。
    fn into_field_spec(self, name: FieldName) -> FieldSpec;
}

#[derive(Debug, Clone)]
struct FieldBuilder {
    kind: FieldKind,
    storage: StorageSpec,
    validation: ValidationSpec,
    access: AccessSpec,
    presentation: PresentationSpec,
    relation: Option<FieldRef>,
    select: Option<ActionRef>,
    options: Vec<(String, String)>,
    timestamp_mode: TimestampMode,
    tenant_key: bool,
}

impl FieldBuilder {
    fn new(kind: FieldKind) -> Self {
        Self {
            kind,
            storage: StorageSpec::default(),
            validation: ValidationSpec::default(),
            access: AccessSpec::default(),
            presentation: PresentationSpec::default(),
            relation: None,
            select: None,
            options: Vec::new(),
            timestamp_mode: TimestampMode::Value,
            tenant_key: false,
        }
    }

    fn build(self, name: FieldName) -> FieldSpec {
        FieldSpec {
            name,
            kind: self.kind,
            storage: self.storage,
            validation: self.validation,
            access: self.access,
            presentation: self.presentation,
            relation: self.relation,
            select: self.select,
            options: self.options,
            timestamp_mode: self.timestamp_mode,
            tenant_key: self.tenant_key,
        }
    }
}

macro_rules! simple_builder {
    ($name:ident, $kind:expr) => {
        #[doc = concat!(stringify!($name), " 字段 Builder。")]
        #[derive(Debug, Clone)]
        pub struct $name(FieldBuilder);

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl $name {
            /// 创建字段 Builder。
            pub fn new() -> Self {
                Self(FieldBuilder::new($kind))
            }

            /// 设置展示标题。
            pub fn title(mut self, value: impl Into<String>) -> Self {
                self.0.presentation.title = value.into();
                self
            }

            /// 设置帮助说明。
            pub fn description(mut self, value: impl Into<String>) -> Self {
                self.0.presentation.description = value.into();
                self
            }

            /// 设置前端控件提示;不改变字段存储和权限语义。
            pub fn widget(mut self, value: WidgetHint) -> Self {
                self.0.presentation.widget = Some(value);
                self
            }

            /// 设置必填。
            pub fn require(mut self, value: bool) -> Self {
                self.0.storage.required = value;
                self
            }

            /// 设置数据库默认值。
            pub fn default(mut self, value: impl Into<Value>) -> Self {
                self.0.storage.default = Some(value.into());
                self
            }

            /// 设置唯一索引。
            pub fn unique(mut self, value: bool) -> Self {
                self.0.storage.unique = value;
                self
            }

            /// 设置普通索引。
            pub fn indexed(mut self, value: bool) -> Self {
                self.0.storage.indexed = value;
                self
            }

            /// 声明当前字段由旧列原位改名而来。
            pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
                self.0.storage.renamed_from = Some(legacy_name.into());
                self
            }

            /// 设置是否允许全文关键词搜索。
            pub fn searchable(mut self, value: bool) -> Self {
                self.0.access.searchable = value;
                self
            }

            /// 设置是否允许结构化条件筛选。
            pub fn filterable(mut self, value: bool) -> Self {
                self.0.access.filterable = value;
                self
            }

            /// 设置是否允许排序。
            pub fn sortable(mut self, value: bool) -> Self {
                self.0.access.sortable = value;
                self
            }

            /// 设置敏感字段语义。
            pub fn secret(mut self, value: bool) -> Self {
                self.0.access.secret = value;
                if value {
                    self.0.access.readable = AccessRule::Nobody;
                    self.0.access.writable = AccessRule::Nobody;
                }
                self
            }

            /// 设置是否可读。
            pub fn readable(mut self, value: bool) -> Self {
                self.0.access.readable = if value {
                    AccessRule::Everyone
                } else {
                    AccessRule::Nobody
                };
                self
            }

            /// 限制可读角色。
            pub fn readable_by<I, S>(mut self, roles: I) -> Self
            where
                I: IntoIterator<Item = S>,
                S: Into<String>,
            {
                self.0.access.readable =
                    AccessRule::Roles(roles.into_iter().map(Into::into).collect());
                self
            }

            /// 限制可写角色。
            pub fn writable_by<I, S>(mut self, roles: I) -> Self
            where
                I: IntoIterator<Item = S>,
                S: Into<String>,
            {
                self.0.access.writable =
                    AccessRule::Roles(roles.into_iter().map(Into::into).collect());
                self
            }

            /// 标记租户隔离键。
            pub fn tenant_key(mut self, value: bool) -> Self {
                self.0.tenant_key = value;
                self
            }
        }

        impl IntoFieldSpec for $name {
            fn into_field_spec(self, name: FieldName) -> FieldSpec {
                self.0.build(name)
            }
        }
    };
}

simple_builder!(Key, FieldKind::Key);
simple_builder!(Str, FieldKind::Str);
simple_builder!(Text, FieldKind::Text);
simple_builder!(Int, FieldKind::Int);
simple_builder!(Decimal, FieldKind::Decimal);
simple_builder!(Switch, FieldKind::Switch);
simple_builder!(Table, FieldKind::Table);
simple_builder!(Tree, FieldKind::Tree);
simple_builder!(Timestamp, FieldKind::Timestamp);

/// 密码参数 Builder;默认标记 secret 且不投影为可读字段。
#[derive(Debug, Clone)]
pub struct Password(FieldBuilder);

impl Default for Password {
    fn default() -> Self {
        Self::new()
    }
}

impl Password {
    /// 创建密码参数 Builder。
    pub fn new() -> Self {
        let mut inner = FieldBuilder::new(FieldKind::Str);
        inner.access.secret = true;
        inner.access.readable = AccessRule::Nobody;
        inner.presentation.widget = Some(WidgetHint::Password);
        Self(inner)
    }

    /// 设置展示标题。
    pub fn title(mut self, value: impl Into<String>) -> Self {
        self.0.presentation.title = value.into();
        self
    }

    /// 设置前端控件提示;不改变密码字段的 secret 访问语义。
    pub fn widget(mut self, value: WidgetHint) -> Self {
        self.0.presentation.widget = Some(value);
        self
    }

    /// 设置必填。
    pub fn require(mut self, value: bool) -> Self {
        self.0.storage.required = value;
        self
    }

    /// 设置最小长度。
    pub fn min_length(mut self, value: usize) -> Self {
        self.0.validation.min_length = Some(value);
        self
    }

    /// 设置最大长度。
    pub fn max_length(mut self, value: usize) -> Self {
        self.0.storage.max_length = Some(value);
        self.0.validation.max_length = Some(value);
        self
    }
}

impl IntoFieldSpec for Password {
    fn into_field_spec(self, name: FieldName) -> FieldSpec {
        self.0.build(name)
    }
}

impl Str {
    /// 同时设置 VARCHAR 与输入校验上限。
    pub fn max_length(mut self, value: usize) -> Self {
        self.0.storage.max_length = Some(value);
        self.0.validation.max_length = Some(value);
        self
    }

    /// 设置输入最小长度。
    pub fn min_length(mut self, value: usize) -> Self {
        self.0.validation.min_length = Some(value);
        self
    }

    /// 设置正则校验。
    pub fn pattern(mut self, value: impl Into<String>) -> Self {
        self.0.validation.pattern = Some(value.into());
        self
    }

    /// 设置严格 ASCII 邮箱格式,并提示前端使用 email 控件。
    pub fn email(mut self) -> Self {
        self.0.validation.pattern =
            Some(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
        self.0.presentation.widget = Some(WidgetHint::Email);
        self
    }
}

impl Decimal {
    /// 设置 DECIMAL 精度和小数位。
    pub fn precision(mut self, precision: u8, scale: u8) -> Self {
        self.0.storage.precision = Some(precision);
        self.0.storage.scale = Some(scale);
        self
    }
}

impl Timestamp {
    /// 标记为插入时自动写入的创建时间。
    pub fn created_at(mut self) -> Self {
        self.0.timestamp_mode = TimestampMode::CreatedAt;
        self
    }

    /// 标记为更新时自动写入的更新时间。
    pub fn updated_at(mut self) -> Self {
        self.0.timestamp_mode = TimestampMode::UpdatedAt;
        self
    }

    /// 标记为软删除时间。
    pub fn soft_delete(mut self) -> Self {
        self.0.timestamp_mode = TimestampMode::SoftDelete;
        self
    }
}

macro_rules! relation_builder {
    ($name:ident) => {
        impl $name {
            /// 设置关系目标表主键。
            pub fn target(mut self, value: FieldRef) -> Self {
                self.0.relation = Some(value);
                self
            }

            /// 设置默认选择器 Action。
            pub fn select(mut self, value: ActionRef) -> Self {
                self.0.select = Some(value);
                self
            }

            /// 设置关系展示字段。
            pub fn display<I>(mut self, values: I) -> Self
            where
                I: IntoIterator<Item = FieldRef>,
            {
                self.0.presentation.display = values.into_iter().collect();
                self
            }
        }
    };
}

relation_builder!(Table);
relation_builder!(Tree);

/// 保留 Rust 值类型信息的 Radio Builder;运行时 Catalog 存储稳定字符串值。
#[derive(Debug, Clone)]
pub struct Radio<T> {
    inner: FieldBuilder,
    marker: PhantomData<fn() -> T>,
}

impl<T> Default for Radio<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Radio<T> {
    /// 创建 Radio Builder。
    pub fn new() -> Self {
        Self {
            inner: FieldBuilder::new(FieldKind::Radio),
            marker: PhantomData,
        }
    }

    /// 设置展示标题。
    pub fn title(mut self, value: impl Into<String>) -> Self {
        self.inner.presentation.title = value.into();
        self
    }

    /// 设置前端控件提示;不改变枚举值集合。
    pub fn widget(mut self, value: WidgetHint) -> Self {
        self.inner.presentation.widget = Some(value);
        self
    }

    /// 设置必填。
    pub fn require(mut self, value: bool) -> Self {
        self.inner.storage.required = value;
        self
    }

    /// 使用 VARCHAR 作为物理存储,同时保留 Radio 候选值的应用层校验。
    ///
    /// 适用于需要通过前向 CHECK 迁移约束既有 VARCHAR 列的场景;未调用时仍使用
    /// 数据库原生 ENUM。`max_length` 必须覆盖所有候选值。
    pub fn varchar(mut self, max_length: usize) -> Self {
        self.inner.storage.max_length = Some(max_length);
        self
    }

    /// 复用 PostgreSQL 原生枚举类型(`CREATE TYPE ... AS ENUM`)。
    ///
    /// 与 [`Self::varchar`] 互斥;MySQL 方言在渲染 DDL 时明确拒绝。声明后
    /// PostgreSQL 不再生成隐式 `VARCHAR + CHECK`,而是直接使用该枚举类型。
    pub fn native_enum(mut self, type_name: impl Into<String>) -> Self {
        self.inner.storage.native_enum = Some(type_name.into());
        self
    }

    /// 设置候选值和标题。
    pub fn options<I, V, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = (V, S)>,
        V: ToString,
        S: Into<String>,
    {
        self.inner.options = values
            .into_iter()
            .map(|(value, title)| (value.to_string(), title.into()))
            .collect();
        self
    }

    /// 设置默认值。
    pub fn default<V>(mut self, value: V) -> Self
    where
        V: ToString,
    {
        self.inner.storage.default = Some(Value::String(value.to_string()));
        self
    }

    /// 设置是否允许结构化条件筛选。
    pub fn filterable(mut self, value: bool) -> Self {
        self.inner.access.filterable = value;
        self
    }

    /// 设置是否允许排序。
    pub fn sortable(mut self, value: bool) -> Self {
        self.inner.access.sortable = value;
        self
    }
}

impl<T> IntoFieldSpec for Radio<T> {
    fn into_field_spec(self, name: FieldName) -> FieldSpec {
        self.inner.build(name)
    }
}

/// 表级复合索引声明。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableIndexSpec {
    /// 可选的显式索引名。
    pub name: Option<String>,
    /// 当前表中的受控字段引用。
    pub fields: Vec<FieldRef>,
    /// 表达式键(已校验的受信 SQL)。
    pub expressions: Vec<String>,
    /// PostgreSQL 部分索引谓词(`WHERE ...`)。
    pub predicate: Option<String>,
    /// 是否为唯一索引。
    pub unique: bool,
}

/// 表级 CHECK 约束声明。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableCheckSpec {
    /// 约束名。
    pub name: String,
    /// 受信任的 MySQL 布尔表达式。
    pub expression: String,
}

/// 表级复合外键声明。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableForeignKeySpec {
    /// 约束名。
    pub name: String,
    /// 当前表字段。
    pub fields: Vec<FieldRef>,
    /// 目标表字段;必须全部来自同一张表。
    pub referenced_fields: Vec<FieldRef>,
}

/// 表级 opaque 列声明(仅 PostgreSQL)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableOpaqueColumnSpec {
    /// 列名。
    pub name: String,
    /// 期望的 `format_type` 文本。
    pub sql_type: String,
}

/// 表及其唯一字段定义。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSpec {
    /// 表名。
    pub name: TableName,
    /// 用户可见名称。
    pub title: String,
    /// 字段集合。
    pub fields: Vec<FieldSpec>,
    /// 表级复合索引。
    pub indexes: Vec<TableIndexSpec>,
    /// 表级 CHECK 约束。
    pub checks: Vec<TableCheckSpec>,
    /// 表级外键约束。
    pub foreign_keys: Vec<TableForeignKeySpec>,
    /// 框架不建模的存量列(仅 PostgreSQL)。
    pub opaque_columns: Vec<TableOpaqueColumnSpec>,
    /// 表所属逻辑数据源;`None` 表示使用模块/默认数据源。
    pub datasource: Option<DatasourceId>,
    /// 主键列声明顺序(构建期用于抵消字段排序)。
    pub(crate) primary_key_order: Vec<String>,
}

impl TableSpec {
    /// 创建空表定义。
    pub fn new(name: TableName) -> Self {
        Self {
            name,
            title: String::new(),
            fields: Vec::new(),
            indexes: Vec::new(),
            checks: Vec::new(),
            foreign_keys: Vec::new(),
            opaque_columns: Vec::new(),
            datasource: None,
            primary_key_order: Vec::new(),
        }
    }

    /// 设置表标题。
    pub fn title(mut self, value: impl Into<String>) -> Self {
        self.title = value.into();
        self
    }

    /// 设置表所属逻辑数据源。
    pub fn datasource(mut self, id: DatasourceId) -> Self {
        self.datasource = Some(id);
        self
    }

    /// 使用 Fields 作为唯一字段来源。
    pub fn fields(mut self, fields: Fields) -> Self {
        self.fields = fields.into_vec();
        self.primary_key_order = self
            .fields
            .iter()
            .filter(|field| field.kind == FieldKind::Key)
            .map(|field| field.name.to_string())
            .collect();
        self
    }

    /// 增加一个已经命名的字段定义。
    #[must_use]
    pub fn field(mut self, field: FieldSpec) -> Self {
        if field.kind == FieldKind::Key {
            self.primary_key_order.push(field.name.to_string());
        }
        self.fields.push(field);
        self
    }

    /// 添加复合唯一索引。
    pub fn unique(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
        self.indexes.push(TableIndexSpec {
            name: None,
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: None,
            unique: true,
        });
        self
    }

    /// 添加指定名称的复合唯一索引。
    pub fn unique_named(
        mut self,
        name: impl Into<String>,
        fields: impl IntoIterator<Item = FieldRef>,
    ) -> Self {
        self.indexes.push(TableIndexSpec {
            name: Some(name.into()),
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: None,
            unique: true,
        });
        self
    }

    /// 添加复合普通索引。
    pub fn index(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
        self.indexes.push(TableIndexSpec {
            name: None,
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: None,
            unique: false,
        });
        self
    }

    /// 添加指定名称的复合普通索引。
    pub fn index_named(
        mut self,
        name: impl Into<String>,
        fields: impl IntoIterator<Item = FieldRef>,
    ) -> Self {
        self.indexes.push(TableIndexSpec {
            name: Some(name.into()),
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: None,
            unique: false,
        });
        self
    }

    /// 添加带 `WHERE` 谓词的 PostgreSQL 部分索引。
    pub fn partial_index(
        mut self,
        name: impl Into<String>,
        fields: impl IntoIterator<Item = FieldRef>,
        predicate: impl Into<String>,
    ) -> Self {
        self.indexes.push(TableIndexSpec {
            name: Some(name.into()),
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: Some(predicate.into()),
            unique: false,
        });
        self
    }

    /// 添加带 `WHERE` 谓词的 PostgreSQL 部分唯一索引。
    pub fn partial_unique_named(
        mut self,
        name: impl Into<String>,
        fields: impl IntoIterator<Item = FieldRef>,
        predicate: impl Into<String>,
    ) -> Self {
        self.indexes.push(TableIndexSpec {
            name: Some(name.into()),
            fields: fields.into_iter().collect(),
            expressions: Vec::new(),
            predicate: Some(predicate.into()),
            unique: true,
        });
        self
    }

    /// 添加表达式索引(如 `lower(email)`)。
    pub fn expression_index(
        mut self,
        name: impl Into<String>,
        expressions: impl IntoIterator<Item = impl Into<String>>,
        unique: bool,
    ) -> Self {
        self.indexes.push(TableIndexSpec {
            name: Some(name.into()),
            fields: Vec::new(),
            expressions: expressions.into_iter().map(Into::into).collect(),
            predicate: None,
            unique,
        });
        self
    }

    /// 添加指定名称的 CHECK 约束。
    pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
        self.checks.push(TableCheckSpec {
            name: name.into(),
            expression: expression.into(),
        });
        self
    }

    /// 添加指定名称的复合外键;更新和删除规则固定为 `RESTRICT`。
    pub fn foreign_key_named(
        mut self,
        name: impl Into<String>,
        fields: impl IntoIterator<Item = FieldRef>,
        referenced_fields: impl IntoIterator<Item = FieldRef>,
    ) -> Self {
        self.foreign_keys.push(TableForeignKeySpec {
            name: name.into(),
            fields: fields.into_iter().collect(),
            referenced_fields: referenced_fields.into_iter().collect(),
        });
        self
    }

    /// 声明一个框架不建模的存量列(仅 PostgreSQL)。
    pub fn opaque_column(mut self, name: impl Into<String>, sql_type: impl Into<String>) -> Self {
        self.opaque_columns.push(TableOpaqueColumnSpec {
            name: name.into(),
            sql_type: sql_type.into(),
        });
        self
    }

    /// 生成 schema 同步和 TableQuery 使用的不可变执行产物。
    pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
        let mut table = SchemaTable::new(self.name.to_string());
        table = table
            .datasource(self.datasource.clone().unwrap_or_default())
            .primary_key_order(self.primary_key_order.clone());
        for opaque in &self.opaque_columns {
            table = table.opaque_column(opaque.name.clone(), opaque.sql_type.clone());
        }
        if !self.title.is_empty() {
            table = table.label(self.title.clone());
        }
        for index in &self.indexes {
            let fields = self.validate_index(index)?;
            if !index.expressions.is_empty() || index.predicate.is_some() {
                table = table.index_spec(
                    index.name.clone(),
                    fields,
                    index.expressions.clone(),
                    index.predicate.clone(),
                    index.unique,
                    false,
                );
                continue;
            }
            table = match (&index.name, index.unique) {
                (Some(name), true) => table.unique_named(name.clone(), fields),
                (None, true) => table.unique(fields),
                (Some(name), false) => table.index_named(name.clone(), fields),
                (None, false) => table.index(fields),
            };
        }
        for check in &self.checks {
            table = table.check_named(check.name.clone(), check.expression.clone());
        }
        for foreign_key in &self.foreign_keys {
            let (columns, referenced_table, referenced_columns) =
                self.validate_foreign_key(foreign_key)?;
            table = table.foreign_key_named(
                foreign_key.name.clone(),
                columns,
                referenced_table,
                referenced_columns,
            );
        }
        let fields = self
            .fields
            .clone()
            .into_iter()
            .map(FieldSpec::into_schema_field)
            .collect::<Result<Vec<_>, _>>()?;
        table.fields(fields).build()
    }

    fn validate_index(&self, index: &TableIndexSpec) -> Result<Vec<String>, BaseError> {
        if index.fields.is_empty() && index.expressions.is_empty() {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的索引至少需要一个字段或表达式",
                self.name
            )));
        }
        if !index.expressions.is_empty() && index.name.is_none() {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的表达式索引必须显式声明名称",
                self.name
            )));
        }
        let declared = self
            .fields
            .iter()
            .map(|field| field.name.as_str())
            .collect::<BTreeSet<_>>();
        let mut seen = BTreeSet::new();
        let mut fields = Vec::with_capacity(index.fields.len());
        for reference in &index.fields {
            if reference.table() != &self.name {
                return Err(BaseError::ConfigError(format!(
                    "表 {} 的索引不能引用其他表字段 {}",
                    self.name, reference
                )));
            }
            let field = reference.field().as_str();
            if !declared.contains(field) {
                return Err(BaseError::ConfigError(format!(
                    "表 {} 的索引引用了未声明字段 {}",
                    self.name, field
                )));
            }
            if !seen.insert(field) {
                return Err(BaseError::ConfigError(format!(
                    "表 {} 的索引重复引用字段 {}",
                    self.name, field
                )));
            }
            fields.push(field.to_string());
        }
        Ok(fields)
    }

    fn validate_foreign_key(
        &self,
        foreign_key: &TableForeignKeySpec,
    ) -> Result<(Vec<String>, String, Vec<String>), BaseError> {
        if foreign_key.fields.is_empty()
            || foreign_key.fields.len() != foreign_key.referenced_fields.len()
        {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的外键 {} 本地字段与目标字段必须非空且数量一致",
                self.name, foreign_key.name
            )));
        }
        let declared = self
            .fields
            .iter()
            .map(|field| field.name.as_str())
            .collect::<BTreeSet<_>>();
        let mut columns = Vec::with_capacity(foreign_key.fields.len());
        for field in &foreign_key.fields {
            if field.table() != &self.name || !declared.contains(field.field().as_str()) {
                return Err(BaseError::ConfigError(format!(
                    "表 {} 的外键 {} 引用了未声明的本地字段 {}",
                    self.name, foreign_key.name, field
                )));
            }
            columns.push(field.field().to_string());
        }
        let referenced_table = foreign_key.referenced_fields[0].table().clone();
        if foreign_key
            .referenced_fields
            .iter()
            .any(|field| field.table() != &referenced_table)
        {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的外键 {} 目标字段必须来自同一张表",
                self.name, foreign_key.name
            )));
        }
        Ok((
            columns,
            referenced_table.to_string(),
            foreign_key
                .referenced_fields
                .iter()
                .map(|field| field.field().to_string())
                .collect(),
        ))
    }
}