1use super::{ActionRef, FieldKind, FieldName, FieldRef, TableName, WidgetHint};
4use crate::datasource::DatasourceId;
5use crate::error::BaseError;
6use crate::table::{Field, RelationType, Table as SchemaTable, TableDefinition, Validator};
7use serde_json::Value;
8use std::collections::BTreeSet;
9use std::marker::PhantomData;
10use std::sync::Arc;
11
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
14pub struct StorageSpec {
15 pub required: bool,
17 pub max_length: Option<usize>,
19 pub precision: Option<u8>,
21 pub scale: Option<u8>,
23 pub default: Option<Value>,
25 pub unique: bool,
27 pub indexed: bool,
29 pub renamed_from: Option<String>,
31 pub native_enum: Option<String>,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
37pub struct ValidationSpec {
38 pub min_length: Option<usize>,
40 pub max_length: Option<usize>,
42 pub minimum: Option<String>,
44 pub maximum: Option<String>,
46 pub pattern: Option<String>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum AccessRule {
53 Everyone,
55 Nobody,
57 Roles(Vec<String>),
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct AccessSpec {
64 pub readable: AccessRule,
66 pub writable: AccessRule,
68 pub searchable: bool,
70 pub filterable: bool,
72 pub sortable: bool,
74 pub secret: bool,
76}
77
78impl Default for AccessSpec {
79 fn default() -> Self {
80 Self {
81 readable: AccessRule::Everyone,
82 writable: AccessRule::Everyone,
83 searchable: false,
84 filterable: false,
85 sortable: false,
86 secret: false,
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Default)]
93pub struct PresentationSpec {
94 pub title: String,
96 pub description: String,
98 pub display: Vec<FieldRef>,
100 pub widget: Option<WidgetHint>,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum TimestampMode {
107 Value,
109 CreatedAt,
111 UpdatedAt,
113 SoftDelete,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct FieldSpec {
120 pub name: FieldName,
122 pub kind: FieldKind,
124 pub storage: StorageSpec,
126 pub validation: ValidationSpec,
128 pub access: AccessSpec,
130 pub presentation: PresentationSpec,
132 pub relation: Option<FieldRef>,
134 pub select: Option<ActionRef>,
136 pub options: Vec<(String, String)>,
138 pub timestamp_mode: TimestampMode,
140 pub tenant_key: bool,
142}
143
144impl FieldSpec {
145 pub fn new(name: FieldName, kind: FieldKind) -> Self {
147 Self {
148 name,
149 kind,
150 storage: StorageSpec::default(),
151 validation: ValidationSpec::default(),
152 access: AccessSpec::default(),
153 presentation: PresentationSpec::default(),
154 relation: None,
155 select: None,
156 options: Vec::new(),
157 timestamp_mode: TimestampMode::Value,
158 tenant_key: false,
159 }
160 }
161
162 pub fn required(mut self, required: bool) -> Self {
164 self.storage.required = required;
165 self
166 }
167
168 pub fn is_required(&self) -> bool {
170 self.storage.required
171 }
172
173 pub fn relation(mut self, target: FieldRef) -> Self {
175 self.relation = Some(target);
176 self
177 }
178
179 pub fn select(mut self, action: ActionRef) -> Self {
181 self.select = Some(action);
182 self
183 }
184
185 pub fn tenant_key(mut self, tenant_key: bool) -> Self {
187 self.tenant_key = tenant_key;
188 self
189 }
190
191 pub fn widget_hint(&self) -> WidgetHint {
196 if let Some(widget) = self.presentation.widget {
197 return widget;
198 }
199 match self.kind {
200 FieldKind::Key | FieldKind::Int => WidgetHint::Integer,
201 FieldKind::Str if self.access.secret => WidgetHint::Password,
202 FieldKind::Str => WidgetHint::Text,
203 FieldKind::Text => WidgetHint::Textarea,
204 FieldKind::Decimal => WidgetHint::Decimal,
205 FieldKind::Switch => WidgetHint::Switch,
206 FieldKind::Radio => WidgetHint::Radio,
207 FieldKind::Table => WidgetHint::RelationSelect,
208 FieldKind::Tree => WidgetHint::TreeSelect,
209 FieldKind::Timestamp => WidgetHint::DateTime,
210 }
211 }
212
213 fn into_schema_field(self) -> Result<Field, BaseError> {
214 let name = self.name.to_string();
215 let mut field = match self.kind {
216 FieldKind::Key => Field::id(name),
217 FieldKind::Str => Field::string(name, self.storage.max_length.unwrap_or(255)),
218 FieldKind::Text => Field::text(name),
219 FieldKind::Int => Field::bigint(name),
220 FieldKind::Decimal => Field::decimal(
221 name,
222 self.storage.precision.unwrap_or(18),
223 self.storage.scale.unwrap_or(2),
224 ),
225 FieldKind::Switch => Field::boolean(name),
226 FieldKind::Radio => {
227 let values = self
228 .options
229 .iter()
230 .map(|(value, _)| value.clone())
231 .collect::<Vec<_>>();
232 if self.storage.native_enum.is_some() && self.storage.max_length.is_some() {
233 return Err(BaseError::ConfigError(format!(
234 "Radio 字段 {name} 不能同时声明 native_enum 与 varchar 存储"
235 )));
236 }
237 if let Some(max_length) = self.storage.max_length {
238 let unique = values.iter().collect::<BTreeSet<_>>();
239 let longest = values
240 .iter()
241 .map(|value| value.chars().count())
242 .max()
243 .unwrap_or(0);
244 if values.is_empty() || unique.len() != values.len() || longest > max_length {
245 return Err(BaseError::ConfigError(format!(
246 "VARCHAR Radio 字段 {name} 必须提供非空、不重复且不超过 {max_length} 字符的候选值"
247 )));
248 }
249 let allowed = Arc::new(values);
250 Field::string(name, max_length).validator(Validator::Custom(Arc::new(
251 move |field_name, value| match value.as_str() {
252 Some(value) if allowed.iter().any(|candidate| candidate == value) => {
253 Ok(())
254 }
255 Some(value) => Err(BaseError::InvalidEnumValue(
256 field_name.to_string(),
257 value.to_string(),
258 )),
259 None => Err(BaseError::InvalidFieldType(
260 field_name.to_string(),
261 "期望字符串类型的枚举值".to_string(),
262 )),
263 },
264 )))
265 } else {
266 let field = Field::enumeration(name, values);
267 match self.storage.native_enum {
268 Some(type_name) => field.native_enum(type_name),
269 None => field,
270 }
271 }
272 }
273 FieldKind::Table | FieldKind::Tree => Field::bigint(name),
274 FieldKind::Timestamp => match self.timestamp_mode {
275 TimestampMode::Value => Field::timestamp(name),
276 TimestampMode::CreatedAt => Field::created_at(name),
277 TimestampMode::UpdatedAt => Field::updated_at(name),
278 TimestampMode::SoftDelete => Field::soft_delete(name),
279 },
280 };
281
282 if self.kind != FieldKind::Key && self.storage.required {
283 field = field.required();
284 }
285 if let Some(default) = self.storage.default {
286 field = field.default(default);
287 }
288 if self.storage.unique {
289 field = field.unique();
290 }
291 if self.storage.indexed {
292 field = field.index();
293 }
294 if let Some(legacy_name) = self.storage.renamed_from {
295 field = field.renamed_from(legacy_name);
296 }
297 if let Some(value) = self.validation.min_length {
298 field = field.min_length(value);
299 }
300 if let Some(value) = self.validation.max_length {
301 field = field.max_length(value);
302 }
303 if let Some(pattern) = self.validation.pattern {
304 field = field.regex(pattern);
305 }
306 if let Some(value) = self.validation.minimum.as_deref() {
307 field = field.min(parse_numeric_bound(self.name.as_str(), "minimum", value)?);
308 }
309 if let Some(value) = self.validation.maximum.as_deref() {
310 field = field.max(parse_numeric_bound(self.name.as_str(), "maximum", value)?);
311 }
312 if self.access.secret {
313 field = field.secret();
314 }
315 field = apply_read_rule(field, self.access.readable);
316 let managed_write_default = self.access.writable == AccessRule::Everyone
321 && (self.kind == FieldKind::Key
322 || (self.kind == FieldKind::Timestamp
323 && self.timestamp_mode != TimestampMode::Value));
324 field = apply_write_rule(field, self.access.writable);
325 if managed_write_default {
326 field = field.not_writable();
327 }
328 if self.access.searchable {
329 field = field.searchable();
330 }
331 if self.access.filterable {
335 field = field.filterable();
336 } else {
337 field = field.not_filterable();
338 }
339 if self.access.sortable {
340 field = field.sortable();
341 } else {
342 field = field.not_sortable();
343 }
344 if self.tenant_key {
345 field = field.tenant_key();
346 }
347 if !self.presentation.title.is_empty() {
348 field = field.label(self.presentation.title);
349 }
350 if let Some(target) = self.relation {
351 let relation_type = if self.kind == FieldKind::Tree {
352 RelationType::OneToMany
353 } else {
354 RelationType::ManyToOne
355 };
356 field = field.relation(
357 target.table().to_string(),
358 target.field().to_string(),
359 relation_type,
360 );
361 }
362 Ok(field)
363 }
364}
365
366fn apply_read_rule(field: Field, rule: AccessRule) -> Field {
367 match rule {
368 AccessRule::Everyone => field.readable(),
369 AccessRule::Nobody => field.not_readable(),
370 AccessRule::Roles(roles) => field.readable_by(roles),
371 }
372}
373
374fn apply_write_rule(field: Field, rule: AccessRule) -> Field {
375 match rule {
376 AccessRule::Everyone => field.writable(),
377 AccessRule::Nobody => field.not_writable(),
378 AccessRule::Roles(roles) => field.writable_by(roles),
379 }
380}
381
382fn parse_numeric_bound(name: &str, label: &str, raw: &str) -> Result<f64, BaseError> {
384 let parsed = raw.trim().parse::<f64>().map_err(|_| {
385 BaseError::ConfigError(format!("字段 {name} 的 {label} 必须是十进制数值: {raw:?}"))
386 })?;
387 if !parsed.is_finite() {
388 return Err(BaseError::ConfigError(format!(
389 "字段 {name} 的 {label} 必须是有限数值"
390 )));
391 }
392 Ok(parsed)
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Default)]
397pub struct Fields(Vec<FieldSpec>);
398
399impl Fields {
400 pub const fn new() -> Self {
402 Self(Vec::new())
403 }
404
405 pub fn field<B>(mut self, name: FieldName, builder: B) -> Self
407 where
408 B: IntoFieldSpec,
409 {
410 self.0.push(builder.into_field_spec(name));
411 self
412 }
413
414 pub fn as_slice(&self) -> &[FieldSpec] {
416 &self.0
417 }
418
419 pub(crate) fn into_vec(self) -> Vec<FieldSpec> {
420 self.0
421 }
422}
423
424pub trait IntoFieldSpec {
426 fn into_field_spec(self, name: FieldName) -> FieldSpec;
428}
429
430#[derive(Debug, Clone)]
431struct FieldBuilder {
432 kind: FieldKind,
433 storage: StorageSpec,
434 validation: ValidationSpec,
435 access: AccessSpec,
436 presentation: PresentationSpec,
437 relation: Option<FieldRef>,
438 select: Option<ActionRef>,
439 options: Vec<(String, String)>,
440 timestamp_mode: TimestampMode,
441 tenant_key: bool,
442}
443
444impl FieldBuilder {
445 fn new(kind: FieldKind) -> Self {
446 Self {
447 kind,
448 storage: StorageSpec::default(),
449 validation: ValidationSpec::default(),
450 access: AccessSpec::default(),
451 presentation: PresentationSpec::default(),
452 relation: None,
453 select: None,
454 options: Vec::new(),
455 timestamp_mode: TimestampMode::Value,
456 tenant_key: false,
457 }
458 }
459
460 fn build(self, name: FieldName) -> FieldSpec {
461 FieldSpec {
462 name,
463 kind: self.kind,
464 storage: self.storage,
465 validation: self.validation,
466 access: self.access,
467 presentation: self.presentation,
468 relation: self.relation,
469 select: self.select,
470 options: self.options,
471 timestamp_mode: self.timestamp_mode,
472 tenant_key: self.tenant_key,
473 }
474 }
475}
476
477macro_rules! simple_builder {
478 ($name:ident, $kind:expr) => {
479 #[doc = concat!(stringify!($name), " 字段 Builder。")]
480 #[derive(Debug, Clone)]
481 pub struct $name(FieldBuilder);
482
483 impl Default for $name {
484 fn default() -> Self {
485 Self::new()
486 }
487 }
488
489 impl $name {
490 pub fn new() -> Self {
492 Self(FieldBuilder::new($kind))
493 }
494
495 pub fn title(mut self, value: impl Into<String>) -> Self {
497 self.0.presentation.title = value.into();
498 self
499 }
500
501 pub fn description(mut self, value: impl Into<String>) -> Self {
503 self.0.presentation.description = value.into();
504 self
505 }
506
507 pub fn widget(mut self, value: WidgetHint) -> Self {
509 self.0.presentation.widget = Some(value);
510 self
511 }
512
513 pub fn require(mut self, value: bool) -> Self {
515 self.0.storage.required = value;
516 self
517 }
518
519 pub fn default(mut self, value: impl Into<Value>) -> Self {
521 self.0.storage.default = Some(value.into());
522 self
523 }
524
525 pub fn unique(mut self, value: bool) -> Self {
527 self.0.storage.unique = value;
528 self
529 }
530
531 pub fn indexed(mut self, value: bool) -> Self {
533 self.0.storage.indexed = value;
534 self
535 }
536
537 pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
539 self.0.storage.renamed_from = Some(legacy_name.into());
540 self
541 }
542
543 pub fn searchable(mut self, value: bool) -> Self {
545 self.0.access.searchable = value;
546 self
547 }
548
549 pub fn filterable(mut self, value: bool) -> Self {
551 self.0.access.filterable = value;
552 self
553 }
554
555 pub fn sortable(mut self, value: bool) -> Self {
557 self.0.access.sortable = value;
558 self
559 }
560
561 pub fn secret(mut self, value: bool) -> Self {
563 self.0.access.secret = value;
564 if value {
565 self.0.access.readable = AccessRule::Nobody;
566 self.0.access.writable = AccessRule::Nobody;
567 }
568 self
569 }
570
571 pub fn readable(mut self, value: bool) -> Self {
573 self.0.access.readable = if value {
574 AccessRule::Everyone
575 } else {
576 AccessRule::Nobody
577 };
578 self
579 }
580
581 pub fn readable_by<I, S>(mut self, roles: I) -> Self
583 where
584 I: IntoIterator<Item = S>,
585 S: Into<String>,
586 {
587 self.0.access.readable =
588 AccessRule::Roles(roles.into_iter().map(Into::into).collect());
589 self
590 }
591
592 pub fn writable_by<I, S>(mut self, roles: I) -> Self
594 where
595 I: IntoIterator<Item = S>,
596 S: Into<String>,
597 {
598 self.0.access.writable =
599 AccessRule::Roles(roles.into_iter().map(Into::into).collect());
600 self
601 }
602
603 pub fn tenant_key(mut self, value: bool) -> Self {
605 self.0.tenant_key = value;
606 self
607 }
608 }
609
610 impl IntoFieldSpec for $name {
611 fn into_field_spec(self, name: FieldName) -> FieldSpec {
612 self.0.build(name)
613 }
614 }
615 };
616}
617
618simple_builder!(Key, FieldKind::Key);
619simple_builder!(Str, FieldKind::Str);
620simple_builder!(Text, FieldKind::Text);
621simple_builder!(Int, FieldKind::Int);
622simple_builder!(Decimal, FieldKind::Decimal);
623simple_builder!(Switch, FieldKind::Switch);
624simple_builder!(Table, FieldKind::Table);
625simple_builder!(Tree, FieldKind::Tree);
626simple_builder!(Timestamp, FieldKind::Timestamp);
627
628#[derive(Debug, Clone)]
630pub struct Password(FieldBuilder);
631
632impl Default for Password {
633 fn default() -> Self {
634 Self::new()
635 }
636}
637
638impl Password {
639 pub fn new() -> Self {
641 let mut inner = FieldBuilder::new(FieldKind::Str);
642 inner.access.secret = true;
643 inner.access.readable = AccessRule::Nobody;
644 inner.presentation.widget = Some(WidgetHint::Password);
645 Self(inner)
646 }
647
648 pub fn title(mut self, value: impl Into<String>) -> Self {
650 self.0.presentation.title = value.into();
651 self
652 }
653
654 pub fn widget(mut self, value: WidgetHint) -> Self {
656 self.0.presentation.widget = Some(value);
657 self
658 }
659
660 pub fn require(mut self, value: bool) -> Self {
662 self.0.storage.required = value;
663 self
664 }
665
666 pub fn min_length(mut self, value: usize) -> Self {
668 self.0.validation.min_length = Some(value);
669 self
670 }
671
672 pub fn max_length(mut self, value: usize) -> Self {
674 self.0.storage.max_length = Some(value);
675 self.0.validation.max_length = Some(value);
676 self
677 }
678}
679
680impl IntoFieldSpec for Password {
681 fn into_field_spec(self, name: FieldName) -> FieldSpec {
682 self.0.build(name)
683 }
684}
685
686impl Str {
687 pub fn max_length(mut self, value: usize) -> Self {
689 self.0.storage.max_length = Some(value);
690 self.0.validation.max_length = Some(value);
691 self
692 }
693
694 pub fn min_length(mut self, value: usize) -> Self {
696 self.0.validation.min_length = Some(value);
697 self
698 }
699
700 pub fn pattern(mut self, value: impl Into<String>) -> Self {
702 self.0.validation.pattern = Some(value.into());
703 self
704 }
705
706 pub fn email(mut self) -> Self {
708 self.0.validation.pattern =
709 Some(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
710 self.0.presentation.widget = Some(WidgetHint::Email);
711 self
712 }
713}
714
715impl Decimal {
716 pub fn precision(mut self, precision: u8, scale: u8) -> Self {
718 self.0.storage.precision = Some(precision);
719 self.0.storage.scale = Some(scale);
720 self
721 }
722}
723
724impl Timestamp {
725 pub fn created_at(mut self) -> Self {
727 self.0.timestamp_mode = TimestampMode::CreatedAt;
728 self
729 }
730
731 pub fn updated_at(mut self) -> Self {
733 self.0.timestamp_mode = TimestampMode::UpdatedAt;
734 self
735 }
736
737 pub fn soft_delete(mut self) -> Self {
739 self.0.timestamp_mode = TimestampMode::SoftDelete;
740 self
741 }
742}
743
744macro_rules! relation_builder {
745 ($name:ident) => {
746 impl $name {
747 pub fn target(mut self, value: FieldRef) -> Self {
749 self.0.relation = Some(value);
750 self
751 }
752
753 pub fn select(mut self, value: ActionRef) -> Self {
755 self.0.select = Some(value);
756 self
757 }
758
759 pub fn display<I>(mut self, values: I) -> Self
761 where
762 I: IntoIterator<Item = FieldRef>,
763 {
764 self.0.presentation.display = values.into_iter().collect();
765 self
766 }
767 }
768 };
769}
770
771relation_builder!(Table);
772relation_builder!(Tree);
773
774#[derive(Debug, Clone)]
776pub struct Radio<T> {
777 inner: FieldBuilder,
778 marker: PhantomData<fn() -> T>,
779}
780
781impl<T> Default for Radio<T> {
782 fn default() -> Self {
783 Self::new()
784 }
785}
786
787impl<T> Radio<T> {
788 pub fn new() -> Self {
790 Self {
791 inner: FieldBuilder::new(FieldKind::Radio),
792 marker: PhantomData,
793 }
794 }
795
796 pub fn title(mut self, value: impl Into<String>) -> Self {
798 self.inner.presentation.title = value.into();
799 self
800 }
801
802 pub fn widget(mut self, value: WidgetHint) -> Self {
804 self.inner.presentation.widget = Some(value);
805 self
806 }
807
808 pub fn require(mut self, value: bool) -> Self {
810 self.inner.storage.required = value;
811 self
812 }
813
814 pub fn varchar(mut self, max_length: usize) -> Self {
819 self.inner.storage.max_length = Some(max_length);
820 self
821 }
822
823 pub fn native_enum(mut self, type_name: impl Into<String>) -> Self {
828 self.inner.storage.native_enum = Some(type_name.into());
829 self
830 }
831
832 pub fn options<I, V, S>(mut self, values: I) -> Self
834 where
835 I: IntoIterator<Item = (V, S)>,
836 V: ToString,
837 S: Into<String>,
838 {
839 self.inner.options = values
840 .into_iter()
841 .map(|(value, title)| (value.to_string(), title.into()))
842 .collect();
843 self
844 }
845
846 pub fn default<V>(mut self, value: V) -> Self
848 where
849 V: ToString,
850 {
851 self.inner.storage.default = Some(Value::String(value.to_string()));
852 self
853 }
854
855 pub fn filterable(mut self, value: bool) -> Self {
857 self.inner.access.filterable = value;
858 self
859 }
860
861 pub fn sortable(mut self, value: bool) -> Self {
863 self.inner.access.sortable = value;
864 self
865 }
866}
867
868impl<T> IntoFieldSpec for Radio<T> {
869 fn into_field_spec(self, name: FieldName) -> FieldSpec {
870 self.inner.build(name)
871 }
872}
873
874#[derive(Debug, Clone, PartialEq, Eq)]
876pub struct TableIndexSpec {
877 pub name: Option<String>,
879 pub fields: Vec<FieldRef>,
881 pub expressions: Vec<String>,
883 pub predicate: Option<String>,
885 pub unique: bool,
887}
888
889#[derive(Debug, Clone, PartialEq, Eq)]
891pub struct TableCheckSpec {
892 pub name: String,
894 pub expression: String,
896}
897
898#[derive(Debug, Clone, PartialEq, Eq)]
900pub struct TableForeignKeySpec {
901 pub name: String,
903 pub fields: Vec<FieldRef>,
905 pub referenced_fields: Vec<FieldRef>,
907}
908
909#[derive(Debug, Clone, PartialEq, Eq)]
911pub struct TableOpaqueColumnSpec {
912 pub name: String,
914 pub sql_type: String,
916}
917
918#[derive(Debug, Clone, PartialEq, Eq)]
920pub struct TableSpec {
921 pub name: TableName,
923 pub title: String,
925 pub fields: Vec<FieldSpec>,
927 pub indexes: Vec<TableIndexSpec>,
929 pub checks: Vec<TableCheckSpec>,
931 pub foreign_keys: Vec<TableForeignKeySpec>,
933 pub opaque_columns: Vec<TableOpaqueColumnSpec>,
935 pub datasource: Option<DatasourceId>,
937 pub(crate) primary_key_order: Vec<String>,
939}
940
941impl TableSpec {
942 pub fn new(name: TableName) -> Self {
944 Self {
945 name,
946 title: String::new(),
947 fields: Vec::new(),
948 indexes: Vec::new(),
949 checks: Vec::new(),
950 foreign_keys: Vec::new(),
951 opaque_columns: Vec::new(),
952 datasource: None,
953 primary_key_order: Vec::new(),
954 }
955 }
956
957 pub fn title(mut self, value: impl Into<String>) -> Self {
959 self.title = value.into();
960 self
961 }
962
963 pub fn datasource(mut self, id: DatasourceId) -> Self {
965 self.datasource = Some(id);
966 self
967 }
968
969 pub fn fields(mut self, fields: Fields) -> Self {
971 self.fields = fields.into_vec();
972 self.primary_key_order = self
973 .fields
974 .iter()
975 .filter(|field| field.kind == FieldKind::Key)
976 .map(|field| field.name.to_string())
977 .collect();
978 self
979 }
980
981 #[must_use]
983 pub fn field(mut self, field: FieldSpec) -> Self {
984 if field.kind == FieldKind::Key {
985 self.primary_key_order.push(field.name.to_string());
986 }
987 self.fields.push(field);
988 self
989 }
990
991 pub fn unique(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
993 self.indexes.push(TableIndexSpec {
994 name: None,
995 fields: fields.into_iter().collect(),
996 expressions: Vec::new(),
997 predicate: None,
998 unique: true,
999 });
1000 self
1001 }
1002
1003 pub fn unique_named(
1005 mut self,
1006 name: impl Into<String>,
1007 fields: impl IntoIterator<Item = FieldRef>,
1008 ) -> Self {
1009 self.indexes.push(TableIndexSpec {
1010 name: Some(name.into()),
1011 fields: fields.into_iter().collect(),
1012 expressions: Vec::new(),
1013 predicate: None,
1014 unique: true,
1015 });
1016 self
1017 }
1018
1019 pub fn index(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
1021 self.indexes.push(TableIndexSpec {
1022 name: None,
1023 fields: fields.into_iter().collect(),
1024 expressions: Vec::new(),
1025 predicate: None,
1026 unique: false,
1027 });
1028 self
1029 }
1030
1031 pub fn index_named(
1033 mut self,
1034 name: impl Into<String>,
1035 fields: impl IntoIterator<Item = FieldRef>,
1036 ) -> Self {
1037 self.indexes.push(TableIndexSpec {
1038 name: Some(name.into()),
1039 fields: fields.into_iter().collect(),
1040 expressions: Vec::new(),
1041 predicate: None,
1042 unique: false,
1043 });
1044 self
1045 }
1046
1047 pub fn partial_index(
1049 mut self,
1050 name: impl Into<String>,
1051 fields: impl IntoIterator<Item = FieldRef>,
1052 predicate: impl Into<String>,
1053 ) -> Self {
1054 self.indexes.push(TableIndexSpec {
1055 name: Some(name.into()),
1056 fields: fields.into_iter().collect(),
1057 expressions: Vec::new(),
1058 predicate: Some(predicate.into()),
1059 unique: false,
1060 });
1061 self
1062 }
1063
1064 pub fn partial_unique_named(
1066 mut self,
1067 name: impl Into<String>,
1068 fields: impl IntoIterator<Item = FieldRef>,
1069 predicate: impl Into<String>,
1070 ) -> Self {
1071 self.indexes.push(TableIndexSpec {
1072 name: Some(name.into()),
1073 fields: fields.into_iter().collect(),
1074 expressions: Vec::new(),
1075 predicate: Some(predicate.into()),
1076 unique: true,
1077 });
1078 self
1079 }
1080
1081 pub fn expression_index(
1083 mut self,
1084 name: impl Into<String>,
1085 expressions: impl IntoIterator<Item = impl Into<String>>,
1086 unique: bool,
1087 ) -> Self {
1088 self.indexes.push(TableIndexSpec {
1089 name: Some(name.into()),
1090 fields: Vec::new(),
1091 expressions: expressions.into_iter().map(Into::into).collect(),
1092 predicate: None,
1093 unique,
1094 });
1095 self
1096 }
1097
1098 pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
1100 self.checks.push(TableCheckSpec {
1101 name: name.into(),
1102 expression: expression.into(),
1103 });
1104 self
1105 }
1106
1107 pub fn foreign_key_named(
1109 mut self,
1110 name: impl Into<String>,
1111 fields: impl IntoIterator<Item = FieldRef>,
1112 referenced_fields: impl IntoIterator<Item = FieldRef>,
1113 ) -> Self {
1114 self.foreign_keys.push(TableForeignKeySpec {
1115 name: name.into(),
1116 fields: fields.into_iter().collect(),
1117 referenced_fields: referenced_fields.into_iter().collect(),
1118 });
1119 self
1120 }
1121
1122 pub fn opaque_column(mut self, name: impl Into<String>, sql_type: impl Into<String>) -> Self {
1124 self.opaque_columns.push(TableOpaqueColumnSpec {
1125 name: name.into(),
1126 sql_type: sql_type.into(),
1127 });
1128 self
1129 }
1130
1131 pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
1133 let mut table = SchemaTable::new(self.name.to_string());
1134 table = table
1135 .datasource(self.datasource.clone().unwrap_or_default())
1136 .primary_key_order(self.primary_key_order.clone());
1137 for opaque in &self.opaque_columns {
1138 table = table.opaque_column(opaque.name.clone(), opaque.sql_type.clone());
1139 }
1140 if !self.title.is_empty() {
1141 table = table.label(self.title.clone());
1142 }
1143 for index in &self.indexes {
1144 let fields = self.validate_index(index)?;
1145 if !index.expressions.is_empty() || index.predicate.is_some() {
1146 table = table.index_spec(
1147 index.name.clone(),
1148 fields,
1149 index.expressions.clone(),
1150 index.predicate.clone(),
1151 index.unique,
1152 false,
1153 );
1154 continue;
1155 }
1156 table = match (&index.name, index.unique) {
1157 (Some(name), true) => table.unique_named(name.clone(), fields),
1158 (None, true) => table.unique(fields),
1159 (Some(name), false) => table.index_named(name.clone(), fields),
1160 (None, false) => table.index(fields),
1161 };
1162 }
1163 for check in &self.checks {
1164 table = table.check_named(check.name.clone(), check.expression.clone());
1165 }
1166 for foreign_key in &self.foreign_keys {
1167 let (columns, referenced_table, referenced_columns) =
1168 self.validate_foreign_key(foreign_key)?;
1169 table = table.foreign_key_named(
1170 foreign_key.name.clone(),
1171 columns,
1172 referenced_table,
1173 referenced_columns,
1174 );
1175 }
1176 let fields = self
1177 .fields
1178 .clone()
1179 .into_iter()
1180 .map(FieldSpec::into_schema_field)
1181 .collect::<Result<Vec<_>, _>>()?;
1182 table.fields(fields).build()
1183 }
1184
1185 fn validate_index(&self, index: &TableIndexSpec) -> Result<Vec<String>, BaseError> {
1186 if index.fields.is_empty() && index.expressions.is_empty() {
1187 return Err(BaseError::ConfigError(format!(
1188 "表 {} 的索引至少需要一个字段或表达式",
1189 self.name
1190 )));
1191 }
1192 if !index.expressions.is_empty() && index.name.is_none() {
1193 return Err(BaseError::ConfigError(format!(
1194 "表 {} 的表达式索引必须显式声明名称",
1195 self.name
1196 )));
1197 }
1198 let declared = self
1199 .fields
1200 .iter()
1201 .map(|field| field.name.as_str())
1202 .collect::<BTreeSet<_>>();
1203 let mut seen = BTreeSet::new();
1204 let mut fields = Vec::with_capacity(index.fields.len());
1205 for reference in &index.fields {
1206 if reference.table() != &self.name {
1207 return Err(BaseError::ConfigError(format!(
1208 "表 {} 的索引不能引用其他表字段 {}",
1209 self.name, reference
1210 )));
1211 }
1212 let field = reference.field().as_str();
1213 if !declared.contains(field) {
1214 return Err(BaseError::ConfigError(format!(
1215 "表 {} 的索引引用了未声明字段 {}",
1216 self.name, field
1217 )));
1218 }
1219 if !seen.insert(field) {
1220 return Err(BaseError::ConfigError(format!(
1221 "表 {} 的索引重复引用字段 {}",
1222 self.name, field
1223 )));
1224 }
1225 fields.push(field.to_string());
1226 }
1227 Ok(fields)
1228 }
1229
1230 fn validate_foreign_key(
1231 &self,
1232 foreign_key: &TableForeignKeySpec,
1233 ) -> Result<(Vec<String>, String, Vec<String>), BaseError> {
1234 if foreign_key.fields.is_empty()
1235 || foreign_key.fields.len() != foreign_key.referenced_fields.len()
1236 {
1237 return Err(BaseError::ConfigError(format!(
1238 "表 {} 的外键 {} 本地字段与目标字段必须非空且数量一致",
1239 self.name, foreign_key.name
1240 )));
1241 }
1242 let declared = self
1243 .fields
1244 .iter()
1245 .map(|field| field.name.as_str())
1246 .collect::<BTreeSet<_>>();
1247 let mut columns = Vec::with_capacity(foreign_key.fields.len());
1248 for field in &foreign_key.fields {
1249 if field.table() != &self.name || !declared.contains(field.field().as_str()) {
1250 return Err(BaseError::ConfigError(format!(
1251 "表 {} 的外键 {} 引用了未声明的本地字段 {}",
1252 self.name, foreign_key.name, field
1253 )));
1254 }
1255 columns.push(field.field().to_string());
1256 }
1257 let referenced_table = foreign_key.referenced_fields[0].table().clone();
1258 if foreign_key
1259 .referenced_fields
1260 .iter()
1261 .any(|field| field.table() != &referenced_table)
1262 {
1263 return Err(BaseError::ConfigError(format!(
1264 "表 {} 的外键 {} 目标字段必须来自同一张表",
1265 self.name, foreign_key.name
1266 )));
1267 }
1268 Ok((
1269 columns,
1270 referenced_table.to_string(),
1271 foreign_key
1272 .referenced_fields
1273 .iter()
1274 .map(|field| field.field().to_string())
1275 .collect(),
1276 ))
1277 }
1278}