1use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{
9 CheckConfig, ForeignKeyConfig, IndexConfig, TableConfig, TimestampFields,
10};
11#[cfg(any(feature = "mysql", feature = "postgres"))]
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 generated(mut self, expression: impl Into<String>) -> Self {
117 self.config.generated = Some(expression.into());
118 self.config.permissions.writable = Audience::Nobody;
119 self
120 }
121
122 pub fn comment(mut self, comment: impl Into<String>) -> Self {
124 self.config.comment = Some(comment.into());
125 self
126 }
127
128 pub fn collation(mut self, collation: impl Into<String>) -> Self {
130 self.config.collation = Some(collation.into());
131 self
132 }
133
134 pub fn id(name: impl Into<String>) -> Self {
136 Self::new(name, FieldType::BigInt)
137 .required()
138 .primary_key()
139 .auto_increment()
140 .not_writable()
141 }
142
143 pub fn string(name: impl Into<String>, max_length: usize) -> Self {
145 Self::new(name, FieldType::String { max_length })
146 }
147
148 pub fn integer(name: impl Into<String>) -> Self {
150 Self::new(name, FieldType::Integer)
151 }
152
153 pub fn bigint(name: impl Into<String>) -> Self {
155 Self::new(name, FieldType::BigInt)
156 }
157
158 pub fn float(name: impl Into<String>) -> Self {
160 Self::new(name, FieldType::Float)
161 }
162
163 pub fn double(name: impl Into<String>) -> Self {
165 Self::new(name, FieldType::Double)
166 }
167
168 pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
170 Self::new(name, FieldType::Decimal { precision, scale })
171 }
172
173 pub fn boolean(name: impl Into<String>) -> Self {
175 Self::new(name, FieldType::Boolean)
176 }
177
178 pub fn date(name: impl Into<String>) -> Self {
180 Self::new(name, FieldType::Date)
181 }
182
183 pub fn datetime(name: impl Into<String>) -> Self {
185 Self::new(name, FieldType::DateTime)
186 }
187
188 pub fn timestamp(name: impl Into<String>) -> Self {
190 Self::new(name, FieldType::Timestamp)
191 }
192
193 pub fn json(name: impl Into<String>) -> Self {
195 Self::new(name, FieldType::Json)
196 }
197
198 pub fn text(name: impl Into<String>) -> Self {
200 Self::new(name, FieldType::Text)
201 }
202
203 pub fn uuid(name: impl Into<String>) -> Self {
205 Self::new(name, FieldType::Uuid)
206 }
207
208 pub fn bytes(name: impl Into<String>) -> Self {
210 Self::new(name, FieldType::Bytes)
211 }
212
213 pub fn array(name: impl Into<String>, element: FieldType) -> Self {
215 Self::new(name, FieldType::Array(Box::new(element)))
216 }
217
218 pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
220 where
221 I: IntoIterator<Item = S>,
222 S: Into<String>,
223 {
224 Self::new(
225 name,
226 FieldType::Enum {
227 values: values.into_iter().map(Into::into).collect(),
228 },
229 )
230 }
231
232 pub fn created_at(name: impl Into<String>) -> Self {
234 let mut field = Self::bigint(name).required().not_writable();
235 field.created_at = true;
236 field
237 }
238
239 pub fn updated_at(name: impl Into<String>) -> Self {
241 let mut field = Self::bigint(name).required().not_writable();
242 field.updated_at = true;
243 field
244 }
245
246 pub fn soft_delete(name: impl Into<String>) -> Self {
248 let mut field = Self::bigint(name).not_writable();
249 field.deleted_at = true;
250 field.soft_delete = true;
251 field
252 }
253
254 pub fn label(mut self, label: impl Into<String>) -> Self {
256 self.config.display_name = label.into();
257 self
258 }
259
260 pub fn required(mut self) -> Self {
262 self.config.required = true;
263 self
264 }
265
266 pub fn nullable(mut self) -> Self {
268 self.config.required = false;
269 self
270 }
271
272 pub fn default(mut self, value: impl Into<Value>) -> Self {
274 self.config.default_value = Some(value.into());
275 self
276 }
277
278 pub fn auto_increment(mut self) -> Self {
280 self.config.auto_increment = true;
281 self
282 }
283
284 pub fn primary_key(mut self) -> Self {
286 self.primary_key = true;
287 self
288 }
289
290 pub fn unique(mut self) -> Self {
292 self.unique = true;
293 self
294 }
295
296 pub fn unique_named(mut self, name: impl Into<String>) -> Self {
298 self.unique = true;
299 self.unique_name = Some(name.into());
300 self
301 }
302
303 pub fn index(mut self) -> Self {
305 self.index = true;
306 self
307 }
308
309 pub fn index_named(mut self, name: impl Into<String>) -> Self {
311 self.index = true;
312 self.index_name = Some(name.into());
313 self
314 }
315
316 pub fn validator(mut self, validator: Validator) -> Self {
318 self.config.validators.push(validator);
319 self
320 }
321
322 pub fn min_length(self, value: usize) -> Self {
324 self.validator(Validator::MinLength(value))
325 }
326
327 pub fn max_length(self, value: usize) -> Self {
329 self.validator(Validator::MaxLength(value))
330 }
331
332 pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
334 self.min_length(*range.start()).max_length(*range.end())
335 }
336
337 pub fn min(self, value: f64) -> Self {
339 self.validator(Validator::Min(value))
340 }
341
342 pub fn max(self, value: f64) -> Self {
344 self.validator(Validator::Max(value))
345 }
346
347 pub fn email(self) -> Self {
349 self.validator(Validator::Email)
350 }
351
352 pub fn phone(self) -> Self {
354 self.validator(Validator::Phone)
355 }
356
357 pub fn url(self) -> Self {
359 self.validator(Validator::Url)
360 }
361
362 pub fn regex(self, pattern: impl Into<String>) -> Self {
364 self.validator(Validator::Regex(pattern.into()))
365 }
366
367 pub fn readable(mut self) -> Self {
369 self.config.permissions.readable = Audience::Everyone;
370 self
371 }
372
373 pub fn not_readable(mut self) -> Self {
375 self.config.permissions.readable = Audience::Nobody;
376 self
377 }
378
379 pub fn readable_by<I, S>(mut self, roles: I) -> Self
381 where
382 I: IntoIterator<Item = S>,
383 S: Into<String>,
384 {
385 self.config.permissions.readable = Audience::roles(roles);
386 self
387 }
388
389 pub fn writable_by<I, S>(mut self, roles: I) -> Self
391 where
392 I: IntoIterator<Item = S>,
393 S: Into<String>,
394 {
395 self.config.permissions.writable = Audience::roles(roles);
396 self
397 }
398
399 pub fn writable(mut self) -> Self {
401 self.config.permissions.writable = Audience::Everyone;
402 self
403 }
404
405 pub fn not_writable(mut self) -> Self {
407 self.config.permissions.writable = Audience::Nobody;
408 self
409 }
410
411 pub fn searchable(mut self) -> Self {
417 self.config.searchable = true;
418 self
419 }
420
421 pub fn filterable(mut self) -> Self {
423 self.config.filterable = true;
424 self.config.permissions.filterable = Audience::Everyone;
425 self
426 }
427
428 pub fn not_filterable(mut self) -> Self {
430 self.config.filterable = false;
431 self.config.permissions.filterable = Audience::Nobody;
432 self
433 }
434
435 pub fn filterable_by<I, S>(mut self, roles: I) -> Self
437 where
438 I: IntoIterator<Item = S>,
439 S: Into<String>,
440 {
441 self.config.filterable = true;
442 self.config.permissions.filterable = Audience::roles(roles);
443 self
444 }
445
446 pub fn sortable(mut self) -> Self {
448 self.config.sortable = true;
449 self.config.permissions.sortable = Audience::Everyone;
450 self
451 }
452
453 pub fn not_sortable(mut self) -> Self {
455 self.config.sortable = false;
456 self.config.permissions.sortable = Audience::Nobody;
457 self
458 }
459
460 pub fn sortable_by<I, S>(mut self, roles: I) -> Self
462 where
463 I: IntoIterator<Item = S>,
464 S: Into<String>,
465 {
466 self.config.sortable = true;
467 self.config.permissions.sortable = Audience::roles(roles);
468 self
469 }
470
471 pub fn tenant_key(mut self) -> Self {
473 self.config.tenant_key = true;
474 self
475 }
476
477 pub fn secret(mut self) -> Self {
483 self.config.hidden = true;
484 self.config.permissions = FieldPermissions {
485 readable: Audience::Nobody,
486 writable: Audience::Nobody,
487 filterable: Audience::Nobody,
488 sortable: Audience::Nobody,
489 };
490 self.config.searchable = false;
491 self.config.filterable = false;
492 self.config.sortable = false;
493 self
494 }
495
496 pub fn relation(
498 mut self,
499 table: impl Into<String>,
500 field: impl Into<String>,
501 relation_type: RelationType,
502 ) -> Self {
503 self.config.relation = Some(RelationConfig {
504 table: table.into(),
505 field: field.into(),
506 display_fields: Vec::new(),
507 relation_type,
508 });
509 self
510 }
511
512 pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
514 where
515 I: IntoIterator<Item = S>,
516 S: Into<String>,
517 {
518 self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
519 self
520 }
521}
522
523#[derive(Debug, Clone)]
524struct PendingIndex {
525 name: Option<String>,
526 fields: Vec<String>,
527 unique: bool,
528 nulls_not_distinct: bool,
529}
530
531#[derive(Debug, Clone)]
532struct PendingCheck {
533 name: String,
534 expression: String,
535}
536
537#[derive(Debug, Clone)]
538struct PendingForeignKey {
539 name: String,
540 columns: Vec<String>,
541 referenced_table: String,
542 referenced_columns: Vec<String>,
543}
544
545#[derive(Debug, Clone)]
547#[must_use = "表构建器必须调用 build"]
548pub struct Table {
549 name: String,
550 label: Option<String>,
551 fields: Vec<Field>,
552 indexes: Vec<PendingIndex>,
553 checks: Vec<PendingCheck>,
554 foreign_keys: Vec<PendingForeignKey>,
555 default_order: Vec<Order>,
556}
557
558impl Table {
559 pub fn new(name: impl Into<String>) -> Self {
561 Self {
562 name: name.into(),
563 label: None,
564 fields: Vec::new(),
565 indexes: Vec::new(),
566 checks: Vec::new(),
567 foreign_keys: Vec::new(),
568 default_order: Vec::new(),
569 }
570 }
571
572 pub fn label(mut self, label: impl Into<String>) -> Self {
574 self.label = Some(label.into());
575 self
576 }
577
578 pub fn fields<I>(mut self, fields: I) -> Self
580 where
581 I: IntoIterator<Item = Field>,
582 {
583 self.fields.extend(fields);
584 self
585 }
586
587 pub fn unique<I, C>(mut self, fields: I) -> Self
589 where
590 I: IntoIterator<Item = C>,
591 C: Into<ColumnName>,
592 {
593 self.indexes.push(PendingIndex {
594 name: None,
595 fields: fields
596 .into_iter()
597 .map(|field| field.into().into_name())
598 .collect(),
599 unique: true,
600 nulls_not_distinct: false,
601 });
602 self
603 }
604
605 pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
607 where
608 I: IntoIterator<Item = C>,
609 C: Into<ColumnName>,
610 {
611 self.indexes.push(PendingIndex {
612 name: Some(name.into()),
613 fields: fields
614 .into_iter()
615 .map(|field| field.into().into_name())
616 .collect(),
617 unique: true,
618 nulls_not_distinct: false,
619 });
620 self
621 }
622
623 pub fn unique_nulls_not_distinct<I, C>(mut self, fields: I) -> Self
628 where
629 I: IntoIterator<Item = C>,
630 C: Into<ColumnName>,
631 {
632 self.indexes.push(PendingIndex {
633 name: None,
634 fields: fields
635 .into_iter()
636 .map(|field| field.into().into_name())
637 .collect(),
638 unique: true,
639 nulls_not_distinct: true,
640 });
641 self
642 }
643
644 pub fn unique_named_nulls_not_distinct<I, C>(
646 mut self,
647 name: impl Into<String>,
648 fields: I,
649 ) -> Self
650 where
651 I: IntoIterator<Item = C>,
652 C: Into<ColumnName>,
653 {
654 self.indexes.push(PendingIndex {
655 name: Some(name.into()),
656 fields: fields
657 .into_iter()
658 .map(|field| field.into().into_name())
659 .collect(),
660 unique: true,
661 nulls_not_distinct: true,
662 });
663 self
664 }
665
666 pub fn index<I, C>(mut self, fields: I) -> Self
668 where
669 I: IntoIterator<Item = C>,
670 C: Into<ColumnName>,
671 {
672 self.indexes.push(PendingIndex {
673 name: None,
674 fields: fields
675 .into_iter()
676 .map(|field| field.into().into_name())
677 .collect(),
678 unique: false,
679 nulls_not_distinct: false,
680 });
681 self
682 }
683
684 pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
686 where
687 I: IntoIterator<Item = C>,
688 C: Into<ColumnName>,
689 {
690 self.indexes.push(PendingIndex {
691 name: Some(name.into()),
692 fields: fields
693 .into_iter()
694 .map(|field| field.into().into_name())
695 .collect(),
696 unique: false,
697 nulls_not_distinct: false,
698 });
699 self
700 }
701
702 pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
706 self.checks.push(PendingCheck {
707 name: name.into(),
708 expression: expression.into(),
709 });
710 self
711 }
712
713 pub fn foreign_key_named<I, C, R, RC>(
715 mut self,
716 name: impl Into<String>,
717 columns: I,
718 referenced_table: impl Into<String>,
719 referenced_columns: R,
720 ) -> Self
721 where
722 I: IntoIterator<Item = C>,
723 C: Into<ColumnName>,
724 R: IntoIterator<Item = RC>,
725 RC: Into<ColumnName>,
726 {
727 self.foreign_keys.push(PendingForeignKey {
728 name: name.into(),
729 columns: columns
730 .into_iter()
731 .map(|column| column.into().into_name())
732 .collect(),
733 referenced_table: referenced_table.into(),
734 referenced_columns: referenced_columns
735 .into_iter()
736 .map(|column| column.into().into_name())
737 .collect(),
738 });
739 self
740 }
741
742 pub fn default_order(mut self, order: Order) -> Self {
744 self.default_order = vec![order];
745 self
746 }
747
748 pub fn then_order(mut self, order: Order) -> Self {
750 self.default_order.push(order);
751 self
752 }
753
754 pub fn build(self) -> Result<TableDefinition, BaseError> {
756 validate_identifier("表", &self.name)?;
757 if self.fields.is_empty() {
758 return Err(BaseError::ConfigError(format!(
759 "表 {} 至少需要一个字段",
760 self.name
761 )));
762 }
763
764 let mut field_names = HashSet::with_capacity(self.fields.len());
765 let mut legacy_names = HashSet::new();
766 let mut configs = HashMap::with_capacity(self.fields.len());
767 let mut primary_key: Option<String> = None;
768 let mut created_at: Option<String> = None;
769 let mut updated_at: Option<String> = None;
770 let mut deleted_at: Option<String> = None;
771 let mut soft_delete: Option<String> = None;
772 let mut tenant_key: Option<String> = None;
773 let mut indexes = self.indexes;
774 let checks = self.checks;
775 let foreign_keys = self.foreign_keys;
776 let regex_cache = RegexCache::default();
778
779 for mut field in self.fields {
780 validate_identifier("字段", &field.config.name)?;
781 if !field_names.insert(field.config.name.clone()) {
782 return Err(BaseError::ConfigError(format!(
783 "表 {} 存在重复字段: {}",
784 self.name, field.config.name
785 )));
786 }
787 if let Some(legacy_name) = field.config.renamed_from.as_deref() {
788 validate_identifier("旧字段", legacy_name)?;
789 if legacy_name == field.config.name || !legacy_names.insert(legacy_name.to_string())
790 {
791 return Err(BaseError::ConfigError(format!(
792 "表 {} 的旧字段改名来源重复或未发生改名: {}",
793 self.name, legacy_name
794 )));
795 }
796 }
797 if field.config.display_name.is_empty() {
798 field.config.display_name = field.config.name.clone();
799 }
800 if let Some(display_fields) = field.relation_display_fields.take() {
801 let relation = field.config.relation.as_mut().ok_or_else(|| {
802 BaseError::ConfigError(format!(
803 "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
804 self.name, field.config.name
805 ))
806 })?;
807 relation.display_fields = display_fields;
808 }
809 validate_field_shape(&self.name, &field, ®ex_cache)?;
810
811 if field.primary_key && primary_key.replace(field.config.name.clone()).is_some() {
812 return Err(BaseError::ConfigError(format!(
813 "表 {} 只能定义一个主键",
814 self.name
815 )));
816 }
817 if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
818 return Err(BaseError::ConfigError(format!(
819 "表 {} 只能定义一个租户隔离字段",
820 self.name
821 )));
822 }
823 set_unique_role(
824 &self.name,
825 "created_at",
826 field.created_at,
827 &field.config.name,
828 &mut created_at,
829 )?;
830 set_unique_role(
831 &self.name,
832 "updated_at",
833 field.updated_at,
834 &field.config.name,
835 &mut updated_at,
836 )?;
837 set_unique_role(
838 &self.name,
839 "deleted_at",
840 field.deleted_at,
841 &field.config.name,
842 &mut deleted_at,
843 )?;
844 set_unique_role(
845 &self.name,
846 "soft_delete",
847 field.soft_delete,
848 &field.config.name,
849 &mut soft_delete,
850 )?;
851
852 if field.unique {
853 indexes.push(PendingIndex {
854 name: field.unique_name.take(),
855 fields: vec![field.config.name.clone()],
856 unique: true,
857 nulls_not_distinct: false,
858 });
859 }
860 if field.index {
861 indexes.push(PendingIndex {
862 name: field.index_name.take(),
863 fields: vec![field.config.name.clone()],
864 unique: false,
865 nulls_not_distinct: false,
866 });
867 }
868 configs.insert(field.config.name.clone(), field.config);
869 }
870
871 if let Some(legacy_name) = legacy_names
872 .iter()
873 .find(|legacy_name| field_names.contains(legacy_name.as_str()))
874 {
875 return Err(BaseError::ConfigError(format!(
876 "表 {} 同时声明旧字段与改名后字段: {}",
877 self.name, legacy_name
878 )));
879 }
880
881 let primary_key = primary_key
882 .ok_or_else(|| BaseError::ConfigError(format!("表 {} 必须定义一个主键", self.name)))?;
883
884 let mut unique_indexes = Vec::new();
885 let mut normal_indexes = Vec::new();
886 let mut index_names = HashSet::new();
887 for index in indexes {
888 validate_index(&self.name, &field_names, &index, &mut index_names)?;
889 let config = IndexConfig::new(index.name, index.fields, index.nulls_not_distinct);
890 if index.unique {
891 unique_indexes.push(config);
892 } else {
893 normal_indexes.push(config);
894 }
895 }
896
897 let mut constraint_names = HashSet::new();
898 let checks = checks
899 .into_iter()
900 .map(|check| {
901 validate_constraint_name(&self.name, &check.name, &mut constraint_names)?;
902 validate_check_expression(&self.name, &check.name, &check.expression)?;
903 Ok(CheckConfig {
904 name: check.name,
905 expression: check.expression,
906 })
907 })
908 .collect::<Result<Vec<_>, BaseError>>()?;
909 let foreign_keys = foreign_keys
910 .into_iter()
911 .map(|foreign_key| {
912 validate_constraint_name(&self.name, &foreign_key.name, &mut constraint_names)?;
913 validate_foreign_key(&self.name, &field_names, &foreign_key)?;
914 Ok(ForeignKeyConfig {
915 name: foreign_key.name,
916 columns: foreign_key.columns,
917 referenced_table: foreign_key.referenced_table,
918 referenced_columns: foreign_key.referenced_columns,
919 })
920 })
921 .collect::<Result<Vec<_>, BaseError>>()?;
922
923 let mut orders = Vec::with_capacity(self.default_order.len());
924 for order in self.default_order {
925 if !field_names.contains(&order.field) {
926 return Err(BaseError::ConfigError(format!(
927 "表 {} 的默认排序字段不存在: {}",
928 self.name, order.field
929 )));
930 }
931 orders.push((order.field, order.direction));
932 }
933
934 let timestamp_fields =
935 if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
936 Some(TimestampFields::new(created_at, updated_at, deleted_at))
937 } else {
938 None
939 };
940 let table_ref = yang_db::TableRef::new(self.name.clone())
941 .map_err(|error| BaseError::ConfigError(error.to_string()))?;
942 let field_refs = field_names
943 .iter()
944 .map(|name| {
945 yang_db::FieldRef::new(name.clone())
946 .map(|field| (name.clone(), field))
947 .map_err(|error| BaseError::ConfigError(error.to_string()))
948 })
949 .collect::<Result<HashMap<_, _>, _>>()?;
950
951 Ok(TableDefinition {
952 config: Arc::new(TableConfig {
953 table_name: self.name.clone(),
954 table_ref,
955 display_name: self.label.unwrap_or(self.name),
956 primary_key,
957 fields: configs,
958 field_refs,
959 unique_indexes,
960 indexes: normal_indexes,
961 checks,
962 foreign_keys,
963 default_order: orders,
964 soft_delete_field: soft_delete,
965 timestamp_fields,
966 }),
967 })
968 }
969}
970
971#[derive(Debug, Clone)]
973pub struct TableDefinition {
974 pub(crate) config: Arc<TableConfig>,
975}
976
977impl TableDefinition {
978 pub fn name(&self) -> &str {
980 &self.config.table_name
981 }
982
983 pub fn label(&self) -> &str {
985 &self.config.display_name
986 }
987
988 pub fn primary_key(&self) -> &str {
990 &self.config.primary_key
991 }
992
993 pub fn field_count(&self) -> usize {
995 self.config.fields.len()
996 }
997
998 pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
1000 self.config
1001 .fields
1002 .get(name)
1003 .map(|config| FieldMetadata { config })
1004 }
1005
1006 pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
1008 let mut fields: Vec<_> = self
1009 .config
1010 .fields
1011 .values()
1012 .map(|config| FieldMetadata { config })
1013 .collect();
1014 fields.sort_by(|left, right| left.name().cmp(right.name()));
1015 fields
1016 }
1017
1018 pub fn soft_delete_field(&self) -> Option<&str> {
1020 self.config.soft_delete_field.as_deref()
1021 }
1022
1023 pub fn tenant_key_field(&self) -> Option<&str> {
1025 self.config
1026 .fields
1027 .values()
1028 .find(|field| field.tenant_key)
1029 .map(|field| field.name.as_str())
1030 }
1031
1032 pub fn input_schema(&self) -> Value {
1037 self.json_schema(false, None)
1038 }
1039
1040 pub fn output_schema(&self) -> Value {
1045 self.json_schema(true, None)
1046 }
1047
1048 pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1050 self.json_schema(false, Some(roles))
1051 }
1052
1053 pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1055 self.json_schema(true, Some(roles))
1056 }
1057
1058 #[cfg(any(feature = "mysql", feature = "postgres"))]
1060 pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
1061 self.config.fields.get(name).map(field_json_schema)
1062 }
1063
1064 fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
1065 let mut properties = Map::new();
1066 let mut required = Vec::new();
1067 let mut names: Vec<_> = self.config.fields.keys().collect();
1068 names.sort();
1069 for name in names {
1070 let field = &self.config.fields[name];
1071 let generated = field.auto_increment
1072 || self
1073 .config
1074 .timestamp_fields
1075 .as_ref()
1076 .is_some_and(|timestamps| {
1077 timestamps.created_at.as_deref() == Some(name.as_str())
1078 || timestamps.updated_at.as_deref() == Some(name.as_str())
1079 || timestamps.deleted_at.as_deref() == Some(name.as_str())
1080 })
1081 || self.config.soft_delete_field.as_deref() == Some(name.as_str());
1082 let audience = if output {
1083 &field.permissions.readable
1084 } else {
1085 &field.permissions.writable
1086 };
1087 let audience_allows = roles.map_or_else(
1088 || !matches!(audience, Audience::Nobody),
1089 |roles| audience.allows(roles),
1090 );
1091 if field.hidden || !audience_allows || (!output && generated) {
1092 continue;
1093 }
1094 properties.insert(name.clone(), field_json_schema(field));
1095 if field.required && (output || (!generated && field.default_value.is_none())) {
1096 required.push(Value::String(name.clone()));
1097 }
1098 }
1099 json!({
1100 "type": "object",
1101 "title": self.config.display_name,
1102 "properties": properties,
1103 "required": required,
1104 "additionalProperties": false,
1105 })
1106 }
1107
1108 #[cfg(feature = "mysql")]
1109 pub(crate) fn config(&self) -> &TableConfig {
1110 &self.config
1111 }
1112
1113 pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
1114 Arc::clone(&self.config)
1115 }
1116
1117 pub fn validate_schema(
1119 &self,
1120 columns: &[super::SchemaColumn],
1121 ) -> super::SchemaValidationReport {
1122 self.config.validate_schema(columns)
1123 }
1124
1125 #[cfg(feature = "mysql")]
1130 pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
1131 self.bind_pool(crate::database::AnyPool::MySql(pool))
1132 }
1133
1134 #[cfg(any(feature = "mysql", feature = "postgres"))]
1136 pub fn bind_pool(&self, pool: crate::database::AnyPool) -> TableHandle {
1137 TableHandle {
1138 definition: self.clone(),
1139 pool,
1140 }
1141 }
1142}
1143
1144#[derive(Debug, Clone, Copy)]
1146pub struct FieldMetadata<'a> {
1147 config: &'a FieldConfig,
1148}
1149
1150impl<'a> FieldMetadata<'a> {
1151 pub fn name(self) -> &'a str {
1153 &self.config.name
1154 }
1155
1156 pub fn label(self) -> &'a str {
1158 &self.config.display_name
1159 }
1160
1161 pub fn is_tenant_key(self) -> bool {
1163 self.config.tenant_key
1164 }
1165
1166 pub fn field_type(self) -> &'a FieldType {
1168 &self.config.field_type
1169 }
1170
1171 pub fn is_required(self) -> bool {
1173 self.config.required
1174 }
1175
1176 pub fn default_value(self) -> Option<&'a Value> {
1178 self.config.default_value.as_ref()
1179 }
1180
1181 pub fn is_auto_increment(self) -> bool {
1183 self.config.auto_increment
1184 }
1185
1186 pub fn is_searchable(self) -> bool {
1188 self.config.searchable
1189 }
1190
1191 pub fn is_filterable(self) -> bool {
1193 self.config.filterable
1194 }
1195
1196 pub fn is_sortable(self) -> bool {
1198 self.config.sortable
1199 }
1200
1201 pub fn is_secret(self) -> bool {
1203 self.config.hidden
1204 }
1205}
1206
1207#[cfg(any(feature = "mysql", feature = "postgres"))]
1209#[derive(Debug, Clone)]
1210pub struct TableHandle {
1211 definition: TableDefinition,
1212 pool: crate::database::AnyPool,
1213}
1214
1215#[cfg(any(feature = "mysql", feature = "postgres"))]
1216impl TableHandle {
1217 pub fn definition(&self) -> &TableDefinition {
1219 &self.definition
1220 }
1221
1222 pub fn query<I, S>(&self, roles: I) -> TableQuery
1224 where
1225 I: IntoIterator<Item = S>,
1226 S: Into<String>,
1227 {
1228 let roles: Arc<[String]> =
1229 Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1230 TableQuery::new(
1231 self.definition.shared_config(),
1232 roles,
1233 Some(self.pool.clone()),
1234 )
1235 }
1236}
1237
1238fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1239 let mut chars = value.chars();
1240 let first = chars
1241 .next()
1242 .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1243 if value.len() > 64
1244 || !(first == '_' || first.is_ascii_alphabetic())
1245 || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1246 {
1247 return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1248 }
1249 Ok(())
1250}
1251
1252fn has_balanced_generated_expression(expression: &str) -> bool {
1258 let bytes = expression.as_bytes();
1259 let mut depth: i32 = 0;
1260 let mut index = 0;
1261 while index < bytes.len() {
1262 match bytes[index] {
1263 b'\'' => {
1264 let escape_string = is_escape_string_prefix(bytes, index);
1265 index += 1;
1266 while index < bytes.len() {
1267 if escape_string && bytes[index] == b'\\' {
1268 index = (index + 2).min(bytes.len());
1270 continue;
1271 }
1272 if bytes[index] == b'\'' {
1273 if bytes.get(index + 1) == Some(&b'\'') {
1274 index += 2;
1275 continue;
1276 }
1277 index += 1;
1278 break;
1279 }
1280 index += 1;
1281 }
1282 }
1283 b'"' => {
1284 index += 1;
1285 while index < bytes.len() {
1286 if bytes[index] == b'"' {
1287 if bytes.get(index + 1) == Some(&b'"') {
1288 index += 2;
1289 continue;
1290 }
1291 index += 1;
1292 break;
1293 }
1294 index += 1;
1295 }
1296 }
1297 b'(' => {
1298 depth += 1;
1299 index += 1;
1300 }
1301 b')' => {
1302 depth -= 1;
1303 if depth < 0 {
1304 return false;
1305 }
1306 index += 1;
1307 }
1308 _ => index += 1,
1309 }
1310 }
1311 depth == 0
1312}
1313
1314fn is_escape_string_prefix(bytes: &[u8], quote_index: usize) -> bool {
1316 if quote_index == 0 || !matches!(bytes[quote_index - 1], b'E' | b'e') {
1317 return false;
1318 }
1319 quote_index == 1 || !is_identifier_byte(bytes[quote_index - 2])
1320}
1321
1322fn is_identifier_byte(byte: u8) -> bool {
1323 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' || byte >= 0x80
1324}
1325
1326fn has_balanced_check_expression(expression: &str) -> bool {
1333 has_balanced_pg_check_expression(expression) || has_balanced_mysql_check_expression(expression)
1337}
1338
1339pub(crate) fn has_balanced_pg_check_expression(expression: &str) -> bool {
1344 let bytes = expression.as_bytes();
1345 let mut depth: i32 = 0;
1346 let mut index = 0;
1347 while index < bytes.len() {
1348 match bytes[index] {
1349 b'\'' => {
1350 let backslash_escapes =
1351 is_escape_string_prefix(bytes, index) || is_unicode_escape_prefix(bytes, index);
1352 if !skip_quoted(bytes, &mut index, b'\'', backslash_escapes) {
1353 return false;
1354 }
1355 }
1356 b'"' => {
1357 let backslash_escapes = is_unicode_escape_prefix(bytes, index);
1358 if !skip_quoted(bytes, &mut index, b'"', backslash_escapes) {
1359 return false;
1360 }
1361 }
1362 b'$' => {
1363 let Some(tag_end) = dollar_quote_tag_end(bytes, index) else {
1364 index += 1;
1365 continue;
1366 };
1367 let tag = &bytes[index..tag_end];
1368 let mut cursor = tag_end;
1369 loop {
1370 if cursor + tag.len() > bytes.len() {
1371 return false;
1373 }
1374 if &bytes[cursor..cursor + tag.len()] == tag {
1375 index = cursor + tag.len();
1376 break;
1377 }
1378 cursor += 1;
1379 }
1380 }
1381 b'(' => {
1382 depth += 1;
1383 index += 1;
1384 }
1385 b')' => {
1386 depth -= 1;
1387 if depth < 0 {
1388 return false;
1389 }
1390 index += 1;
1391 }
1392 _ => index += 1,
1393 }
1394 }
1395 depth == 0
1396}
1397
1398pub(crate) fn has_balanced_mysql_check_expression(expression: &str) -> bool {
1403 let bytes = expression.as_bytes();
1404 let mut depth: i32 = 0;
1405 let mut index = 0;
1406 while index < bytes.len() {
1407 match bytes[index] {
1408 b'\'' => {
1409 if !skip_quoted(bytes, &mut index, b'\'', true) {
1410 return false;
1411 }
1412 }
1413 b'"' => {
1414 if !skip_quoted(bytes, &mut index, b'"', true) {
1415 return false;
1416 }
1417 }
1418 b'`' => {
1419 if !skip_quoted(bytes, &mut index, b'`', false) {
1420 return false;
1421 }
1422 }
1423 b'#' => {
1424 while index < bytes.len() && bytes[index] != b'\n' {
1425 index += 1;
1426 }
1427 }
1428 b'(' => {
1429 depth += 1;
1430 index += 1;
1431 }
1432 b')' => {
1433 depth -= 1;
1434 if depth < 0 {
1435 return false;
1436 }
1437 index += 1;
1438 }
1439 _ => index += 1,
1440 }
1441 }
1442 depth == 0
1443}
1444
1445fn skip_quoted(bytes: &[u8], index: &mut usize, delimiter: u8, backslash_escapes: bool) -> bool {
1449 *index += 1;
1450 while *index < bytes.len() {
1451 if backslash_escapes && bytes[*index] == b'\\' {
1452 *index = (*index + 2).min(bytes.len());
1453 continue;
1454 }
1455 if bytes[*index] == delimiter {
1456 if bytes.get(*index + 1) == Some(&delimiter) {
1457 *index += 2;
1458 continue;
1459 }
1460 *index += 1;
1461 return true;
1462 }
1463 *index += 1;
1464 }
1465 false
1466}
1467
1468fn is_unicode_escape_prefix(bytes: &[u8], quote_index: usize) -> bool {
1470 if quote_index < 2
1471 || bytes[quote_index - 1] != b'&'
1472 || !matches!(bytes[quote_index - 2], b'U' | b'u')
1473 {
1474 return false;
1475 }
1476 quote_index < 3 || !is_identifier_byte(bytes[quote_index - 3])
1477}
1478
1479fn dollar_quote_tag_end(bytes: &[u8], start: usize) -> Option<usize> {
1481 let mut index = start + 1;
1482 let first = bytes.get(index)?;
1483 if *first == b'$' {
1484 return Some(index + 1);
1486 }
1487 if !(*first == b'_' || first.is_ascii_alphabetic() || *first >= 0x80) {
1488 return None;
1489 }
1490 index += 1;
1491 while let Some(byte) = bytes.get(index) {
1492 if byte.is_ascii_alphanumeric() || *byte == b'_' || *byte >= 0x80 {
1493 index += 1;
1494 } else {
1495 break;
1496 }
1497 }
1498 (bytes.get(index) == Some(&b'$')).then_some(index + 1)
1499}
1500
1501fn validate_field_shape(table: &str, field: &Field, cache: &RegexCache) -> Result<(), BaseError> {
1502 match &field.config.field_type {
1503 FieldType::String { max_length } if !(1..=MAX_VARCHAR_LENGTH).contains(max_length) => {
1504 return Err(BaseError::ConfigError(format!(
1505 "表 {table} 的字符串字段 {} 长度必须在 1..={MAX_VARCHAR_LENGTH}(更长内容请使用 Text 字段)",
1506 field.config.name
1507 )));
1508 }
1509 FieldType::Enum { values } => {
1510 let unique: HashSet<_> = values.iter().collect();
1511 if values.is_empty() || unique.len() != values.len() {
1512 return Err(BaseError::ConfigError(format!(
1513 "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1514 field.config.name
1515 )));
1516 }
1517 }
1518 FieldType::Decimal { precision, scale }
1519 if *precision == 0 || *precision > 65 || *scale > *precision =>
1520 {
1521 return Err(BaseError::ConfigError(format!(
1522 "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1523 field.config.name
1524 )));
1525 }
1526 FieldType::Array(element) if matches!(**element, FieldType::Array(_) | FieldType::Json) => {
1527 return Err(BaseError::ConfigError(format!(
1528 "表 {table} 的数组字段 {} 只支持标量元素,不支持嵌套数组或 JSON 元素",
1529 field.config.name
1530 )));
1531 }
1532 _ => {}
1533 }
1534
1535 if field.config.auto_increment
1536 && (!field.primary_key
1537 || !matches!(
1538 field.config.field_type,
1539 FieldType::Integer | FieldType::BigInt
1540 ))
1541 {
1542 return Err(BaseError::ConfigError(format!(
1543 "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1544 field.config.name
1545 )));
1546 }
1547 if field.primary_key && !field.config.required {
1548 return Err(BaseError::ConfigError(format!(
1549 "表 {table} 的主键必须为必填字段: {}",
1550 field.config.name
1551 )));
1552 }
1553 if field.config.auto_increment && field.config.default_value.is_some() {
1554 return Err(BaseError::ConfigError(format!(
1555 "表 {table} 的自增字段不能配置默认值: {}",
1556 field.config.name
1557 )));
1558 }
1559 if let Some(expression) = &field.config.generated {
1560 let expression = expression.trim();
1561 if expression.is_empty()
1562 || expression.chars().count() > 2_048
1563 || [";", "--", "/*", "*/"]
1564 .iter()
1565 .any(|marker| expression.contains(marker))
1566 || !has_balanced_generated_expression(expression)
1567 {
1568 return Err(BaseError::ConfigError(format!(
1569 "表 {table} 的生成列 {} 必须是单条、非空、长度受限且括号平衡的受信表达式",
1570 field.config.name
1571 )));
1572 }
1573 if field.config.auto_increment || field.config.default_value.is_some() {
1574 return Err(BaseError::ConfigError(format!(
1575 "表 {table} 的生成列 {} 不能同时声明自增或默认值",
1576 field.config.name
1577 )));
1578 }
1579 }
1580 if let Some(collation) = &field.config.collation {
1581 if collation.trim().is_empty() || collation.len() > 128 {
1582 return Err(BaseError::ConfigError(format!(
1583 "表 {table} 的字段 {} 声明了空或过长的 collation",
1584 field.config.name
1585 )));
1586 }
1587 }
1588 validate_validator_configuration(table, &field.config)?;
1589 if let Some(default) = &field.config.default_value {
1590 if matches!(
1591 field.config.field_type,
1592 FieldType::Text | FieldType::Json | FieldType::Bytes | FieldType::Array(_)
1593 ) {
1594 return Err(BaseError::ConfigError(format!(
1595 "表 {table} 的 TEXT/JSON/BYTES/ARRAY 字段不能配置数据库默认值: {}",
1596 field.config.name
1597 )));
1598 }
1599 field.config.validate(default, cache)?;
1600 }
1601 validate_audience(
1602 table,
1603 &field.config.name,
1604 "读取",
1605 &field.config.permissions.readable,
1606 )?;
1607 validate_audience(
1608 table,
1609 &field.config.name,
1610 "写入",
1611 &field.config.permissions.writable,
1612 )?;
1613 validate_audience(
1614 table,
1615 &field.config.name,
1616 "筛选",
1617 &field.config.permissions.filterable,
1618 )?;
1619 validate_audience(
1620 table,
1621 &field.config.name,
1622 "排序",
1623 &field.config.permissions.sortable,
1624 )?;
1625 if let Some(relation) = &field.config.relation {
1626 validate_identifier("关联表", &relation.table)?;
1627 validate_identifier("关联字段", &relation.field)?;
1628 for display_field in &relation.display_fields {
1629 validate_identifier("关联展示字段", display_field)?;
1630 }
1631 }
1632 if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1633 && !matches!(
1634 field.config.field_type,
1635 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1636 )
1637 {
1638 return Err(BaseError::ConfigError(format!(
1639 "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1640 field.config.name
1641 )));
1642 }
1643 Ok(())
1644}
1645
1646fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1647 let string_compatible = matches!(
1648 field.field_type,
1649 FieldType::String { .. }
1650 | FieldType::Text
1651 | FieldType::Enum { .. }
1652 | FieldType::Date
1653 | FieldType::DateTime
1654 );
1655 let numeric_compatible = matches!(
1656 field.field_type,
1657 FieldType::Integer
1658 | FieldType::BigInt
1659 | FieldType::Float
1660 | FieldType::Double
1661 | FieldType::Decimal { .. }
1662 | FieldType::Timestamp
1663 );
1664 let mut min_length: Option<usize> = None;
1665 let mut max_length: Option<usize> = None;
1666 let mut minimum: Option<f64> = None;
1667 let mut maximum: Option<f64> = None;
1668
1669 for validator in &field.validators {
1670 match validator {
1671 Validator::MinLength(value) => {
1672 ensure_validator_type(table, field, validator, string_compatible)?;
1673 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1674 }
1675 Validator::MaxLength(value) => {
1676 ensure_validator_type(table, field, validator, string_compatible)?;
1677 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1678 }
1679 Validator::Min(value) => {
1680 ensure_validator_type(table, field, validator, numeric_compatible)?;
1681 if !value.is_finite() {
1682 return Err(BaseError::ConfigError(format!(
1683 "表 {table} 的字段 {} 数值下限必须是有限数值",
1684 field.name
1685 )));
1686 }
1687 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1688 }
1689 Validator::Max(value) => {
1690 ensure_validator_type(table, field, validator, numeric_compatible)?;
1691 if !value.is_finite() {
1692 return Err(BaseError::ConfigError(format!(
1693 "表 {table} 的字段 {} 数值上限必须是有限数值",
1694 field.name
1695 )));
1696 }
1697 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1698 }
1699 Validator::Email
1700 | Validator::EmailLoose
1701 | Validator::Phone
1702 | Validator::PhoneLoose
1703 | Validator::Url => {
1704 ensure_validator_type(table, field, validator, string_compatible)?;
1705 }
1706 Validator::Regex(pattern) => {
1707 ensure_validator_type(table, field, validator, string_compatible)?;
1708 #[cfg(feature = "validator")]
1709 regex::Regex::new(pattern).map_err(|error| {
1710 BaseError::ConfigError(format!(
1711 "表 {table} 的字段 {} 正则表达式无效: {error}",
1712 field.name
1713 ))
1714 })?;
1715 #[cfg(not(feature = "validator"))]
1716 return Err(BaseError::ConfigError(format!(
1717 "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1718 field.name,
1719 )));
1720 }
1721 Validator::Custom(_) => {}
1722 }
1723 }
1724
1725 if let (Some(min), Some(max)) = (min_length, max_length) {
1726 if min > max {
1727 return Err(BaseError::ConfigError(format!(
1728 "表 {table} 的字段 {} 最小长度不能大于最大长度",
1729 field.name
1730 )));
1731 }
1732 }
1733 if let (
1734 FieldType::String {
1735 max_length: storage_max,
1736 },
1737 Some(min),
1738 ) = (&field.field_type, min_length)
1739 {
1740 if min > *storage_max {
1741 return Err(BaseError::ConfigError(format!(
1742 "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1743 field.name
1744 )));
1745 }
1746 }
1747 if let (Some(min), Some(max)) = (minimum, maximum) {
1748 if min > max {
1749 return Err(BaseError::ConfigError(format!(
1750 "表 {table} 的字段 {} 数值下限不能大于上限",
1751 field.name
1752 )));
1753 }
1754 }
1755 Ok(())
1756}
1757
1758fn ensure_validator_type(
1759 table: &str,
1760 field: &FieldConfig,
1761 validator: &Validator,
1762 compatible: bool,
1763) -> Result<(), BaseError> {
1764 if compatible {
1765 return Ok(());
1766 }
1767 Err(BaseError::ConfigError(format!(
1768 "表 {table} 的字段 {} 类型不能使用{}验证器",
1769 field.name,
1770 validator.display_name()
1771 )))
1772}
1773
1774fn validate_audience(
1775 table: &str,
1776 field: &str,
1777 operation: &str,
1778 audience: &Audience,
1779) -> Result<(), BaseError> {
1780 if let Audience::Roles(roles) = audience {
1781 if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1782 return Err(BaseError::ConfigError(format!(
1783 "表 {table} 的字段 {field} 的{operation}角色不能为空"
1784 )));
1785 }
1786 }
1787 Ok(())
1788}
1789
1790fn set_unique_role(
1791 table: &str,
1792 role: &str,
1793 enabled: bool,
1794 field: &str,
1795 target: &mut Option<String>,
1796) -> Result<(), BaseError> {
1797 if !enabled {
1798 return Ok(());
1799 }
1800 if let Some(existing) = target {
1801 return Err(BaseError::ConfigError(format!(
1802 "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1803 )));
1804 }
1805 *target = Some(field.to_string());
1806 Ok(())
1807}
1808
1809fn validate_index(
1810 table: &str,
1811 field_names: &HashSet<String>,
1812 index: &PendingIndex,
1813 index_names: &mut HashSet<String>,
1814) -> Result<(), BaseError> {
1815 if index.fields.is_empty() {
1816 return Err(BaseError::ConfigError(format!(
1817 "表 {table} 的索引字段不能为空"
1818 )));
1819 }
1820 let mut seen = HashSet::new();
1821 for field in &index.fields {
1822 if !field_names.contains(field) {
1823 return Err(BaseError::ConfigError(format!(
1824 "表 {table} 的索引字段不存在: {field}"
1825 )));
1826 }
1827 if !seen.insert(field) {
1828 return Err(BaseError::ConfigError(format!(
1829 "表 {table} 的索引重复引用字段: {field}"
1830 )));
1831 }
1832 }
1833 let prefix = if index.unique { "uk" } else { "idx" };
1834 let effective_name = index
1835 .name
1836 .clone()
1837 .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
1838 validate_identifier("索引", &effective_name)?;
1839 if !index_names.insert(effective_name.clone()) {
1840 return Err(BaseError::ConfigError(format!(
1841 "表 {table} 存在重复索引名: {effective_name}"
1842 )));
1843 }
1844 Ok(())
1845}
1846
1847fn validate_constraint_name(
1848 table: &str,
1849 name: &str,
1850 names: &mut HashSet<String>,
1851) -> Result<(), BaseError> {
1852 validate_identifier("约束", name)?;
1853 if !names.insert(name.to_string()) {
1854 return Err(BaseError::ConfigError(format!(
1855 "表 {table} 存在重复约束名: {name}"
1856 )));
1857 }
1858 Ok(())
1859}
1860
1861fn validate_check_expression(table: &str, name: &str, expression: &str) -> Result<(), BaseError> {
1862 let expression = expression.trim();
1863 if expression.is_empty()
1864 || expression.chars().count() > 2_048
1865 || [";", "--", "/*", "*/"]
1866 .iter()
1867 .any(|marker| expression.contains(marker))
1868 || !has_balanced_check_expression(expression)
1869 {
1870 return Err(BaseError::ConfigError(format!(
1871 "表 {table} 的 CHECK {name} 必须是单条、非空、长度受限且括号平衡的受信表达式"
1872 )));
1873 }
1874 Ok(())
1875}
1876
1877fn validate_foreign_key(
1878 table: &str,
1879 field_names: &HashSet<String>,
1880 foreign_key: &PendingForeignKey,
1881) -> Result<(), BaseError> {
1882 validate_identifier("外键目标表", &foreign_key.referenced_table)?;
1883 if foreign_key.columns.is_empty()
1884 || foreign_key.columns.len() != foreign_key.referenced_columns.len()
1885 {
1886 return Err(BaseError::ConfigError(format!(
1887 "表 {table} 的外键 {} 本地列与目标列必须非空且数量一致",
1888 foreign_key.name
1889 )));
1890 }
1891 let mut local = HashSet::new();
1892 let mut referenced = HashSet::new();
1893 for column in &foreign_key.columns {
1894 validate_identifier("外键列", column)?;
1895 if !field_names.contains(column) || !local.insert(column) {
1896 return Err(BaseError::ConfigError(format!(
1897 "表 {table} 的外键 {} 引用了缺失或重复的本地列 {column}",
1898 foreign_key.name
1899 )));
1900 }
1901 }
1902 for column in &foreign_key.referenced_columns {
1903 validate_identifier("外键目标列", column)?;
1904 if !referenced.insert(column) {
1905 return Err(BaseError::ConfigError(format!(
1906 "表 {table} 的外键 {} 重复引用目标列 {column}",
1907 foreign_key.name
1908 )));
1909 }
1910 }
1911 Ok(())
1912}
1913
1914fn field_json_schema(field: &FieldConfig) -> Value {
1915 let mut schema = Map::new();
1916 let mut min_length: Option<usize> = None;
1917 let mut max_length: Option<usize> = None;
1918 let mut minimum: Option<f64> = None;
1919 let mut maximum: Option<f64> = None;
1920 let mut patterns = Vec::new();
1921 let mut runtime_validators = Vec::new();
1922 match &field.field_type {
1923 FieldType::String {
1924 max_length: storage_max,
1925 } => {
1926 schema.insert("type".into(), json!("string"));
1927 max_length = Some(*storage_max);
1928 }
1929 FieldType::Text => {
1930 schema.insert("type".into(), json!("string"));
1931 }
1932 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
1933 schema.insert("type".into(), json!("integer"));
1934 }
1935 FieldType::Float | FieldType::Double => {
1936 schema.insert("type".into(), json!("number"));
1937 }
1938 FieldType::Decimal { precision, scale } => {
1939 schema.insert("type".into(), json!("string"));
1940 schema.insert("format".into(), json!("decimal"));
1941 schema.insert("x-precision".into(), json!(precision));
1942 schema.insert("x-scale".into(), json!(scale));
1943 }
1944 FieldType::Boolean => {
1945 schema.insert("type".into(), json!("boolean"));
1946 }
1947 FieldType::Date => {
1948 schema.insert("type".into(), json!("string"));
1949 schema.insert("format".into(), json!("date"));
1950 }
1951 FieldType::DateTime => {
1952 schema.insert("type".into(), json!("string"));
1953 schema.insert("format".into(), json!("date-time"));
1954 }
1955 FieldType::Json => {
1956 schema.insert("type".into(), json!(["object", "array"]));
1957 }
1958 FieldType::Enum { values } => {
1959 schema.insert("type".into(), json!("string"));
1960 schema.insert("enum".into(), json!(values));
1961 }
1962 FieldType::Uuid => {
1963 schema.insert("type".into(), json!("string"));
1964 schema.insert("format".into(), json!("uuid"));
1965 }
1966 FieldType::Bytes => {
1967 schema.insert("type".into(), json!("string"));
1969 schema.insert("format".into(), json!("byte"));
1970 }
1971 FieldType::Array(element) => {
1972 schema.insert("type".into(), json!("array"));
1973 schema.insert("items".into(), storage_type_json_schema(element));
1974 }
1975 }
1976
1977 for validator in &field.validators {
1978 match validator {
1979 Validator::MinLength(value) => {
1980 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1981 }
1982 Validator::MaxLength(value) => {
1983 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1984 }
1985 Validator::Min(value) => {
1986 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1987 }
1988 Validator::Max(value) => {
1989 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1990 }
1991 Validator::Email => {
1992 #[cfg(feature = "validator")]
1993 patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
1994 #[cfg(not(feature = "validator"))]
1995 patterns.push("@".to_string());
1996 }
1997 Validator::EmailLoose => patterns.push("@".to_string()),
1998 Validator::Phone => {
1999 #[cfg(feature = "validator")]
2000 patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
2001 #[cfg(not(feature = "validator"))]
2002 patterns.push(r"^[0-9+\-]*$".to_string());
2003 }
2004 Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
2005 Validator::Url => patterns.push(r"^https?://".to_string()),
2006 Validator::Regex(pattern) => patterns.push(pattern.clone()),
2007 Validator::Custom(_) => runtime_validators.push("custom"),
2008 }
2009 }
2010
2011 if let Some(value) = min_length {
2012 schema.insert("minLength".into(), json!(value));
2013 }
2014 if let Some(value) = max_length {
2015 schema.insert("maxLength".into(), json!(value));
2016 }
2017 if let Some(value) = minimum {
2018 schema.insert("minimum".into(), json!(value));
2019 }
2020 if let Some(value) = maximum {
2021 schema.insert("maximum".into(), json!(value));
2022 }
2023 match patterns.as_slice() {
2024 [] => {}
2025 [pattern] => {
2026 schema.insert("pattern".into(), json!(pattern));
2027 }
2028 patterns => {
2029 schema.insert(
2030 "allOf".into(),
2031 Value::Array(
2032 patterns
2033 .iter()
2034 .map(|pattern| json!({ "pattern": pattern }))
2035 .collect(),
2036 ),
2037 );
2038 }
2039 }
2040 if !runtime_validators.is_empty() {
2041 schema.insert(
2042 "x-yang-runtime-validators".into(),
2043 json!(runtime_validators),
2044 );
2045 }
2046 if let Some(relation) = &field.relation {
2047 let relation_type = match relation.relation_type {
2048 RelationType::OneToOne => "one_to_one",
2049 RelationType::OneToMany => "one_to_many",
2050 RelationType::ManyToOne => "many_to_one",
2051 RelationType::ManyToMany => "many_to_many",
2052 };
2053 schema.insert(
2054 "x-yang-relation".into(),
2055 json!({
2056 "table": relation.table,
2057 "field": relation.field,
2058 "displayFields": relation.display_fields,
2059 "type": relation_type,
2060 }),
2061 );
2062 }
2063
2064 if !field.required {
2065 if let Some(field_types) = schema.get_mut("type") {
2066 match field_types {
2067 Value::String(field_type) => {
2068 *field_types = json!([field_type.clone(), "null"]);
2069 }
2070 Value::Array(types) if !types.iter().any(|value| value == "null") => {
2071 types.push(json!("null"));
2072 }
2073 _ => {}
2074 }
2075 }
2076 if let Some(Value::Array(values)) = schema.get_mut("enum") {
2077 values.push(Value::Null);
2078 }
2079 }
2080 if !field.display_name.is_empty() {
2081 schema.insert("title".into(), json!(field.display_name));
2082 }
2083 if let Some(default) = &field.default_value {
2084 schema.insert("default".into(), default.clone());
2085 }
2086 Value::Object(schema)
2087}
2088
2089fn storage_type_json_schema(field_type: &FieldType) -> Value {
2091 match field_type {
2092 FieldType::String { max_length } => json!({
2093 "type": "string",
2094 "maxLength": max_length,
2095 }),
2096 FieldType::Text => json!({"type": "string"}),
2097 FieldType::Uuid => json!({"type": "string", "format": "uuid"}),
2098 FieldType::Bytes => json!({"type": "string", "format": "byte"}),
2099 FieldType::Enum { values } => json!({"type": "string", "enum": values}),
2100 FieldType::Decimal { precision, scale } => json!({
2101 "type": "string",
2102 "format": "decimal",
2103 "x-precision": precision,
2104 "x-scale": scale,
2105 }),
2106 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => json!({"type": "integer"}),
2107 FieldType::Float | FieldType::Double => json!({"type": "number"}),
2108 FieldType::Boolean => json!({"type": "boolean"}),
2109 FieldType::Date => json!({"type": "string", "format": "date"}),
2110 FieldType::DateTime => json!({"type": "string", "format": "date-time"}),
2111 FieldType::Json | FieldType::Array(_) => json!({}),
2113 }
2114}
2115
2116#[cfg(test)]
2117mod generated_expression_tests {
2118 use super::*;
2119
2120 fn generated_table(expression: &str) -> Result<TableDefinition, BaseError> {
2121 Table::new("generated_balance")
2122 .fields([
2123 Field::id("id"),
2124 Field::integer("price").required(),
2125 Field::string("name", 32),
2126 Field::bigint("total").generated(expression),
2127 ])
2128 .build()
2129 }
2130
2131 #[test]
2132 fn balanced_generated_expressions_pass() {
2133 generated_table("price * 2").expect("简单表达式应通过");
2134 generated_table("coalesce(price, 0)").expect("函数调用应通过");
2135 generated_table("coalesce(name, ')')").expect("字符串字面量含右括号应通过");
2137 generated_table(r"coalesce(name, E'\')')").expect("E 字符串转义应通过");
2139 }
2140
2141 #[test]
2142 fn generated_expression_injection_is_rejected() {
2143 let error = generated_table("price) STORED, 注入 INTEGER")
2144 .expect_err("闭合外层括号的注入表达式必须拒绝");
2145 assert!(
2146 matches!(error, BaseError::ConfigError(ref message) if message.contains("生成列")),
2147 "实得错误: {error:?}"
2148 );
2149 }
2150}
2151
2152#[cfg(test)]
2153mod check_expression_tests {
2154 use super::*;
2155
2156 fn check_table(expression: &str) -> Result<TableDefinition, BaseError> {
2157 Table::new("check_balance")
2158 .fields([
2159 Field::id("id"),
2160 Field::integer("price").required(),
2161 Field::string("status", 32),
2162 Field::string("note", 64),
2163 ])
2164 .check_named("chk_balance", expression)
2165 .build()
2166 }
2167
2168 #[test]
2169 fn legal_check_expressions_pass() {
2170 check_table("price > 0").expect("简单表达式应通过");
2171 check_table("price > 0 AND status <> 'banned'").expect("字符串字面量应通过");
2172 check_table("(price > 0)").expect("成对分组括号应通过");
2173 check_table("`parent_id` > 0").expect("反引号标识符应通过");
2174 check_table(r"note <> 'it\'s)'").expect("MySQL 反斜杠转义字符串应通过");
2176 check_table("`amount)` > 0").expect("反引号内的括号应通过");
2178 check_table("price > 0 # note (policy 2024\nAND status <> 'cancelled'")
2180 .expect("MySQL # 注释应通过");
2181 check_table("$q$a)b$q$").expect("PostgreSQL 美元引号应通过");
2183 check_table(r"note <> E'\')'").expect("PostgreSQL E 字符串应通过");
2185 }
2186
2187 #[test]
2188 fn check_expression_injection_is_rejected() {
2189 let error = check_table("price > 0), evil INT, CHECK (1=1")
2192 .expect_err("闭合外层括号的注入表达式必须拒绝");
2193 assert!(
2194 matches!(error, BaseError::ConfigError(ref message) if message.contains("CHECK")),
2195 "实得错误: {error:?}"
2196 );
2197 }
2198}