1use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{
9 CheckConfig, ForeignKeyConfig, IndexConfig, TableConfig, TimestampFields,
10};
11#[cfg(feature = "mysql")]
12use super::TableQuery;
13use super::{FieldType, RegexCache, SortOrder, Validator, MAX_VARCHAR_LENGTH};
14use crate::error::BaseError;
15use serde_json::{json, Map, Value};
16use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19pub fn col(name: impl Into<String>) -> ColumnName {
21 ColumnName(name.into())
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub struct ColumnName(String);
27
28impl ColumnName {
29 pub fn asc(self) -> Order {
31 Order {
32 field: self.0,
33 direction: SortOrder::Asc,
34 }
35 }
36
37 pub fn desc(self) -> Order {
39 Order {
40 field: self.0,
41 direction: SortOrder::Desc,
42 }
43 }
44
45 fn into_name(self) -> String {
46 self.0
47 }
48}
49
50impl From<&str> for ColumnName {
51 fn from(value: &str) -> Self {
52 Self(value.to_string())
53 }
54}
55
56impl From<String> for ColumnName {
57 fn from(value: String) -> Self {
58 Self(value)
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Order {
65 field: String,
66 direction: SortOrder,
67}
68
69#[derive(Debug, Clone)]
74#[must_use = "字段定义必须传给 Table::fields"]
75pub struct Field {
76 config: FieldConfig,
77 primary_key: bool,
78 unique: bool,
79 unique_name: Option<String>,
80 index: bool,
81 index_name: Option<String>,
82 created_at: bool,
83 updated_at: bool,
84 deleted_at: bool,
85 soft_delete: bool,
86 relation_display_fields: Option<Vec<String>>,
87}
88
89impl Field {
90 fn new(name: impl Into<String>, field_type: FieldType) -> Self {
91 Self {
92 config: FieldConfig::new(name, field_type),
93 primary_key: false,
94 unique: false,
95 unique_name: None,
96 index: false,
97 index_name: None,
98 created_at: false,
99 updated_at: false,
100 deleted_at: false,
101 soft_delete: false,
102 relation_display_fields: None,
103 }
104 }
105
106 pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
108 self.config.renamed_from = Some(legacy_name.into());
109 self
110 }
111
112 pub fn id(name: impl Into<String>) -> Self {
114 Self::new(name, FieldType::BigInt)
115 .required()
116 .primary_key()
117 .auto_increment()
118 .not_writable()
119 }
120
121 pub fn string(name: impl Into<String>, max_length: usize) -> Self {
123 Self::new(name, FieldType::String { max_length })
124 }
125
126 pub fn integer(name: impl Into<String>) -> Self {
128 Self::new(name, FieldType::Integer)
129 }
130
131 pub fn bigint(name: impl Into<String>) -> Self {
133 Self::new(name, FieldType::BigInt)
134 }
135
136 pub fn float(name: impl Into<String>) -> Self {
138 Self::new(name, FieldType::Float)
139 }
140
141 pub fn double(name: impl Into<String>) -> Self {
143 Self::new(name, FieldType::Double)
144 }
145
146 pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
148 Self::new(name, FieldType::Decimal { precision, scale })
149 }
150
151 pub fn boolean(name: impl Into<String>) -> Self {
153 Self::new(name, FieldType::Boolean)
154 }
155
156 pub fn date(name: impl Into<String>) -> Self {
158 Self::new(name, FieldType::Date)
159 }
160
161 pub fn datetime(name: impl Into<String>) -> Self {
163 Self::new(name, FieldType::DateTime)
164 }
165
166 pub fn timestamp(name: impl Into<String>) -> Self {
168 Self::new(name, FieldType::Timestamp)
169 }
170
171 pub fn json(name: impl Into<String>) -> Self {
173 Self::new(name, FieldType::Json)
174 }
175
176 pub fn text(name: impl Into<String>) -> Self {
178 Self::new(name, FieldType::Text)
179 }
180
181 pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
183 where
184 I: IntoIterator<Item = S>,
185 S: Into<String>,
186 {
187 Self::new(
188 name,
189 FieldType::Enum {
190 values: values.into_iter().map(Into::into).collect(),
191 },
192 )
193 }
194
195 pub fn created_at(name: impl Into<String>) -> Self {
197 let mut field = Self::bigint(name).required().not_writable();
198 field.created_at = true;
199 field
200 }
201
202 pub fn updated_at(name: impl Into<String>) -> Self {
204 let mut field = Self::bigint(name).required().not_writable();
205 field.updated_at = true;
206 field
207 }
208
209 pub fn soft_delete(name: impl Into<String>) -> Self {
211 let mut field = Self::bigint(name).not_writable();
212 field.deleted_at = true;
213 field.soft_delete = true;
214 field
215 }
216
217 pub fn label(mut self, label: impl Into<String>) -> Self {
219 self.config.display_name = label.into();
220 self
221 }
222
223 pub fn required(mut self) -> Self {
225 self.config.required = true;
226 self
227 }
228
229 pub fn nullable(mut self) -> Self {
231 self.config.required = false;
232 self
233 }
234
235 pub fn default(mut self, value: impl Into<Value>) -> Self {
237 self.config.default_value = Some(value.into());
238 self
239 }
240
241 pub fn auto_increment(mut self) -> Self {
243 self.config.auto_increment = true;
244 self
245 }
246
247 pub fn primary_key(mut self) -> Self {
249 self.primary_key = true;
250 self
251 }
252
253 pub fn unique(mut self) -> Self {
255 self.unique = true;
256 self
257 }
258
259 pub fn unique_named(mut self, name: impl Into<String>) -> Self {
261 self.unique = true;
262 self.unique_name = Some(name.into());
263 self
264 }
265
266 pub fn index(mut self) -> Self {
268 self.index = true;
269 self
270 }
271
272 pub fn index_named(mut self, name: impl Into<String>) -> Self {
274 self.index = true;
275 self.index_name = Some(name.into());
276 self
277 }
278
279 pub fn validator(mut self, validator: Validator) -> Self {
281 self.config.validators.push(validator);
282 self
283 }
284
285 pub fn min_length(self, value: usize) -> Self {
287 self.validator(Validator::MinLength(value))
288 }
289
290 pub fn max_length(self, value: usize) -> Self {
292 self.validator(Validator::MaxLength(value))
293 }
294
295 pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
297 self.min_length(*range.start()).max_length(*range.end())
298 }
299
300 pub fn min(self, value: f64) -> Self {
302 self.validator(Validator::Min(value))
303 }
304
305 pub fn max(self, value: f64) -> Self {
307 self.validator(Validator::Max(value))
308 }
309
310 pub fn email(self) -> Self {
312 self.validator(Validator::Email)
313 }
314
315 pub fn phone(self) -> Self {
317 self.validator(Validator::Phone)
318 }
319
320 pub fn url(self) -> Self {
322 self.validator(Validator::Url)
323 }
324
325 pub fn regex(self, pattern: impl Into<String>) -> Self {
327 self.validator(Validator::Regex(pattern.into()))
328 }
329
330 pub fn readable(mut self) -> Self {
332 self.config.permissions.readable = Audience::Everyone;
333 self
334 }
335
336 pub fn not_readable(mut self) -> Self {
338 self.config.permissions.readable = Audience::Nobody;
339 self
340 }
341
342 pub fn readable_by<I, S>(mut self, roles: I) -> Self
344 where
345 I: IntoIterator<Item = S>,
346 S: Into<String>,
347 {
348 self.config.permissions.readable = Audience::roles(roles);
349 self
350 }
351
352 pub fn writable_by<I, S>(mut self, roles: I) -> Self
354 where
355 I: IntoIterator<Item = S>,
356 S: Into<String>,
357 {
358 self.config.permissions.writable = Audience::roles(roles);
359 self
360 }
361
362 pub fn writable(mut self) -> Self {
364 self.config.permissions.writable = Audience::Everyone;
365 self
366 }
367
368 pub fn not_writable(mut self) -> Self {
370 self.config.permissions.writable = Audience::Nobody;
371 self
372 }
373
374 pub fn searchable(mut self) -> Self {
380 self.config.searchable = true;
381 self
382 }
383
384 pub fn filterable(mut self) -> Self {
386 self.config.filterable = true;
387 self.config.permissions.filterable = Audience::Everyone;
388 self
389 }
390
391 pub fn not_filterable(mut self) -> Self {
393 self.config.filterable = false;
394 self.config.permissions.filterable = Audience::Nobody;
395 self
396 }
397
398 pub fn filterable_by<I, S>(mut self, roles: I) -> Self
400 where
401 I: IntoIterator<Item = S>,
402 S: Into<String>,
403 {
404 self.config.filterable = true;
405 self.config.permissions.filterable = Audience::roles(roles);
406 self
407 }
408
409 pub fn sortable(mut self) -> Self {
411 self.config.sortable = true;
412 self.config.permissions.sortable = Audience::Everyone;
413 self
414 }
415
416 pub fn not_sortable(mut self) -> Self {
418 self.config.sortable = false;
419 self.config.permissions.sortable = Audience::Nobody;
420 self
421 }
422
423 pub fn sortable_by<I, S>(mut self, roles: I) -> Self
425 where
426 I: IntoIterator<Item = S>,
427 S: Into<String>,
428 {
429 self.config.sortable = true;
430 self.config.permissions.sortable = Audience::roles(roles);
431 self
432 }
433
434 pub fn tenant_key(mut self) -> Self {
436 self.config.tenant_key = true;
437 self
438 }
439
440 pub fn secret(mut self) -> Self {
446 self.config.hidden = true;
447 self.config.permissions = FieldPermissions {
448 readable: Audience::Nobody,
449 writable: Audience::Nobody,
450 filterable: Audience::Nobody,
451 sortable: Audience::Nobody,
452 };
453 self.config.searchable = false;
454 self.config.filterable = false;
455 self.config.sortable = false;
456 self
457 }
458
459 pub fn relation(
461 mut self,
462 table: impl Into<String>,
463 field: impl Into<String>,
464 relation_type: RelationType,
465 ) -> Self {
466 self.config.relation = Some(RelationConfig {
467 table: table.into(),
468 field: field.into(),
469 display_fields: Vec::new(),
470 relation_type,
471 });
472 self
473 }
474
475 pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
477 where
478 I: IntoIterator<Item = S>,
479 S: Into<String>,
480 {
481 self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
482 self
483 }
484}
485
486#[derive(Debug, Clone)]
487struct PendingIndex {
488 name: Option<String>,
489 fields: Vec<String>,
490 unique: bool,
491}
492
493#[derive(Debug, Clone)]
494struct PendingCheck {
495 name: String,
496 expression: String,
497}
498
499#[derive(Debug, Clone)]
500struct PendingForeignKey {
501 name: String,
502 columns: Vec<String>,
503 referenced_table: String,
504 referenced_columns: Vec<String>,
505}
506
507#[derive(Debug, Clone)]
509#[must_use = "表构建器必须调用 build"]
510pub struct Table {
511 name: String,
512 label: Option<String>,
513 fields: Vec<Field>,
514 indexes: Vec<PendingIndex>,
515 checks: Vec<PendingCheck>,
516 foreign_keys: Vec<PendingForeignKey>,
517 default_order: Vec<Order>,
518}
519
520impl Table {
521 pub fn new(name: impl Into<String>) -> Self {
523 Self {
524 name: name.into(),
525 label: None,
526 fields: Vec::new(),
527 indexes: Vec::new(),
528 checks: Vec::new(),
529 foreign_keys: Vec::new(),
530 default_order: Vec::new(),
531 }
532 }
533
534 pub fn label(mut self, label: impl Into<String>) -> Self {
536 self.label = Some(label.into());
537 self
538 }
539
540 pub fn fields<I>(mut self, fields: I) -> Self
542 where
543 I: IntoIterator<Item = Field>,
544 {
545 self.fields.extend(fields);
546 self
547 }
548
549 pub fn unique<I, C>(mut self, fields: I) -> Self
551 where
552 I: IntoIterator<Item = C>,
553 C: Into<ColumnName>,
554 {
555 self.indexes.push(PendingIndex {
556 name: None,
557 fields: fields
558 .into_iter()
559 .map(|field| field.into().into_name())
560 .collect(),
561 unique: true,
562 });
563 self
564 }
565
566 pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
568 where
569 I: IntoIterator<Item = C>,
570 C: Into<ColumnName>,
571 {
572 self.indexes.push(PendingIndex {
573 name: Some(name.into()),
574 fields: fields
575 .into_iter()
576 .map(|field| field.into().into_name())
577 .collect(),
578 unique: true,
579 });
580 self
581 }
582
583 pub fn index<I, C>(mut self, fields: I) -> Self
585 where
586 I: IntoIterator<Item = C>,
587 C: Into<ColumnName>,
588 {
589 self.indexes.push(PendingIndex {
590 name: None,
591 fields: fields
592 .into_iter()
593 .map(|field| field.into().into_name())
594 .collect(),
595 unique: false,
596 });
597 self
598 }
599
600 pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
602 where
603 I: IntoIterator<Item = C>,
604 C: Into<ColumnName>,
605 {
606 self.indexes.push(PendingIndex {
607 name: Some(name.into()),
608 fields: fields
609 .into_iter()
610 .map(|field| field.into().into_name())
611 .collect(),
612 unique: false,
613 });
614 self
615 }
616
617 pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
621 self.checks.push(PendingCheck {
622 name: name.into(),
623 expression: expression.into(),
624 });
625 self
626 }
627
628 pub fn foreign_key_named<I, C, R, RC>(
630 mut self,
631 name: impl Into<String>,
632 columns: I,
633 referenced_table: impl Into<String>,
634 referenced_columns: R,
635 ) -> Self
636 where
637 I: IntoIterator<Item = C>,
638 C: Into<ColumnName>,
639 R: IntoIterator<Item = RC>,
640 RC: Into<ColumnName>,
641 {
642 self.foreign_keys.push(PendingForeignKey {
643 name: name.into(),
644 columns: columns
645 .into_iter()
646 .map(|column| column.into().into_name())
647 .collect(),
648 referenced_table: referenced_table.into(),
649 referenced_columns: referenced_columns
650 .into_iter()
651 .map(|column| column.into().into_name())
652 .collect(),
653 });
654 self
655 }
656
657 pub fn default_order(mut self, order: Order) -> Self {
659 self.default_order = vec![order];
660 self
661 }
662
663 pub fn then_order(mut self, order: Order) -> Self {
665 self.default_order.push(order);
666 self
667 }
668
669 pub fn build(self) -> Result<TableDefinition, BaseError> {
671 validate_identifier("表", &self.name)?;
672 if self.fields.is_empty() {
673 return Err(BaseError::ConfigError(format!(
674 "表 {} 至少需要一个字段",
675 self.name
676 )));
677 }
678
679 let mut field_names = HashSet::with_capacity(self.fields.len());
680 let mut legacy_names = HashSet::new();
681 let mut configs = HashMap::with_capacity(self.fields.len());
682 let mut primary_key: Option<String> = None;
683 let mut created_at: Option<String> = None;
684 let mut updated_at: Option<String> = None;
685 let mut deleted_at: Option<String> = None;
686 let mut soft_delete: Option<String> = None;
687 let mut tenant_key: Option<String> = None;
688 let mut indexes = self.indexes;
689 let checks = self.checks;
690 let foreign_keys = self.foreign_keys;
691 let regex_cache = RegexCache::default();
693
694 for mut field in self.fields {
695 validate_identifier("字段", &field.config.name)?;
696 if !field_names.insert(field.config.name.clone()) {
697 return Err(BaseError::ConfigError(format!(
698 "表 {} 存在重复字段: {}",
699 self.name, field.config.name
700 )));
701 }
702 if let Some(legacy_name) = field.config.renamed_from.as_deref() {
703 validate_identifier("旧字段", legacy_name)?;
704 if legacy_name == field.config.name || !legacy_names.insert(legacy_name.to_string())
705 {
706 return Err(BaseError::ConfigError(format!(
707 "表 {} 的旧字段改名来源重复或未发生改名: {}",
708 self.name, legacy_name
709 )));
710 }
711 }
712 if field.config.display_name.is_empty() {
713 field.config.display_name = field.config.name.clone();
714 }
715 if let Some(display_fields) = field.relation_display_fields.take() {
716 let relation = field.config.relation.as_mut().ok_or_else(|| {
717 BaseError::ConfigError(format!(
718 "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
719 self.name, field.config.name
720 ))
721 })?;
722 relation.display_fields = display_fields;
723 }
724 validate_field_shape(&self.name, &field, ®ex_cache)?;
725
726 if field.primary_key && primary_key.replace(field.config.name.clone()).is_some() {
727 return Err(BaseError::ConfigError(format!(
728 "表 {} 只能定义一个主键",
729 self.name
730 )));
731 }
732 if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
733 return Err(BaseError::ConfigError(format!(
734 "表 {} 只能定义一个租户隔离字段",
735 self.name
736 )));
737 }
738 set_unique_role(
739 &self.name,
740 "created_at",
741 field.created_at,
742 &field.config.name,
743 &mut created_at,
744 )?;
745 set_unique_role(
746 &self.name,
747 "updated_at",
748 field.updated_at,
749 &field.config.name,
750 &mut updated_at,
751 )?;
752 set_unique_role(
753 &self.name,
754 "deleted_at",
755 field.deleted_at,
756 &field.config.name,
757 &mut deleted_at,
758 )?;
759 set_unique_role(
760 &self.name,
761 "soft_delete",
762 field.soft_delete,
763 &field.config.name,
764 &mut soft_delete,
765 )?;
766
767 if field.unique {
768 indexes.push(PendingIndex {
769 name: field.unique_name.take(),
770 fields: vec![field.config.name.clone()],
771 unique: true,
772 });
773 }
774 if field.index {
775 indexes.push(PendingIndex {
776 name: field.index_name.take(),
777 fields: vec![field.config.name.clone()],
778 unique: false,
779 });
780 }
781 configs.insert(field.config.name.clone(), field.config);
782 }
783
784 if let Some(legacy_name) = legacy_names
785 .iter()
786 .find(|legacy_name| field_names.contains(legacy_name.as_str()))
787 {
788 return Err(BaseError::ConfigError(format!(
789 "表 {} 同时声明旧字段与改名后字段: {}",
790 self.name, legacy_name
791 )));
792 }
793
794 let primary_key = primary_key
795 .ok_or_else(|| BaseError::ConfigError(format!("表 {} 必须定义一个主键", self.name)))?;
796
797 let mut unique_indexes = Vec::new();
798 let mut normal_indexes = Vec::new();
799 let mut index_names = HashSet::new();
800 for index in indexes {
801 validate_index(&self.name, &field_names, &index, &mut index_names)?;
802 let config = IndexConfig::new(index.name, index.fields);
803 if index.unique {
804 unique_indexes.push(config);
805 } else {
806 normal_indexes.push(config);
807 }
808 }
809
810 let mut constraint_names = HashSet::new();
811 let checks = checks
812 .into_iter()
813 .map(|check| {
814 validate_constraint_name(&self.name, &check.name, &mut constraint_names)?;
815 validate_check_expression(&self.name, &check.name, &check.expression)?;
816 Ok(CheckConfig {
817 name: check.name,
818 expression: check.expression,
819 })
820 })
821 .collect::<Result<Vec<_>, BaseError>>()?;
822 let foreign_keys = foreign_keys
823 .into_iter()
824 .map(|foreign_key| {
825 validate_constraint_name(&self.name, &foreign_key.name, &mut constraint_names)?;
826 validate_foreign_key(&self.name, &field_names, &foreign_key)?;
827 Ok(ForeignKeyConfig {
828 name: foreign_key.name,
829 columns: foreign_key.columns,
830 referenced_table: foreign_key.referenced_table,
831 referenced_columns: foreign_key.referenced_columns,
832 })
833 })
834 .collect::<Result<Vec<_>, BaseError>>()?;
835
836 let mut orders = Vec::with_capacity(self.default_order.len());
837 for order in self.default_order {
838 if !field_names.contains(&order.field) {
839 return Err(BaseError::ConfigError(format!(
840 "表 {} 的默认排序字段不存在: {}",
841 self.name, order.field
842 )));
843 }
844 orders.push((order.field, order.direction));
845 }
846
847 let timestamp_fields =
848 if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
849 Some(TimestampFields::new(created_at, updated_at, deleted_at))
850 } else {
851 None
852 };
853 let table_ref = yang_db::TableRef::new(self.name.clone())
854 .map_err(|error| BaseError::ConfigError(error.to_string()))?;
855 let field_refs = field_names
856 .iter()
857 .map(|name| {
858 yang_db::FieldRef::new(name.clone())
859 .map(|field| (name.clone(), field))
860 .map_err(|error| BaseError::ConfigError(error.to_string()))
861 })
862 .collect::<Result<HashMap<_, _>, _>>()?;
863
864 Ok(TableDefinition {
865 config: Arc::new(TableConfig {
866 table_name: self.name.clone(),
867 table_ref,
868 display_name: self.label.unwrap_or(self.name),
869 primary_key,
870 fields: configs,
871 field_refs,
872 unique_indexes,
873 indexes: normal_indexes,
874 checks,
875 foreign_keys,
876 default_order: orders,
877 soft_delete_field: soft_delete,
878 timestamp_fields,
879 }),
880 })
881 }
882}
883
884#[derive(Debug, Clone)]
886pub struct TableDefinition {
887 pub(crate) config: Arc<TableConfig>,
888}
889
890impl TableDefinition {
891 pub fn name(&self) -> &str {
893 &self.config.table_name
894 }
895
896 pub fn label(&self) -> &str {
898 &self.config.display_name
899 }
900
901 pub fn primary_key(&self) -> &str {
903 &self.config.primary_key
904 }
905
906 pub fn field_count(&self) -> usize {
908 self.config.fields.len()
909 }
910
911 pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
913 self.config
914 .fields
915 .get(name)
916 .map(|config| FieldMetadata { config })
917 }
918
919 pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
921 let mut fields: Vec<_> = self
922 .config
923 .fields
924 .values()
925 .map(|config| FieldMetadata { config })
926 .collect();
927 fields.sort_by(|left, right| left.name().cmp(right.name()));
928 fields
929 }
930
931 pub fn soft_delete_field(&self) -> Option<&str> {
933 self.config.soft_delete_field.as_deref()
934 }
935
936 pub fn tenant_key_field(&self) -> Option<&str> {
938 self.config
939 .fields
940 .values()
941 .find(|field| field.tenant_key)
942 .map(|field| field.name.as_str())
943 }
944
945 pub fn input_schema(&self) -> Value {
950 self.json_schema(false, None)
951 }
952
953 pub fn output_schema(&self) -> Value {
958 self.json_schema(true, None)
959 }
960
961 pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
963 self.json_schema(false, Some(roles))
964 }
965
966 pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
968 self.json_schema(true, Some(roles))
969 }
970
971 #[cfg(feature = "mysql")]
973 pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
974 self.config.fields.get(name).map(field_json_schema)
975 }
976
977 fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
978 let mut properties = Map::new();
979 let mut required = Vec::new();
980 let mut names: Vec<_> = self.config.fields.keys().collect();
981 names.sort();
982 for name in names {
983 let field = &self.config.fields[name];
984 let generated = field.auto_increment
985 || self
986 .config
987 .timestamp_fields
988 .as_ref()
989 .is_some_and(|timestamps| {
990 timestamps.created_at.as_deref() == Some(name.as_str())
991 || timestamps.updated_at.as_deref() == Some(name.as_str())
992 || timestamps.deleted_at.as_deref() == Some(name.as_str())
993 })
994 || self.config.soft_delete_field.as_deref() == Some(name.as_str());
995 let audience = if output {
996 &field.permissions.readable
997 } else {
998 &field.permissions.writable
999 };
1000 let audience_allows = roles.map_or_else(
1001 || !matches!(audience, Audience::Nobody),
1002 |roles| audience.allows(roles),
1003 );
1004 if field.hidden || !audience_allows || (!output && generated) {
1005 continue;
1006 }
1007 properties.insert(name.clone(), field_json_schema(field));
1008 if field.required && (output || (!generated && field.default_value.is_none())) {
1009 required.push(Value::String(name.clone()));
1010 }
1011 }
1012 json!({
1013 "type": "object",
1014 "title": self.config.display_name,
1015 "properties": properties,
1016 "required": required,
1017 "additionalProperties": false,
1018 })
1019 }
1020
1021 #[cfg(feature = "mysql")]
1022 pub(crate) fn config(&self) -> &TableConfig {
1023 &self.config
1024 }
1025
1026 pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
1027 Arc::clone(&self.config)
1028 }
1029
1030 pub fn validate_schema(
1032 &self,
1033 columns: &[super::SchemaColumn],
1034 ) -> super::SchemaValidationReport {
1035 self.config.validate_schema(columns)
1036 }
1037
1038 #[cfg(feature = "mysql")]
1040 pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
1041 TableHandle {
1042 definition: self.clone(),
1043 pool,
1044 }
1045 }
1046}
1047
1048#[derive(Debug, Clone, Copy)]
1050pub struct FieldMetadata<'a> {
1051 config: &'a FieldConfig,
1052}
1053
1054impl<'a> FieldMetadata<'a> {
1055 pub fn name(self) -> &'a str {
1057 &self.config.name
1058 }
1059
1060 pub fn label(self) -> &'a str {
1062 &self.config.display_name
1063 }
1064
1065 pub fn is_tenant_key(self) -> bool {
1067 self.config.tenant_key
1068 }
1069
1070 pub fn field_type(self) -> &'a FieldType {
1072 &self.config.field_type
1073 }
1074
1075 pub fn is_required(self) -> bool {
1077 self.config.required
1078 }
1079
1080 pub fn default_value(self) -> Option<&'a Value> {
1082 self.config.default_value.as_ref()
1083 }
1084
1085 pub fn is_auto_increment(self) -> bool {
1087 self.config.auto_increment
1088 }
1089
1090 pub fn is_searchable(self) -> bool {
1092 self.config.searchable
1093 }
1094
1095 pub fn is_filterable(self) -> bool {
1097 self.config.filterable
1098 }
1099
1100 pub fn is_sortable(self) -> bool {
1102 self.config.sortable
1103 }
1104
1105 pub fn is_secret(self) -> bool {
1107 self.config.hidden
1108 }
1109}
1110
1111#[cfg(feature = "mysql")]
1113#[derive(Debug, Clone)]
1114pub struct TableHandle {
1115 definition: TableDefinition,
1116 pool: Arc<sqlx::MySqlPool>,
1117}
1118
1119#[cfg(feature = "mysql")]
1120impl TableHandle {
1121 pub fn definition(&self) -> &TableDefinition {
1123 &self.definition
1124 }
1125
1126 pub fn query<I, S>(&self, roles: I) -> TableQuery
1128 where
1129 I: IntoIterator<Item = S>,
1130 S: Into<String>,
1131 {
1132 let roles: Arc<[String]> =
1133 Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1134 TableQuery::new(
1135 self.definition.shared_config(),
1136 roles,
1137 Some(Arc::clone(&self.pool)),
1138 )
1139 }
1140}
1141
1142fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1143 let mut chars = value.chars();
1144 let first = chars
1145 .next()
1146 .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1147 if value.len() > 64
1148 || !(first == '_' || first.is_ascii_alphabetic())
1149 || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1150 {
1151 return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1152 }
1153 Ok(())
1154}
1155
1156fn validate_field_shape(table: &str, field: &Field, cache: &RegexCache) -> Result<(), BaseError> {
1157 match &field.config.field_type {
1158 FieldType::String { max_length } if !(1..=MAX_VARCHAR_LENGTH).contains(max_length) => {
1159 return Err(BaseError::ConfigError(format!(
1160 "表 {table} 的字符串字段 {} 长度必须在 1..={MAX_VARCHAR_LENGTH}(更长内容请使用 Text 字段)",
1161 field.config.name
1162 )));
1163 }
1164 FieldType::Enum { values } => {
1165 let unique: HashSet<_> = values.iter().collect();
1166 if values.is_empty() || unique.len() != values.len() {
1167 return Err(BaseError::ConfigError(format!(
1168 "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1169 field.config.name
1170 )));
1171 }
1172 }
1173 FieldType::Decimal { precision, scale }
1174 if *precision == 0 || *precision > 65 || *scale > *precision =>
1175 {
1176 return Err(BaseError::ConfigError(format!(
1177 "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1178 field.config.name
1179 )));
1180 }
1181 _ => {}
1182 }
1183
1184 if field.config.auto_increment
1185 && (!field.primary_key
1186 || !matches!(
1187 field.config.field_type,
1188 FieldType::Integer | FieldType::BigInt
1189 ))
1190 {
1191 return Err(BaseError::ConfigError(format!(
1192 "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1193 field.config.name
1194 )));
1195 }
1196 if field.primary_key && !field.config.required {
1197 return Err(BaseError::ConfigError(format!(
1198 "表 {table} 的主键必须为必填字段: {}",
1199 field.config.name
1200 )));
1201 }
1202 if field.config.auto_increment && field.config.default_value.is_some() {
1203 return Err(BaseError::ConfigError(format!(
1204 "表 {table} 的自增字段不能配置默认值: {}",
1205 field.config.name
1206 )));
1207 }
1208 validate_validator_configuration(table, &field.config)?;
1209 if let Some(default) = &field.config.default_value {
1210 if matches!(field.config.field_type, FieldType::Text | FieldType::Json) {
1211 return Err(BaseError::ConfigError(format!(
1212 "表 {table} 的 TEXT/JSON 字段不能配置数据库默认值: {}",
1213 field.config.name
1214 )));
1215 }
1216 field.config.validate(default, cache)?;
1217 }
1218 validate_audience(
1219 table,
1220 &field.config.name,
1221 "读取",
1222 &field.config.permissions.readable,
1223 )?;
1224 validate_audience(
1225 table,
1226 &field.config.name,
1227 "写入",
1228 &field.config.permissions.writable,
1229 )?;
1230 validate_audience(
1231 table,
1232 &field.config.name,
1233 "筛选",
1234 &field.config.permissions.filterable,
1235 )?;
1236 validate_audience(
1237 table,
1238 &field.config.name,
1239 "排序",
1240 &field.config.permissions.sortable,
1241 )?;
1242 if let Some(relation) = &field.config.relation {
1243 validate_identifier("关联表", &relation.table)?;
1244 validate_identifier("关联字段", &relation.field)?;
1245 for display_field in &relation.display_fields {
1246 validate_identifier("关联展示字段", display_field)?;
1247 }
1248 }
1249 if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1250 && !matches!(
1251 field.config.field_type,
1252 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1253 )
1254 {
1255 return Err(BaseError::ConfigError(format!(
1256 "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1257 field.config.name
1258 )));
1259 }
1260 Ok(())
1261}
1262
1263fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1264 let string_compatible = matches!(
1265 field.field_type,
1266 FieldType::String { .. }
1267 | FieldType::Text
1268 | FieldType::Enum { .. }
1269 | FieldType::Date
1270 | FieldType::DateTime
1271 );
1272 let numeric_compatible = matches!(
1273 field.field_type,
1274 FieldType::Integer
1275 | FieldType::BigInt
1276 | FieldType::Float
1277 | FieldType::Double
1278 | FieldType::Decimal { .. }
1279 | FieldType::Timestamp
1280 );
1281 let mut min_length: Option<usize> = None;
1282 let mut max_length: Option<usize> = None;
1283 let mut minimum: Option<f64> = None;
1284 let mut maximum: Option<f64> = None;
1285
1286 for validator in &field.validators {
1287 match validator {
1288 Validator::MinLength(value) => {
1289 ensure_validator_type(table, field, validator, string_compatible)?;
1290 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1291 }
1292 Validator::MaxLength(value) => {
1293 ensure_validator_type(table, field, validator, string_compatible)?;
1294 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1295 }
1296 Validator::Min(value) => {
1297 ensure_validator_type(table, field, validator, numeric_compatible)?;
1298 if !value.is_finite() {
1299 return Err(BaseError::ConfigError(format!(
1300 "表 {table} 的字段 {} 数值下限必须是有限数值",
1301 field.name
1302 )));
1303 }
1304 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1305 }
1306 Validator::Max(value) => {
1307 ensure_validator_type(table, field, validator, numeric_compatible)?;
1308 if !value.is_finite() {
1309 return Err(BaseError::ConfigError(format!(
1310 "表 {table} 的字段 {} 数值上限必须是有限数值",
1311 field.name
1312 )));
1313 }
1314 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1315 }
1316 Validator::Email
1317 | Validator::EmailLoose
1318 | Validator::Phone
1319 | Validator::PhoneLoose
1320 | Validator::Url => {
1321 ensure_validator_type(table, field, validator, string_compatible)?;
1322 }
1323 Validator::Regex(pattern) => {
1324 ensure_validator_type(table, field, validator, string_compatible)?;
1325 #[cfg(feature = "validator")]
1326 regex::Regex::new(pattern).map_err(|error| {
1327 BaseError::ConfigError(format!(
1328 "表 {table} 的字段 {} 正则表达式无效: {error}",
1329 field.name
1330 ))
1331 })?;
1332 #[cfg(not(feature = "validator"))]
1333 return Err(BaseError::ConfigError(format!(
1334 "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1335 field.name,
1336 )));
1337 }
1338 Validator::Custom(_) => {}
1339 }
1340 }
1341
1342 if let (Some(min), Some(max)) = (min_length, max_length) {
1343 if min > max {
1344 return Err(BaseError::ConfigError(format!(
1345 "表 {table} 的字段 {} 最小长度不能大于最大长度",
1346 field.name
1347 )));
1348 }
1349 }
1350 if let (
1351 FieldType::String {
1352 max_length: storage_max,
1353 },
1354 Some(min),
1355 ) = (&field.field_type, min_length)
1356 {
1357 if min > *storage_max {
1358 return Err(BaseError::ConfigError(format!(
1359 "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1360 field.name
1361 )));
1362 }
1363 }
1364 if let (Some(min), Some(max)) = (minimum, maximum) {
1365 if min > max {
1366 return Err(BaseError::ConfigError(format!(
1367 "表 {table} 的字段 {} 数值下限不能大于上限",
1368 field.name
1369 )));
1370 }
1371 }
1372 Ok(())
1373}
1374
1375fn ensure_validator_type(
1376 table: &str,
1377 field: &FieldConfig,
1378 validator: &Validator,
1379 compatible: bool,
1380) -> Result<(), BaseError> {
1381 if compatible {
1382 return Ok(());
1383 }
1384 Err(BaseError::ConfigError(format!(
1385 "表 {table} 的字段 {} 类型不能使用{}验证器",
1386 field.name,
1387 validator.display_name()
1388 )))
1389}
1390
1391fn validate_audience(
1392 table: &str,
1393 field: &str,
1394 operation: &str,
1395 audience: &Audience,
1396) -> Result<(), BaseError> {
1397 if let Audience::Roles(roles) = audience {
1398 if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1399 return Err(BaseError::ConfigError(format!(
1400 "表 {table} 的字段 {field} 的{operation}角色不能为空"
1401 )));
1402 }
1403 }
1404 Ok(())
1405}
1406
1407fn set_unique_role(
1408 table: &str,
1409 role: &str,
1410 enabled: bool,
1411 field: &str,
1412 target: &mut Option<String>,
1413) -> Result<(), BaseError> {
1414 if !enabled {
1415 return Ok(());
1416 }
1417 if let Some(existing) = target {
1418 return Err(BaseError::ConfigError(format!(
1419 "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1420 )));
1421 }
1422 *target = Some(field.to_string());
1423 Ok(())
1424}
1425
1426fn validate_index(
1427 table: &str,
1428 field_names: &HashSet<String>,
1429 index: &PendingIndex,
1430 index_names: &mut HashSet<String>,
1431) -> Result<(), BaseError> {
1432 if index.fields.is_empty() {
1433 return Err(BaseError::ConfigError(format!(
1434 "表 {table} 的索引字段不能为空"
1435 )));
1436 }
1437 let mut seen = HashSet::new();
1438 for field in &index.fields {
1439 if !field_names.contains(field) {
1440 return Err(BaseError::ConfigError(format!(
1441 "表 {table} 的索引字段不存在: {field}"
1442 )));
1443 }
1444 if !seen.insert(field) {
1445 return Err(BaseError::ConfigError(format!(
1446 "表 {table} 的索引重复引用字段: {field}"
1447 )));
1448 }
1449 }
1450 let prefix = if index.unique { "uk" } else { "idx" };
1451 let effective_name = index
1452 .name
1453 .clone()
1454 .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
1455 validate_identifier("索引", &effective_name)?;
1456 if !index_names.insert(effective_name.clone()) {
1457 return Err(BaseError::ConfigError(format!(
1458 "表 {table} 存在重复索引名: {effective_name}"
1459 )));
1460 }
1461 Ok(())
1462}
1463
1464fn validate_constraint_name(
1465 table: &str,
1466 name: &str,
1467 names: &mut HashSet<String>,
1468) -> Result<(), BaseError> {
1469 validate_identifier("约束", name)?;
1470 if !names.insert(name.to_string()) {
1471 return Err(BaseError::ConfigError(format!(
1472 "表 {table} 存在重复约束名: {name}"
1473 )));
1474 }
1475 Ok(())
1476}
1477
1478fn validate_check_expression(table: &str, name: &str, expression: &str) -> Result<(), BaseError> {
1479 let expression = expression.trim();
1480 if expression.is_empty()
1481 || expression.chars().count() > 2_048
1482 || [";", "--", "/*", "*/"]
1483 .iter()
1484 .any(|marker| expression.contains(marker))
1485 {
1486 return Err(BaseError::ConfigError(format!(
1487 "表 {table} 的 CHECK {name} 必须是单条、非空且长度受限的受信表达式"
1488 )));
1489 }
1490 Ok(())
1491}
1492
1493fn validate_foreign_key(
1494 table: &str,
1495 field_names: &HashSet<String>,
1496 foreign_key: &PendingForeignKey,
1497) -> Result<(), BaseError> {
1498 validate_identifier("外键目标表", &foreign_key.referenced_table)?;
1499 if foreign_key.columns.is_empty()
1500 || foreign_key.columns.len() != foreign_key.referenced_columns.len()
1501 {
1502 return Err(BaseError::ConfigError(format!(
1503 "表 {table} 的外键 {} 本地列与目标列必须非空且数量一致",
1504 foreign_key.name
1505 )));
1506 }
1507 let mut local = HashSet::new();
1508 let mut referenced = HashSet::new();
1509 for column in &foreign_key.columns {
1510 validate_identifier("外键列", column)?;
1511 if !field_names.contains(column) || !local.insert(column) {
1512 return Err(BaseError::ConfigError(format!(
1513 "表 {table} 的外键 {} 引用了缺失或重复的本地列 {column}",
1514 foreign_key.name
1515 )));
1516 }
1517 }
1518 for column in &foreign_key.referenced_columns {
1519 validate_identifier("外键目标列", column)?;
1520 if !referenced.insert(column) {
1521 return Err(BaseError::ConfigError(format!(
1522 "表 {table} 的外键 {} 重复引用目标列 {column}",
1523 foreign_key.name
1524 )));
1525 }
1526 }
1527 Ok(())
1528}
1529
1530fn field_json_schema(field: &FieldConfig) -> Value {
1531 let mut schema = Map::new();
1532 let mut min_length: Option<usize> = None;
1533 let mut max_length: Option<usize> = None;
1534 let mut minimum: Option<f64> = None;
1535 let mut maximum: Option<f64> = None;
1536 let mut patterns = Vec::new();
1537 let mut runtime_validators = Vec::new();
1538 match &field.field_type {
1539 FieldType::String {
1540 max_length: storage_max,
1541 } => {
1542 schema.insert("type".into(), json!("string"));
1543 max_length = Some(*storage_max);
1544 }
1545 FieldType::Text => {
1546 schema.insert("type".into(), json!("string"));
1547 }
1548 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
1549 schema.insert("type".into(), json!("integer"));
1550 }
1551 FieldType::Float | FieldType::Double => {
1552 schema.insert("type".into(), json!("number"));
1553 }
1554 FieldType::Decimal { precision, scale } => {
1555 schema.insert("type".into(), json!("string"));
1556 schema.insert("format".into(), json!("decimal"));
1557 schema.insert("x-precision".into(), json!(precision));
1558 schema.insert("x-scale".into(), json!(scale));
1559 }
1560 FieldType::Boolean => {
1561 schema.insert("type".into(), json!("boolean"));
1562 }
1563 FieldType::Date => {
1564 schema.insert("type".into(), json!("string"));
1565 schema.insert("format".into(), json!("date"));
1566 }
1567 FieldType::DateTime => {
1568 schema.insert("type".into(), json!("string"));
1569 schema.insert("format".into(), json!("date-time"));
1570 }
1571 FieldType::Json => {
1572 schema.insert("type".into(), json!(["object", "array"]));
1573 }
1574 FieldType::Enum { values } => {
1575 schema.insert("type".into(), json!("string"));
1576 schema.insert("enum".into(), json!(values));
1577 }
1578 }
1579
1580 for validator in &field.validators {
1581 match validator {
1582 Validator::MinLength(value) => {
1583 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1584 }
1585 Validator::MaxLength(value) => {
1586 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1587 }
1588 Validator::Min(value) => {
1589 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1590 }
1591 Validator::Max(value) => {
1592 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1593 }
1594 Validator::Email => {
1595 #[cfg(feature = "validator")]
1596 patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
1597 #[cfg(not(feature = "validator"))]
1598 patterns.push("@".to_string());
1599 }
1600 Validator::EmailLoose => patterns.push("@".to_string()),
1601 Validator::Phone => {
1602 #[cfg(feature = "validator")]
1603 patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
1604 #[cfg(not(feature = "validator"))]
1605 patterns.push(r"^[0-9+\-]*$".to_string());
1606 }
1607 Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
1608 Validator::Url => patterns.push(r"^https?://".to_string()),
1609 Validator::Regex(pattern) => patterns.push(pattern.clone()),
1610 Validator::Custom(_) => runtime_validators.push("custom"),
1611 }
1612 }
1613
1614 if let Some(value) = min_length {
1615 schema.insert("minLength".into(), json!(value));
1616 }
1617 if let Some(value) = max_length {
1618 schema.insert("maxLength".into(), json!(value));
1619 }
1620 if let Some(value) = minimum {
1621 schema.insert("minimum".into(), json!(value));
1622 }
1623 if let Some(value) = maximum {
1624 schema.insert("maximum".into(), json!(value));
1625 }
1626 match patterns.as_slice() {
1627 [] => {}
1628 [pattern] => {
1629 schema.insert("pattern".into(), json!(pattern));
1630 }
1631 patterns => {
1632 schema.insert(
1633 "allOf".into(),
1634 Value::Array(
1635 patterns
1636 .iter()
1637 .map(|pattern| json!({ "pattern": pattern }))
1638 .collect(),
1639 ),
1640 );
1641 }
1642 }
1643 if !runtime_validators.is_empty() {
1644 schema.insert(
1645 "x-yang-runtime-validators".into(),
1646 json!(runtime_validators),
1647 );
1648 }
1649 if let Some(relation) = &field.relation {
1650 let relation_type = match relation.relation_type {
1651 RelationType::OneToOne => "one_to_one",
1652 RelationType::OneToMany => "one_to_many",
1653 RelationType::ManyToOne => "many_to_one",
1654 RelationType::ManyToMany => "many_to_many",
1655 };
1656 schema.insert(
1657 "x-yang-relation".into(),
1658 json!({
1659 "table": relation.table,
1660 "field": relation.field,
1661 "displayFields": relation.display_fields,
1662 "type": relation_type,
1663 }),
1664 );
1665 }
1666
1667 if !field.required {
1668 if let Some(field_types) = schema.get_mut("type") {
1669 match field_types {
1670 Value::String(field_type) => {
1671 *field_types = json!([field_type.clone(), "null"]);
1672 }
1673 Value::Array(types) if !types.iter().any(|value| value == "null") => {
1674 types.push(json!("null"));
1675 }
1676 _ => {}
1677 }
1678 }
1679 if let Some(Value::Array(values)) = schema.get_mut("enum") {
1680 values.push(Value::Null);
1681 }
1682 }
1683 if !field.display_name.is_empty() {
1684 schema.insert("title".into(), json!(field.display_name));
1685 }
1686 if let Some(default) = &field.default_value {
1687 schema.insert("default".into(), default.clone());
1688 }
1689 Value::Object(schema)
1690}