1use super::{ActionRef, FieldKind, FieldName, FieldRef, TableName, WidgetHint};
4use crate::error::BaseError;
5use crate::table::{Field, RelationType, Table as SchemaTable, TableDefinition, Validator};
6use serde_json::Value;
7use std::collections::BTreeSet;
8use std::marker::PhantomData;
9use std::sync::Arc;
10
11#[derive(Debug, Clone, PartialEq, Eq, Default)]
13pub struct StorageSpec {
14 pub required: bool,
16 pub max_length: Option<usize>,
18 pub precision: Option<u8>,
20 pub scale: Option<u8>,
22 pub default: Option<Value>,
24 pub unique: bool,
26 pub indexed: bool,
28 pub renamed_from: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Default)]
34pub struct ValidationSpec {
35 pub min_length: Option<usize>,
37 pub max_length: Option<usize>,
39 pub minimum: Option<String>,
41 pub maximum: Option<String>,
43 pub pattern: Option<String>,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum AccessRule {
50 Everyone,
52 Nobody,
54 Roles(Vec<String>),
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct AccessSpec {
61 pub readable: AccessRule,
63 pub writable: AccessRule,
65 pub searchable: bool,
67 pub filterable: bool,
69 pub sortable: bool,
71 pub secret: bool,
73}
74
75impl Default for AccessSpec {
76 fn default() -> Self {
77 Self {
78 readable: AccessRule::Everyone,
79 writable: AccessRule::Everyone,
80 searchable: false,
81 filterable: false,
82 sortable: false,
83 secret: false,
84 }
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Default)]
90pub struct PresentationSpec {
91 pub title: String,
93 pub description: String,
95 pub display: Vec<FieldRef>,
97 pub widget: Option<WidgetHint>,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum TimestampMode {
104 Value,
106 CreatedAt,
108 UpdatedAt,
110 SoftDelete,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct FieldSpec {
117 pub name: FieldName,
119 pub kind: FieldKind,
121 pub storage: StorageSpec,
123 pub validation: ValidationSpec,
125 pub access: AccessSpec,
127 pub presentation: PresentationSpec,
129 pub relation: Option<FieldRef>,
131 pub select: Option<ActionRef>,
133 pub options: Vec<(String, String)>,
135 pub timestamp_mode: TimestampMode,
137 pub tenant_key: bool,
139}
140
141impl FieldSpec {
142 pub fn new(name: FieldName, kind: FieldKind) -> Self {
144 Self {
145 name,
146 kind,
147 storage: StorageSpec::default(),
148 validation: ValidationSpec::default(),
149 access: AccessSpec::default(),
150 presentation: PresentationSpec::default(),
151 relation: None,
152 select: None,
153 options: Vec::new(),
154 timestamp_mode: TimestampMode::Value,
155 tenant_key: false,
156 }
157 }
158
159 pub fn required(mut self, required: bool) -> Self {
161 self.storage.required = required;
162 self
163 }
164
165 pub fn is_required(&self) -> bool {
167 self.storage.required
168 }
169
170 pub fn relation(mut self, target: FieldRef) -> Self {
172 self.relation = Some(target);
173 self
174 }
175
176 pub fn select(mut self, action: ActionRef) -> Self {
178 self.select = Some(action);
179 self
180 }
181
182 pub fn tenant_key(mut self, tenant_key: bool) -> Self {
184 self.tenant_key = tenant_key;
185 self
186 }
187
188 pub fn widget_hint(&self) -> WidgetHint {
193 if let Some(widget) = self.presentation.widget {
194 return widget;
195 }
196 match self.kind {
197 FieldKind::Key | FieldKind::Int => WidgetHint::Integer,
198 FieldKind::Str if self.access.secret => WidgetHint::Password,
199 FieldKind::Str => WidgetHint::Text,
200 FieldKind::Text => WidgetHint::Textarea,
201 FieldKind::Decimal => WidgetHint::Decimal,
202 FieldKind::Switch => WidgetHint::Switch,
203 FieldKind::Radio => WidgetHint::Radio,
204 FieldKind::Table => WidgetHint::RelationSelect,
205 FieldKind::Tree => WidgetHint::TreeSelect,
206 FieldKind::Timestamp => WidgetHint::DateTime,
207 }
208 }
209
210 fn into_schema_field(self) -> Result<Field, BaseError> {
211 let name = self.name.to_string();
212 let mut field = match self.kind {
213 FieldKind::Key => Field::id(name),
214 FieldKind::Str => Field::string(name, self.storage.max_length.unwrap_or(255)),
215 FieldKind::Text => Field::text(name),
216 FieldKind::Int => Field::bigint(name),
217 FieldKind::Decimal => Field::decimal(
218 name,
219 self.storage.precision.unwrap_or(18),
220 self.storage.scale.unwrap_or(2),
221 ),
222 FieldKind::Switch => Field::boolean(name),
223 FieldKind::Radio => {
224 let values = self
225 .options
226 .iter()
227 .map(|(value, _)| value.clone())
228 .collect::<Vec<_>>();
229 if let Some(max_length) = self.storage.max_length {
230 let unique = values.iter().collect::<BTreeSet<_>>();
231 let longest = values
232 .iter()
233 .map(|value| value.chars().count())
234 .max()
235 .unwrap_or(0);
236 if values.is_empty() || unique.len() != values.len() || longest > max_length {
237 return Err(BaseError::ConfigError(format!(
238 "VARCHAR Radio 字段 {name} 必须提供非空、不重复且不超过 {max_length} 字符的候选值"
239 )));
240 }
241 let allowed = Arc::new(values);
242 Field::string(name, max_length).validator(Validator::Custom(Arc::new(
243 move |field_name, value| match value.as_str() {
244 Some(value) if allowed.iter().any(|candidate| candidate == value) => {
245 Ok(())
246 }
247 Some(value) => Err(BaseError::InvalidEnumValue(
248 field_name.to_string(),
249 value.to_string(),
250 )),
251 None => Err(BaseError::InvalidFieldType(
252 field_name.to_string(),
253 "期望字符串类型的枚举值".to_string(),
254 )),
255 },
256 )))
257 } else {
258 Field::enumeration(name, values)
259 }
260 }
261 FieldKind::Table | FieldKind::Tree => Field::bigint(name),
262 FieldKind::Timestamp => match self.timestamp_mode {
263 TimestampMode::Value => Field::timestamp(name),
264 TimestampMode::CreatedAt => Field::created_at(name),
265 TimestampMode::UpdatedAt => Field::updated_at(name),
266 TimestampMode::SoftDelete => Field::soft_delete(name),
267 },
268 };
269
270 if self.kind != FieldKind::Key && self.storage.required {
271 field = field.required();
272 }
273 if let Some(default) = self.storage.default {
274 field = field.default(default);
275 }
276 if self.storage.unique {
277 field = field.unique();
278 }
279 if self.storage.indexed {
280 field = field.index();
281 }
282 if let Some(legacy_name) = self.storage.renamed_from {
283 field = field.renamed_from(legacy_name);
284 }
285 if let Some(value) = self.validation.min_length {
286 field = field.min_length(value);
287 }
288 if let Some(value) = self.validation.max_length {
289 field = field.max_length(value);
290 }
291 if let Some(pattern) = self.validation.pattern {
292 field = field.regex(pattern);
293 }
294 if self.access.secret {
295 field = field.secret();
296 }
297 field = apply_read_rule(field, self.access.readable);
298 field = apply_write_rule(field, self.access.writable);
299 if self.access.searchable {
300 field = field.searchable();
301 }
302 if self.access.filterable {
306 field = field.filterable();
307 } else {
308 field = field.not_filterable();
309 }
310 if self.access.sortable {
311 field = field.sortable();
312 } else {
313 field = field.not_sortable();
314 }
315 if self.tenant_key {
316 field = field.tenant_key();
317 }
318 if !self.presentation.title.is_empty() {
319 field = field.label(self.presentation.title);
320 }
321 if let Some(target) = self.relation {
322 let relation_type = if self.kind == FieldKind::Tree {
323 RelationType::OneToMany
324 } else {
325 RelationType::ManyToOne
326 };
327 field = field.relation(
328 target.table().to_string(),
329 target.field().to_string(),
330 relation_type,
331 );
332 }
333 Ok(field)
334 }
335}
336
337fn apply_read_rule(field: Field, rule: AccessRule) -> Field {
338 match rule {
339 AccessRule::Everyone => field.readable(),
340 AccessRule::Nobody => field.not_readable(),
341 AccessRule::Roles(roles) => field.readable_by(roles),
342 }
343}
344
345fn apply_write_rule(field: Field, rule: AccessRule) -> Field {
346 match rule {
347 AccessRule::Everyone => field.writable(),
348 AccessRule::Nobody => field.not_writable(),
349 AccessRule::Roles(roles) => field.writable_by(roles),
350 }
351}
352
353#[derive(Debug, Clone, PartialEq, Eq, Default)]
355pub struct Fields(Vec<FieldSpec>);
356
357impl Fields {
358 pub const fn new() -> Self {
360 Self(Vec::new())
361 }
362
363 pub fn field<B>(mut self, name: FieldName, builder: B) -> Self
365 where
366 B: IntoFieldSpec,
367 {
368 self.0.push(builder.into_field_spec(name));
369 self
370 }
371
372 pub fn as_slice(&self) -> &[FieldSpec] {
374 &self.0
375 }
376
377 pub(crate) fn into_vec(self) -> Vec<FieldSpec> {
378 self.0
379 }
380}
381
382pub trait IntoFieldSpec {
384 fn into_field_spec(self, name: FieldName) -> FieldSpec;
386}
387
388#[derive(Debug, Clone)]
389struct FieldBuilder {
390 kind: FieldKind,
391 storage: StorageSpec,
392 validation: ValidationSpec,
393 access: AccessSpec,
394 presentation: PresentationSpec,
395 relation: Option<FieldRef>,
396 select: Option<ActionRef>,
397 options: Vec<(String, String)>,
398 timestamp_mode: TimestampMode,
399 tenant_key: bool,
400}
401
402impl FieldBuilder {
403 fn new(kind: FieldKind) -> Self {
404 Self {
405 kind,
406 storage: StorageSpec::default(),
407 validation: ValidationSpec::default(),
408 access: AccessSpec::default(),
409 presentation: PresentationSpec::default(),
410 relation: None,
411 select: None,
412 options: Vec::new(),
413 timestamp_mode: TimestampMode::Value,
414 tenant_key: false,
415 }
416 }
417
418 fn build(self, name: FieldName) -> FieldSpec {
419 FieldSpec {
420 name,
421 kind: self.kind,
422 storage: self.storage,
423 validation: self.validation,
424 access: self.access,
425 presentation: self.presentation,
426 relation: self.relation,
427 select: self.select,
428 options: self.options,
429 timestamp_mode: self.timestamp_mode,
430 tenant_key: self.tenant_key,
431 }
432 }
433}
434
435macro_rules! simple_builder {
436 ($name:ident, $kind:expr) => {
437 #[doc = concat!(stringify!($name), " 字段 Builder。")]
438 #[derive(Debug, Clone)]
439 pub struct $name(FieldBuilder);
440
441 impl Default for $name {
442 fn default() -> Self {
443 Self::new()
444 }
445 }
446
447 impl $name {
448 pub fn new() -> Self {
450 Self(FieldBuilder::new($kind))
451 }
452
453 pub fn title(mut self, value: impl Into<String>) -> Self {
455 self.0.presentation.title = value.into();
456 self
457 }
458
459 pub fn description(mut self, value: impl Into<String>) -> Self {
461 self.0.presentation.description = value.into();
462 self
463 }
464
465 pub fn widget(mut self, value: WidgetHint) -> Self {
467 self.0.presentation.widget = Some(value);
468 self
469 }
470
471 pub fn require(mut self, value: bool) -> Self {
473 self.0.storage.required = value;
474 self
475 }
476
477 pub fn default(mut self, value: impl Into<Value>) -> Self {
479 self.0.storage.default = Some(value.into());
480 self
481 }
482
483 pub fn unique(mut self, value: bool) -> Self {
485 self.0.storage.unique = value;
486 self
487 }
488
489 pub fn indexed(mut self, value: bool) -> Self {
491 self.0.storage.indexed = value;
492 self
493 }
494
495 pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
497 self.0.storage.renamed_from = Some(legacy_name.into());
498 self
499 }
500
501 pub fn searchable(mut self, value: bool) -> Self {
503 self.0.access.searchable = value;
504 self
505 }
506
507 pub fn filterable(mut self, value: bool) -> Self {
509 self.0.access.filterable = value;
510 self
511 }
512
513 pub fn sortable(mut self, value: bool) -> Self {
515 self.0.access.sortable = value;
516 self
517 }
518
519 pub fn secret(mut self, value: bool) -> Self {
521 self.0.access.secret = value;
522 if value {
523 self.0.access.readable = AccessRule::Nobody;
524 self.0.access.writable = AccessRule::Nobody;
525 }
526 self
527 }
528
529 pub fn readable(mut self, value: bool) -> Self {
531 self.0.access.readable = if value {
532 AccessRule::Everyone
533 } else {
534 AccessRule::Nobody
535 };
536 self
537 }
538
539 pub fn readable_by<I, S>(mut self, roles: I) -> Self
541 where
542 I: IntoIterator<Item = S>,
543 S: Into<String>,
544 {
545 self.0.access.readable =
546 AccessRule::Roles(roles.into_iter().map(Into::into).collect());
547 self
548 }
549
550 pub fn writable_by<I, S>(mut self, roles: I) -> Self
552 where
553 I: IntoIterator<Item = S>,
554 S: Into<String>,
555 {
556 self.0.access.writable =
557 AccessRule::Roles(roles.into_iter().map(Into::into).collect());
558 self
559 }
560
561 pub fn tenant_key(mut self, value: bool) -> Self {
563 self.0.tenant_key = value;
564 self
565 }
566 }
567
568 impl IntoFieldSpec for $name {
569 fn into_field_spec(self, name: FieldName) -> FieldSpec {
570 self.0.build(name)
571 }
572 }
573 };
574}
575
576simple_builder!(Key, FieldKind::Key);
577simple_builder!(Str, FieldKind::Str);
578simple_builder!(Text, FieldKind::Text);
579simple_builder!(Int, FieldKind::Int);
580simple_builder!(Decimal, FieldKind::Decimal);
581simple_builder!(Switch, FieldKind::Switch);
582simple_builder!(Table, FieldKind::Table);
583simple_builder!(Tree, FieldKind::Tree);
584simple_builder!(Timestamp, FieldKind::Timestamp);
585
586#[derive(Debug, Clone)]
588pub struct Password(FieldBuilder);
589
590impl Default for Password {
591 fn default() -> Self {
592 Self::new()
593 }
594}
595
596impl Password {
597 pub fn new() -> Self {
599 let mut inner = FieldBuilder::new(FieldKind::Str);
600 inner.access.secret = true;
601 inner.access.readable = AccessRule::Nobody;
602 inner.presentation.widget = Some(WidgetHint::Password);
603 Self(inner)
604 }
605
606 pub fn title(mut self, value: impl Into<String>) -> Self {
608 self.0.presentation.title = value.into();
609 self
610 }
611
612 pub fn widget(mut self, value: WidgetHint) -> Self {
614 self.0.presentation.widget = Some(value);
615 self
616 }
617
618 pub fn require(mut self, value: bool) -> Self {
620 self.0.storage.required = value;
621 self
622 }
623
624 pub fn min_length(mut self, value: usize) -> Self {
626 self.0.validation.min_length = Some(value);
627 self
628 }
629
630 pub fn max_length(mut self, value: usize) -> Self {
632 self.0.storage.max_length = Some(value);
633 self.0.validation.max_length = Some(value);
634 self
635 }
636}
637
638impl IntoFieldSpec for Password {
639 fn into_field_spec(self, name: FieldName) -> FieldSpec {
640 self.0.build(name)
641 }
642}
643
644impl Str {
645 pub fn max_length(mut self, value: usize) -> Self {
647 self.0.storage.max_length = Some(value);
648 self.0.validation.max_length = Some(value);
649 self
650 }
651
652 pub fn min_length(mut self, value: usize) -> Self {
654 self.0.validation.min_length = Some(value);
655 self
656 }
657
658 pub fn pattern(mut self, value: impl Into<String>) -> Self {
660 self.0.validation.pattern = Some(value.into());
661 self
662 }
663
664 pub fn email(mut self) -> Self {
666 self.0.validation.pattern =
667 Some(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
668 self.0.presentation.widget = Some(WidgetHint::Email);
669 self
670 }
671}
672
673impl Decimal {
674 pub fn precision(mut self, precision: u8, scale: u8) -> Self {
676 self.0.storage.precision = Some(precision);
677 self.0.storage.scale = Some(scale);
678 self
679 }
680}
681
682impl Timestamp {
683 pub fn created_at(mut self) -> Self {
685 self.0.timestamp_mode = TimestampMode::CreatedAt;
686 self
687 }
688
689 pub fn updated_at(mut self) -> Self {
691 self.0.timestamp_mode = TimestampMode::UpdatedAt;
692 self
693 }
694
695 pub fn soft_delete(mut self) -> Self {
697 self.0.timestamp_mode = TimestampMode::SoftDelete;
698 self
699 }
700}
701
702macro_rules! relation_builder {
703 ($name:ident) => {
704 impl $name {
705 pub fn target(mut self, value: FieldRef) -> Self {
707 self.0.relation = Some(value);
708 self
709 }
710
711 pub fn select(mut self, value: ActionRef) -> Self {
713 self.0.select = Some(value);
714 self
715 }
716
717 pub fn display<I>(mut self, values: I) -> Self
719 where
720 I: IntoIterator<Item = FieldRef>,
721 {
722 self.0.presentation.display = values.into_iter().collect();
723 self
724 }
725 }
726 };
727}
728
729relation_builder!(Table);
730relation_builder!(Tree);
731
732#[derive(Debug, Clone)]
734pub struct Radio<T> {
735 inner: FieldBuilder,
736 marker: PhantomData<fn() -> T>,
737}
738
739impl<T> Default for Radio<T> {
740 fn default() -> Self {
741 Self::new()
742 }
743}
744
745impl<T> Radio<T> {
746 pub fn new() -> Self {
748 Self {
749 inner: FieldBuilder::new(FieldKind::Radio),
750 marker: PhantomData,
751 }
752 }
753
754 pub fn title(mut self, value: impl Into<String>) -> Self {
756 self.inner.presentation.title = value.into();
757 self
758 }
759
760 pub fn widget(mut self, value: WidgetHint) -> Self {
762 self.inner.presentation.widget = Some(value);
763 self
764 }
765
766 pub fn require(mut self, value: bool) -> Self {
768 self.inner.storage.required = value;
769 self
770 }
771
772 pub fn varchar(mut self, max_length: usize) -> Self {
777 self.inner.storage.max_length = Some(max_length);
778 self
779 }
780
781 pub fn options<I, V, S>(mut self, values: I) -> Self
783 where
784 I: IntoIterator<Item = (V, S)>,
785 V: ToString,
786 S: Into<String>,
787 {
788 self.inner.options = values
789 .into_iter()
790 .map(|(value, title)| (value.to_string(), title.into()))
791 .collect();
792 self
793 }
794
795 pub fn default<V>(mut self, value: V) -> Self
797 where
798 V: ToString,
799 {
800 self.inner.storage.default = Some(Value::String(value.to_string()));
801 self
802 }
803
804 pub fn filterable(mut self, value: bool) -> Self {
806 self.inner.access.filterable = value;
807 self
808 }
809
810 pub fn sortable(mut self, value: bool) -> Self {
812 self.inner.access.sortable = value;
813 self
814 }
815}
816
817impl<T> IntoFieldSpec for Radio<T> {
818 fn into_field_spec(self, name: FieldName) -> FieldSpec {
819 self.inner.build(name)
820 }
821}
822
823#[derive(Debug, Clone, PartialEq, Eq)]
825pub struct TableIndexSpec {
826 pub name: Option<String>,
828 pub fields: Vec<FieldRef>,
830 pub unique: bool,
832}
833
834#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct TableCheckSpec {
837 pub name: String,
839 pub expression: String,
841}
842
843#[derive(Debug, Clone, PartialEq, Eq)]
845pub struct TableForeignKeySpec {
846 pub name: String,
848 pub fields: Vec<FieldRef>,
850 pub referenced_fields: Vec<FieldRef>,
852}
853
854#[derive(Debug, Clone, PartialEq, Eq)]
856pub struct TableSpec {
857 pub name: TableName,
859 pub title: String,
861 pub fields: Vec<FieldSpec>,
863 pub indexes: Vec<TableIndexSpec>,
865 pub checks: Vec<TableCheckSpec>,
867 pub foreign_keys: Vec<TableForeignKeySpec>,
869}
870
871impl TableSpec {
872 pub fn new(name: TableName) -> Self {
874 Self {
875 name,
876 title: String::new(),
877 fields: Vec::new(),
878 indexes: Vec::new(),
879 checks: Vec::new(),
880 foreign_keys: Vec::new(),
881 }
882 }
883
884 pub fn title(mut self, value: impl Into<String>) -> Self {
886 self.title = value.into();
887 self
888 }
889
890 pub fn fields(mut self, fields: Fields) -> Self {
892 self.fields = fields.into_vec();
893 self
894 }
895
896 #[must_use]
898 pub fn field(mut self, field: FieldSpec) -> Self {
899 self.fields.push(field);
900 self
901 }
902
903 pub fn unique(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
905 self.indexes.push(TableIndexSpec {
906 name: None,
907 fields: fields.into_iter().collect(),
908 unique: true,
909 });
910 self
911 }
912
913 pub fn unique_named(
915 mut self,
916 name: impl Into<String>,
917 fields: impl IntoIterator<Item = FieldRef>,
918 ) -> Self {
919 self.indexes.push(TableIndexSpec {
920 name: Some(name.into()),
921 fields: fields.into_iter().collect(),
922 unique: true,
923 });
924 self
925 }
926
927 pub fn index(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
929 self.indexes.push(TableIndexSpec {
930 name: None,
931 fields: fields.into_iter().collect(),
932 unique: false,
933 });
934 self
935 }
936
937 pub fn index_named(
939 mut self,
940 name: impl Into<String>,
941 fields: impl IntoIterator<Item = FieldRef>,
942 ) -> Self {
943 self.indexes.push(TableIndexSpec {
944 name: Some(name.into()),
945 fields: fields.into_iter().collect(),
946 unique: false,
947 });
948 self
949 }
950
951 pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
953 self.checks.push(TableCheckSpec {
954 name: name.into(),
955 expression: expression.into(),
956 });
957 self
958 }
959
960 pub fn foreign_key_named(
962 mut self,
963 name: impl Into<String>,
964 fields: impl IntoIterator<Item = FieldRef>,
965 referenced_fields: impl IntoIterator<Item = FieldRef>,
966 ) -> Self {
967 self.foreign_keys.push(TableForeignKeySpec {
968 name: name.into(),
969 fields: fields.into_iter().collect(),
970 referenced_fields: referenced_fields.into_iter().collect(),
971 });
972 self
973 }
974
975 pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
977 let mut table = SchemaTable::new(self.name.to_string());
978 if !self.title.is_empty() {
979 table = table.label(self.title.clone());
980 }
981 for index in &self.indexes {
982 let fields = self.validate_index(index)?;
983 table = match (&index.name, index.unique) {
984 (Some(name), true) => table.unique_named(name.clone(), fields),
985 (None, true) => table.unique(fields),
986 (Some(name), false) => table.index_named(name.clone(), fields),
987 (None, false) => table.index(fields),
988 };
989 }
990 for check in &self.checks {
991 table = table.check_named(check.name.clone(), check.expression.clone());
992 }
993 for foreign_key in &self.foreign_keys {
994 let (columns, referenced_table, referenced_columns) =
995 self.validate_foreign_key(foreign_key)?;
996 table = table.foreign_key_named(
997 foreign_key.name.clone(),
998 columns,
999 referenced_table,
1000 referenced_columns,
1001 );
1002 }
1003 let fields = self
1004 .fields
1005 .clone()
1006 .into_iter()
1007 .map(FieldSpec::into_schema_field)
1008 .collect::<Result<Vec<_>, _>>()?;
1009 table.fields(fields).build()
1010 }
1011
1012 fn validate_index(&self, index: &TableIndexSpec) -> Result<Vec<String>, BaseError> {
1013 if index.fields.is_empty() {
1014 return Err(BaseError::ConfigError(format!(
1015 "表 {} 的复合索引至少需要一个字段",
1016 self.name
1017 )));
1018 }
1019 let declared = self
1020 .fields
1021 .iter()
1022 .map(|field| field.name.as_str())
1023 .collect::<BTreeSet<_>>();
1024 let mut seen = BTreeSet::new();
1025 let mut fields = Vec::with_capacity(index.fields.len());
1026 for reference in &index.fields {
1027 if reference.table() != &self.name {
1028 return Err(BaseError::ConfigError(format!(
1029 "表 {} 的索引不能引用其他表字段 {}",
1030 self.name, reference
1031 )));
1032 }
1033 let field = reference.field().as_str();
1034 if !declared.contains(field) {
1035 return Err(BaseError::ConfigError(format!(
1036 "表 {} 的索引引用了未声明字段 {}",
1037 self.name, field
1038 )));
1039 }
1040 if !seen.insert(field) {
1041 return Err(BaseError::ConfigError(format!(
1042 "表 {} 的索引重复引用字段 {}",
1043 self.name, field
1044 )));
1045 }
1046 fields.push(field.to_string());
1047 }
1048 Ok(fields)
1049 }
1050
1051 fn validate_foreign_key(
1052 &self,
1053 foreign_key: &TableForeignKeySpec,
1054 ) -> Result<(Vec<String>, String, Vec<String>), BaseError> {
1055 if foreign_key.fields.is_empty()
1056 || foreign_key.fields.len() != foreign_key.referenced_fields.len()
1057 {
1058 return Err(BaseError::ConfigError(format!(
1059 "表 {} 的外键 {} 本地字段与目标字段必须非空且数量一致",
1060 self.name, foreign_key.name
1061 )));
1062 }
1063 let declared = self
1064 .fields
1065 .iter()
1066 .map(|field| field.name.as_str())
1067 .collect::<BTreeSet<_>>();
1068 let mut columns = Vec::with_capacity(foreign_key.fields.len());
1069 for field in &foreign_key.fields {
1070 if field.table() != &self.name || !declared.contains(field.field().as_str()) {
1071 return Err(BaseError::ConfigError(format!(
1072 "表 {} 的外键 {} 引用了未声明的本地字段 {}",
1073 self.name, foreign_key.name, field
1074 )));
1075 }
1076 columns.push(field.field().to_string());
1077 }
1078 let referenced_table = foreign_key.referenced_fields[0].table().clone();
1079 if foreign_key
1080 .referenced_fields
1081 .iter()
1082 .any(|field| field.table() != &referenced_table)
1083 {
1084 return Err(BaseError::ConfigError(format!(
1085 "表 {} 的外键 {} 目标字段必须来自同一张表",
1086 self.name, foreign_key.name
1087 )));
1088 }
1089 Ok((
1090 columns,
1091 referenced_table.to_string(),
1092 foreign_key
1093 .referenced_fields
1094 .iter()
1095 .map(|field| field.field().to_string())
1096 .collect(),
1097 ))
1098 }
1099}