yang-base 0.2.1

个人使用构建后端服务器
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
//! BR 风格 Fields 定义及其原生 YANG 投影。

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

/// 字段的数据库存储语义。
#[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,
}

/// 字段的输入验证语义。
#[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 => {
                Field::enumeration(name, self.options.iter().map(|(value, _)| value.clone()))
            }
            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(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 self.access.secret {
            field = field.secret();
        }
        field = apply_read_rule(field, self.access.readable);
        field = apply_write_rule(field, self.access.writable);
        if self.access.searchable {
            field = field.searchable();
        }
        // searchable 与 filterable 是独立位,各自精确映射 AccessSpec 声明;
        // 未声明 filterable 必须显式关闭 table 层的宽松默认值(fail-closed),
        // 保证 UI 投影的 filter_fields 与服务端 where 校验点对点对齐。
        if self.access.filterable {
            field = field.filterable();
        } else {
            field = field.not_filterable();
        }
        if self.access.sortable {
            field = field.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),
    }
}

/// 有序、强类型字段集合。
#[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 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
    }
}

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
    }

    /// 设置候选值和标题。
    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>,
    /// 是否为唯一索引。
    pub unique: bool,
}

/// 表及其唯一字段定义。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSpec {
    /// 表名。
    pub name: TableName,
    /// 用户可见名称。
    pub title: String,
    /// 字段集合。
    pub fields: Vec<FieldSpec>,
    /// 表级复合索引。
    pub indexes: Vec<TableIndexSpec>,
}

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

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

    /// 使用 Fields 作为唯一字段来源。
    pub fn fields(mut self, fields: Fields) -> Self {
        self.fields = fields.into_vec();
        self
    }

    /// 增加一个已经命名的字段定义。
    #[must_use]
    pub fn field(mut self, field: FieldSpec) -> Self {
        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(),
            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(),
            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(),
            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(),
            unique: false,
        });
        self
    }

    /// 生成 schema 同步和 TableQuery 使用的不可变执行产物。
    pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
        let mut table = SchemaTable::new(self.name.to_string());
        if !self.title.is_empty() {
            table = table.label(self.title.clone());
        }
        for index in &self.indexes {
            let fields = self.validate_index(index)?;
            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),
            };
        }
        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() {
            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)
    }
}