1use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{
9 CheckConfig, ForeignKeyConfig, IndexConfig, OpaqueColumnConfig, TableConfig, TimestampFields,
10};
11#[cfg(any(feature = "mysql", feature = "postgres"))]
12use super::TableQuery;
13use super::{FieldType, RegexCache, SortOrder, Validator, MAX_VARCHAR_LENGTH};
14use crate::datasource::DatasourceId;
15use crate::error::BaseError;
16use serde_json::{json, Map, Value};
17use std::collections::{HashMap, HashSet};
18use std::sync::Arc;
19
20pub fn col(name: impl Into<String>) -> ColumnName {
22 ColumnName(name.into())
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub struct ColumnName(String);
28
29impl ColumnName {
30 pub fn asc(self) -> Order {
32 Order {
33 field: self.0,
34 direction: SortOrder::Asc,
35 }
36 }
37
38 pub fn desc(self) -> Order {
40 Order {
41 field: self.0,
42 direction: SortOrder::Desc,
43 }
44 }
45
46 fn into_name(self) -> String {
47 self.0
48 }
49}
50
51impl From<&str> for ColumnName {
52 fn from(value: &str) -> Self {
53 Self(value.to_string())
54 }
55}
56
57impl From<String> for ColumnName {
58 fn from(value: String) -> Self {
59 Self(value)
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Order {
66 field: String,
67 direction: SortOrder,
68}
69
70#[derive(Debug, Clone)]
75#[must_use = "字段定义必须传给 Table::fields"]
76pub struct Field {
77 config: FieldConfig,
78 primary_key: bool,
79 unique: bool,
80 unique_name: Option<String>,
81 index: bool,
82 index_name: Option<String>,
83 created_at: bool,
84 updated_at: bool,
85 deleted_at: bool,
86 soft_delete: bool,
87 relation_display_fields: Option<Vec<String>>,
88}
89
90impl Field {
91 fn new(name: impl Into<String>, field_type: FieldType) -> Self {
92 Self {
93 config: FieldConfig::new(name, field_type),
94 primary_key: false,
95 unique: false,
96 unique_name: None,
97 index: false,
98 index_name: None,
99 created_at: false,
100 updated_at: false,
101 deleted_at: false,
102 soft_delete: false,
103 relation_display_fields: None,
104 }
105 }
106
107 pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
109 self.config.renamed_from = Some(legacy_name.into());
110 self
111 }
112
113 pub fn generated(mut self, expression: impl Into<String>) -> Self {
118 self.config.generated = Some(expression.into());
119 self.config.permissions.writable = Audience::Nobody;
120 self
121 }
122
123 pub fn comment(mut self, comment: impl Into<String>) -> Self {
125 self.config.comment = Some(comment.into());
126 self
127 }
128
129 pub fn collation(mut self, collation: impl Into<String>) -> Self {
131 self.config.collation = Some(collation.into());
132 self
133 }
134
135 pub fn native_enum(mut self, type_name: impl Into<String>) -> Self {
140 self.config.native_enum = Some(type_name.into());
141 self
142 }
143
144 pub fn id(name: impl Into<String>) -> Self {
146 Self::new(name, FieldType::BigInt)
147 .required()
148 .primary_key()
149 .auto_increment()
150 .not_writable()
151 }
152
153 pub fn string(name: impl Into<String>, max_length: usize) -> Self {
155 Self::new(name, FieldType::String { max_length })
156 }
157
158 pub fn integer(name: impl Into<String>) -> Self {
160 Self::new(name, FieldType::Integer)
161 }
162
163 pub fn bigint(name: impl Into<String>) -> Self {
165 Self::new(name, FieldType::BigInt)
166 }
167
168 pub fn float(name: impl Into<String>) -> Self {
170 Self::new(name, FieldType::Float)
171 }
172
173 pub fn double(name: impl Into<String>) -> Self {
175 Self::new(name, FieldType::Double)
176 }
177
178 pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
180 Self::new(name, FieldType::Decimal { precision, scale })
181 }
182
183 pub fn boolean(name: impl Into<String>) -> Self {
185 Self::new(name, FieldType::Boolean)
186 }
187
188 pub fn date(name: impl Into<String>) -> Self {
190 Self::new(name, FieldType::Date)
191 }
192
193 pub fn datetime(name: impl Into<String>) -> Self {
195 Self::new(name, FieldType::DateTime)
196 }
197
198 pub fn timestamp(name: impl Into<String>) -> Self {
200 Self::new(name, FieldType::Timestamp)
201 }
202
203 pub fn json(name: impl Into<String>) -> Self {
205 Self::new(name, FieldType::Json)
206 }
207
208 pub fn text(name: impl Into<String>) -> Self {
210 Self::new(name, FieldType::Text)
211 }
212
213 pub fn uuid(name: impl Into<String>) -> Self {
215 Self::new(name, FieldType::Uuid)
216 }
217
218 pub fn bytes(name: impl Into<String>) -> Self {
220 Self::new(name, FieldType::Bytes)
221 }
222
223 pub fn array(name: impl Into<String>, element: FieldType) -> Self {
225 Self::new(name, FieldType::Array(Box::new(element)))
226 }
227
228 pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
230 where
231 I: IntoIterator<Item = S>,
232 S: Into<String>,
233 {
234 Self::new(
235 name,
236 FieldType::Enum {
237 values: values.into_iter().map(Into::into).collect(),
238 },
239 )
240 }
241
242 pub fn created_at(name: impl Into<String>) -> Self {
244 let mut field = Self::bigint(name).required().not_writable();
245 field.created_at = true;
246 field
247 }
248
249 pub fn updated_at(name: impl Into<String>) -> Self {
251 let mut field = Self::bigint(name).required().not_writable();
252 field.updated_at = true;
253 field
254 }
255
256 pub fn soft_delete(name: impl Into<String>) -> Self {
258 let mut field = Self::bigint(name).not_writable();
259 field.deleted_at = true;
260 field.soft_delete = true;
261 field
262 }
263
264 pub fn label(mut self, label: impl Into<String>) -> Self {
266 self.config.display_name = label.into();
267 self
268 }
269
270 pub fn required(mut self) -> Self {
272 self.config.required = true;
273 self
274 }
275
276 pub fn nullable(mut self) -> Self {
278 self.config.required = false;
279 self
280 }
281
282 pub fn default(mut self, value: impl Into<Value>) -> Self {
284 self.config.default_value = Some(value.into());
285 self
286 }
287
288 pub fn auto_increment(mut self) -> Self {
290 self.config.auto_increment = true;
291 self
292 }
293
294 pub fn primary_key(mut self) -> Self {
296 self.primary_key = true;
297 self
298 }
299
300 pub fn unique(mut self) -> Self {
302 self.unique = true;
303 self
304 }
305
306 pub fn unique_named(mut self, name: impl Into<String>) -> Self {
308 self.unique = true;
309 self.unique_name = Some(name.into());
310 self
311 }
312
313 pub fn index(mut self) -> Self {
315 self.index = true;
316 self
317 }
318
319 pub fn index_named(mut self, name: impl Into<String>) -> Self {
321 self.index = true;
322 self.index_name = Some(name.into());
323 self
324 }
325
326 pub fn validator(mut self, validator: Validator) -> Self {
328 self.config.validators.push(validator);
329 self
330 }
331
332 pub fn min_length(self, value: usize) -> Self {
334 self.validator(Validator::MinLength(value))
335 }
336
337 pub fn max_length(self, value: usize) -> Self {
339 self.validator(Validator::MaxLength(value))
340 }
341
342 pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
344 self.min_length(*range.start()).max_length(*range.end())
345 }
346
347 pub fn min(self, value: f64) -> Self {
349 self.validator(Validator::Min(value))
350 }
351
352 pub fn max(self, value: f64) -> Self {
354 self.validator(Validator::Max(value))
355 }
356
357 pub fn email(self) -> Self {
359 self.validator(Validator::Email)
360 }
361
362 pub fn phone(self) -> Self {
364 self.validator(Validator::Phone)
365 }
366
367 pub fn url(self) -> Self {
369 self.validator(Validator::Url)
370 }
371
372 pub fn regex(self, pattern: impl Into<String>) -> Self {
374 self.validator(Validator::Regex(pattern.into()))
375 }
376
377 pub fn readable(mut self) -> Self {
379 self.config.permissions.readable = Audience::Everyone;
380 self
381 }
382
383 pub fn not_readable(mut self) -> Self {
385 self.config.permissions.readable = Audience::Nobody;
386 self
387 }
388
389 pub fn readable_by<I, S>(mut self, roles: I) -> Self
391 where
392 I: IntoIterator<Item = S>,
393 S: Into<String>,
394 {
395 self.config.permissions.readable = Audience::roles(roles);
396 self
397 }
398
399 pub fn writable_by<I, S>(mut self, roles: I) -> Self
401 where
402 I: IntoIterator<Item = S>,
403 S: Into<String>,
404 {
405 self.config.permissions.writable = Audience::roles(roles);
406 self
407 }
408
409 pub fn writable(mut self) -> Self {
411 self.config.permissions.writable = Audience::Everyone;
412 self
413 }
414
415 pub fn not_writable(mut self) -> Self {
417 self.config.permissions.writable = Audience::Nobody;
418 self
419 }
420
421 pub fn searchable(mut self) -> Self {
427 self.config.searchable = true;
428 self
429 }
430
431 pub fn filterable(mut self) -> Self {
433 self.config.filterable = true;
434 self.config.permissions.filterable = Audience::Everyone;
435 self
436 }
437
438 pub fn not_filterable(mut self) -> Self {
440 self.config.filterable = false;
441 self.config.permissions.filterable = Audience::Nobody;
442 self
443 }
444
445 pub fn filterable_by<I, S>(mut self, roles: I) -> Self
447 where
448 I: IntoIterator<Item = S>,
449 S: Into<String>,
450 {
451 self.config.filterable = true;
452 self.config.permissions.filterable = Audience::roles(roles);
453 self
454 }
455
456 pub fn sortable(mut self) -> Self {
458 self.config.sortable = true;
459 self.config.permissions.sortable = Audience::Everyone;
460 self
461 }
462
463 pub fn not_sortable(mut self) -> Self {
465 self.config.sortable = false;
466 self.config.permissions.sortable = Audience::Nobody;
467 self
468 }
469
470 pub fn sortable_by<I, S>(mut self, roles: I) -> Self
472 where
473 I: IntoIterator<Item = S>,
474 S: Into<String>,
475 {
476 self.config.sortable = true;
477 self.config.permissions.sortable = Audience::roles(roles);
478 self
479 }
480
481 pub fn tenant_key(mut self) -> Self {
483 self.config.tenant_key = true;
484 self
485 }
486
487 pub fn secret(mut self) -> Self {
493 self.config.hidden = true;
494 self.config.permissions = FieldPermissions {
495 readable: Audience::Nobody,
496 writable: Audience::Nobody,
497 filterable: Audience::Nobody,
498 sortable: Audience::Nobody,
499 };
500 self.config.searchable = false;
501 self.config.filterable = false;
502 self.config.sortable = false;
503 self
504 }
505
506 pub fn relation(
508 mut self,
509 table: impl Into<String>,
510 field: impl Into<String>,
511 relation_type: RelationType,
512 ) -> Self {
513 self.config.relation = Some(RelationConfig {
514 table: table.into(),
515 field: field.into(),
516 display_fields: Vec::new(),
517 relation_type,
518 });
519 self
520 }
521
522 pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
524 where
525 I: IntoIterator<Item = S>,
526 S: Into<String>,
527 {
528 self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
529 self
530 }
531}
532
533#[derive(Debug, Clone)]
534struct PendingIndex {
535 name: Option<String>,
536 fields: Vec<String>,
537 expressions: Vec<String>,
538 predicate: Option<String>,
539 unique: bool,
540 nulls_not_distinct: bool,
541}
542
543#[derive(Debug, Clone)]
544struct PendingCheck {
545 name: String,
546 expression: String,
547}
548
549#[derive(Debug, Clone)]
550struct PendingForeignKey {
551 name: String,
552 columns: Vec<String>,
553 referenced_table: String,
554 referenced_columns: Vec<String>,
555}
556
557#[derive(Debug, Clone)]
559#[must_use = "表构建器必须调用 build"]
560pub struct Table {
561 name: String,
562 label: Option<String>,
563 datasource: Option<DatasourceId>,
564 primary_key_order: Vec<String>,
565 fields: Vec<Field>,
566 opaque_columns: Vec<OpaqueColumnConfig>,
567 indexes: Vec<PendingIndex>,
568 checks: Vec<PendingCheck>,
569 foreign_keys: Vec<PendingForeignKey>,
570 default_order: Vec<Order>,
571}
572
573impl Table {
574 pub fn new(name: impl Into<String>) -> Self {
576 Self {
577 name: name.into(),
578 label: None,
579 datasource: None,
580 primary_key_order: Vec::new(),
581 fields: Vec::new(),
582 opaque_columns: Vec::new(),
583 indexes: Vec::new(),
584 checks: Vec::new(),
585 foreign_keys: Vec::new(),
586 default_order: Vec::new(),
587 }
588 }
589
590 pub fn label(mut self, label: impl Into<String>) -> Self {
592 self.label = Some(label.into());
593 self
594 }
595
596 pub fn datasource(mut self, id: DatasourceId) -> Self {
598 self.datasource = Some(id);
599 self
600 }
601
602 pub fn primary_key_order(mut self, order: Vec<String>) -> Self {
604 self.primary_key_order = order;
605 self
606 }
607
608 pub fn fields<I>(mut self, fields: I) -> Self
610 where
611 I: IntoIterator<Item = Field>,
612 {
613 self.fields.extend(fields);
614 self
615 }
616
617 pub fn opaque_column(mut self, name: impl Into<String>, sql_type: impl Into<String>) -> Self {
623 self.opaque_columns.push(OpaqueColumnConfig {
624 name: name.into(),
625 sql_type: sql_type.into(),
626 });
627 self
628 }
629
630 pub fn unique<I, C>(mut self, fields: I) -> Self
632 where
633 I: IntoIterator<Item = C>,
634 C: Into<ColumnName>,
635 {
636 self.indexes.push(PendingIndex {
637 name: None,
638 fields: fields
639 .into_iter()
640 .map(|field| field.into().into_name())
641 .collect(),
642 expressions: Vec::new(),
643 predicate: None,
644 unique: true,
645 nulls_not_distinct: false,
646 });
647 self
648 }
649
650 pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
652 where
653 I: IntoIterator<Item = C>,
654 C: Into<ColumnName>,
655 {
656 self.indexes.push(PendingIndex {
657 name: Some(name.into()),
658 fields: fields
659 .into_iter()
660 .map(|field| field.into().into_name())
661 .collect(),
662 expressions: Vec::new(),
663 predicate: None,
664 unique: true,
665 nulls_not_distinct: false,
666 });
667 self
668 }
669
670 pub fn unique_nulls_not_distinct<I, C>(mut self, fields: I) -> Self
675 where
676 I: IntoIterator<Item = C>,
677 C: Into<ColumnName>,
678 {
679 self.indexes.push(PendingIndex {
680 name: None,
681 fields: fields
682 .into_iter()
683 .map(|field| field.into().into_name())
684 .collect(),
685 expressions: Vec::new(),
686 predicate: None,
687 unique: true,
688 nulls_not_distinct: true,
689 });
690 self
691 }
692
693 pub fn unique_named_nulls_not_distinct<I, C>(
695 mut self,
696 name: impl Into<String>,
697 fields: I,
698 ) -> Self
699 where
700 I: IntoIterator<Item = C>,
701 C: Into<ColumnName>,
702 {
703 self.indexes.push(PendingIndex {
704 name: Some(name.into()),
705 fields: fields
706 .into_iter()
707 .map(|field| field.into().into_name())
708 .collect(),
709 expressions: Vec::new(),
710 predicate: None,
711 unique: true,
712 nulls_not_distinct: true,
713 });
714 self
715 }
716
717 pub fn index<I, C>(mut self, fields: I) -> Self
719 where
720 I: IntoIterator<Item = C>,
721 C: Into<ColumnName>,
722 {
723 self.indexes.push(PendingIndex {
724 name: None,
725 fields: fields
726 .into_iter()
727 .map(|field| field.into().into_name())
728 .collect(),
729 expressions: Vec::new(),
730 predicate: None,
731 unique: false,
732 nulls_not_distinct: false,
733 });
734 self
735 }
736
737 pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
739 where
740 I: IntoIterator<Item = C>,
741 C: Into<ColumnName>,
742 {
743 self.indexes.push(PendingIndex {
744 name: Some(name.into()),
745 fields: fields
746 .into_iter()
747 .map(|field| field.into().into_name())
748 .collect(),
749 expressions: Vec::new(),
750 predicate: None,
751 unique: false,
752 nulls_not_distinct: false,
753 });
754 self
755 }
756
757 pub fn index_spec<I, C, S>(
762 mut self,
763 name: Option<String>,
764 fields: I,
765 expressions: impl IntoIterator<Item = S>,
766 predicate: Option<String>,
767 unique: bool,
768 nulls_not_distinct: bool,
769 ) -> Self
770 where
771 I: IntoIterator<Item = C>,
772 C: Into<ColumnName>,
773 S: Into<String>,
774 {
775 self.indexes.push(PendingIndex {
776 name,
777 fields: fields
778 .into_iter()
779 .map(|field| field.into().into_name())
780 .collect(),
781 expressions: expressions.into_iter().map(Into::into).collect(),
782 predicate,
783 unique,
784 nulls_not_distinct,
785 });
786 self
787 }
788
789 pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
793 self.checks.push(PendingCheck {
794 name: name.into(),
795 expression: expression.into(),
796 });
797 self
798 }
799
800 pub fn foreign_key_named<I, C, R, RC>(
802 mut self,
803 name: impl Into<String>,
804 columns: I,
805 referenced_table: impl Into<String>,
806 referenced_columns: R,
807 ) -> Self
808 where
809 I: IntoIterator<Item = C>,
810 C: Into<ColumnName>,
811 R: IntoIterator<Item = RC>,
812 RC: Into<ColumnName>,
813 {
814 self.foreign_keys.push(PendingForeignKey {
815 name: name.into(),
816 columns: columns
817 .into_iter()
818 .map(|column| column.into().into_name())
819 .collect(),
820 referenced_table: referenced_table.into(),
821 referenced_columns: referenced_columns
822 .into_iter()
823 .map(|column| column.into().into_name())
824 .collect(),
825 });
826 self
827 }
828
829 pub fn default_order(mut self, order: Order) -> Self {
831 self.default_order = vec![order];
832 self
833 }
834
835 pub fn then_order(mut self, order: Order) -> Self {
837 self.default_order.push(order);
838 self
839 }
840
841 pub fn build(self) -> Result<TableDefinition, BaseError> {
843 validate_identifier("表", &self.name)?;
844 if self.fields.is_empty() {
845 return Err(BaseError::ConfigError(format!(
846 "表 {} 至少需要一个字段",
847 self.name
848 )));
849 }
850
851 let mut field_names = HashSet::with_capacity(self.fields.len());
852 let mut legacy_names = HashSet::new();
853 let mut configs = HashMap::with_capacity(self.fields.len());
854 let mut primary_keys: Vec<String> = Vec::new();
855 let mut created_at: Option<String> = None;
856 let mut updated_at: Option<String> = None;
857 let mut deleted_at: Option<String> = None;
858 let mut soft_delete: Option<String> = None;
859 let mut tenant_key: Option<String> = None;
860 let mut indexes = self.indexes;
861 let checks = self.checks;
862 let foreign_keys = self.foreign_keys;
863 let regex_cache = RegexCache::default();
865
866 for mut field in self.fields {
867 validate_identifier("字段", &field.config.name)?;
868 if !field_names.insert(field.config.name.clone()) {
869 return Err(BaseError::ConfigError(format!(
870 "表 {} 存在重复字段: {}",
871 self.name, field.config.name
872 )));
873 }
874 if let Some(legacy_name) = field.config.renamed_from.as_deref() {
875 validate_identifier("旧字段", legacy_name)?;
876 if legacy_name == field.config.name || !legacy_names.insert(legacy_name.to_string())
877 {
878 return Err(BaseError::ConfigError(format!(
879 "表 {} 的旧字段改名来源重复或未发生改名: {}",
880 self.name, legacy_name
881 )));
882 }
883 }
884 if field.config.display_name.is_empty() {
885 field.config.display_name = field.config.name.clone();
886 }
887 if let Some(display_fields) = field.relation_display_fields.take() {
888 let relation = field.config.relation.as_mut().ok_or_else(|| {
889 BaseError::ConfigError(format!(
890 "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
891 self.name, field.config.name
892 ))
893 })?;
894 relation.display_fields = display_fields;
895 }
896 validate_field_shape(&self.name, &field, ®ex_cache)?;
897
898 if field.primary_key {
899 primary_keys.push(field.config.name.clone());
900 }
901 if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
902 return Err(BaseError::ConfigError(format!(
903 "表 {} 只能定义一个租户隔离字段",
904 self.name
905 )));
906 }
907 set_unique_role(
908 &self.name,
909 "created_at",
910 field.created_at,
911 &field.config.name,
912 &mut created_at,
913 )?;
914 set_unique_role(
915 &self.name,
916 "updated_at",
917 field.updated_at,
918 &field.config.name,
919 &mut updated_at,
920 )?;
921 set_unique_role(
922 &self.name,
923 "deleted_at",
924 field.deleted_at,
925 &field.config.name,
926 &mut deleted_at,
927 )?;
928 set_unique_role(
929 &self.name,
930 "soft_delete",
931 field.soft_delete,
932 &field.config.name,
933 &mut soft_delete,
934 )?;
935
936 if field.unique {
937 indexes.push(PendingIndex {
938 name: field.unique_name.take(),
939 fields: vec![field.config.name.clone()],
940 expressions: Vec::new(),
941 predicate: None,
942 unique: true,
943 nulls_not_distinct: false,
944 });
945 }
946 if field.index {
947 indexes.push(PendingIndex {
948 name: field.index_name.take(),
949 fields: vec![field.config.name.clone()],
950 expressions: Vec::new(),
951 predicate: None,
952 unique: false,
953 nulls_not_distinct: false,
954 });
955 }
956 configs.insert(field.config.name.clone(), field.config);
957 }
958
959 let mut opaque_names = HashSet::new();
960 for opaque in &self.opaque_columns {
961 validate_identifier("Opaque 列", &opaque.name)?;
962 if field_names.contains(&opaque.name) || !opaque_names.insert(opaque.name.clone()) {
963 return Err(BaseError::ConfigError(format!(
964 "表 {} 的 opaque 列 {} 与字段或另一 opaque 列重名",
965 self.name, opaque.name
966 )));
967 }
968 let sql_type = opaque.sql_type.trim();
969 if sql_type.is_empty()
970 || sql_type.chars().count() > 256
971 || [";", "--", "/*", "*/", "\n", "\r", "\0"]
972 .iter()
973 .any(|marker| sql_type.contains(marker))
974 {
975 return Err(BaseError::ConfigError(format!(
976 "表 {} 的 opaque 列 {} 必须声明非空、长度受限且不含语句分隔符的类型文本",
977 self.name, opaque.name
978 )));
979 }
980 }
981
982 if let Some(legacy_name) = legacy_names
983 .iter()
984 .find(|legacy_name| field_names.contains(legacy_name.as_str()))
985 {
986 return Err(BaseError::ConfigError(format!(
987 "表 {} 同时声明旧字段与改名后字段: {}",
988 self.name, legacy_name
989 )));
990 }
991
992 if !self.primary_key_order.is_empty() {
993 let mut ordered = Vec::with_capacity(primary_keys.len());
994 for name in &self.primary_key_order {
995 match primary_keys.iter().position(|key| key == name) {
996 Some(position) => ordered.push(primary_keys.remove(position)),
997 None => {
998 return Err(BaseError::ConfigError(format!(
999 "表 {} 的主键顺序引用非主键字段: {name}",
1000 self.name
1001 )))
1002 }
1003 }
1004 }
1005 ordered.append(&mut primary_keys);
1006 primary_keys = ordered;
1007 }
1008
1009 let primary_key = primary_keys.first().cloned().unwrap_or_default();
1010
1011 let mut unique_indexes = Vec::new();
1012 let mut normal_indexes = Vec::new();
1013 let mut index_names = HashSet::new();
1014 for index in indexes {
1015 validate_index(&self.name, &field_names, &index, &mut index_names)?;
1016 let config = IndexConfig::new(index.name, index.fields, index.nulls_not_distinct)
1017 .with_expressions(index.expressions)
1018 .with_predicate(index.predicate);
1019 if index.unique {
1020 unique_indexes.push(config);
1021 } else {
1022 normal_indexes.push(config);
1023 }
1024 }
1025
1026 let mut constraint_names = HashSet::new();
1027 let checks = checks
1028 .into_iter()
1029 .map(|check| {
1030 validate_constraint_name(&self.name, &check.name, &mut constraint_names)?;
1031 validate_check_expression(&self.name, &check.name, &check.expression)?;
1032 Ok(CheckConfig {
1033 name: check.name,
1034 expression: check.expression,
1035 })
1036 })
1037 .collect::<Result<Vec<_>, BaseError>>()?;
1038 let foreign_keys = foreign_keys
1039 .into_iter()
1040 .map(|foreign_key| {
1041 validate_constraint_name(&self.name, &foreign_key.name, &mut constraint_names)?;
1042 validate_foreign_key(&self.name, &field_names, &foreign_key)?;
1043 Ok(ForeignKeyConfig {
1044 name: foreign_key.name,
1045 columns: foreign_key.columns,
1046 referenced_table: foreign_key.referenced_table,
1047 referenced_columns: foreign_key.referenced_columns,
1048 })
1049 })
1050 .collect::<Result<Vec<_>, BaseError>>()?;
1051
1052 let mut orders = Vec::with_capacity(self.default_order.len());
1053 for order in self.default_order {
1054 if !field_names.contains(&order.field) {
1055 return Err(BaseError::ConfigError(format!(
1056 "表 {} 的默认排序字段不存在: {}",
1057 self.name, order.field
1058 )));
1059 }
1060 orders.push((order.field, order.direction));
1061 }
1062
1063 let timestamp_fields =
1064 if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
1065 Some(TimestampFields::new(created_at, updated_at, deleted_at))
1066 } else {
1067 None
1068 };
1069 let table_ref = yang_db::TableRef::new(self.name.clone())
1070 .map_err(|error| BaseError::ConfigError(error.to_string()))?;
1071 let field_refs = field_names
1072 .iter()
1073 .map(|name| {
1074 yang_db::FieldRef::new(name.clone())
1075 .map(|field| (name.clone(), field))
1076 .map_err(|error| BaseError::ConfigError(error.to_string()))
1077 })
1078 .collect::<Result<HashMap<_, _>, _>>()?;
1079
1080 Ok(TableDefinition {
1081 config: Arc::new(TableConfig {
1082 table_name: self.name.clone(),
1083 datasource: self.datasource.unwrap_or_default(),
1084 table_ref,
1085 display_name: self.label.unwrap_or(self.name),
1086 primary_key,
1087 primary_keys,
1088 fields: configs,
1089 opaque_columns: self.opaque_columns,
1090 field_refs,
1091 unique_indexes,
1092 indexes: normal_indexes,
1093 checks,
1094 foreign_keys,
1095 default_order: orders,
1096 soft_delete_field: soft_delete,
1097 timestamp_fields,
1098 }),
1099 })
1100 }
1101}
1102
1103#[derive(Debug, Clone)]
1105pub struct TableDefinition {
1106 pub(crate) config: Arc<TableConfig>,
1107}
1108
1109impl TableDefinition {
1110 pub fn name(&self) -> &str {
1112 &self.config.table_name
1113 }
1114
1115 pub fn datasource(&self) -> &DatasourceId {
1117 &self.config.datasource
1118 }
1119
1120 pub fn label(&self) -> &str {
1122 &self.config.display_name
1123 }
1124
1125 pub fn primary_key(&self) -> &str {
1127 &self.config.primary_key
1128 }
1129
1130 pub fn primary_keys(&self) -> &[String] {
1132 &self.config.primary_keys
1133 }
1134
1135 pub fn field_count(&self) -> usize {
1137 self.config.fields.len()
1138 }
1139
1140 pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
1142 self.config
1143 .fields
1144 .get(name)
1145 .map(|config| FieldMetadata { config })
1146 }
1147
1148 pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
1150 let mut fields: Vec<_> = self
1151 .config
1152 .fields
1153 .values()
1154 .map(|config| FieldMetadata { config })
1155 .collect();
1156 fields.sort_by(|left, right| left.name().cmp(right.name()));
1157 fields
1158 }
1159
1160 pub fn soft_delete_field(&self) -> Option<&str> {
1162 self.config.soft_delete_field.as_deref()
1163 }
1164
1165 pub fn tenant_key_field(&self) -> Option<&str> {
1167 self.config
1168 .fields
1169 .values()
1170 .find(|field| field.tenant_key)
1171 .map(|field| field.name.as_str())
1172 }
1173
1174 pub fn input_schema(&self) -> Value {
1179 self.json_schema(false, None)
1180 }
1181
1182 pub fn output_schema(&self) -> Value {
1187 self.json_schema(true, None)
1188 }
1189
1190 pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1192 self.json_schema(false, Some(roles))
1193 }
1194
1195 pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1197 self.json_schema(true, Some(roles))
1198 }
1199
1200 #[cfg(any(feature = "mysql", feature = "postgres"))]
1202 pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
1203 self.config.fields.get(name).map(field_json_schema)
1204 }
1205
1206 fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
1207 let mut properties = Map::new();
1208 let mut required = Vec::new();
1209 let mut names: Vec<_> = self.config.fields.keys().collect();
1210 names.sort();
1211 for name in names {
1212 let field = &self.config.fields[name];
1213 let generated = field.auto_increment
1214 || self
1215 .config
1216 .timestamp_fields
1217 .as_ref()
1218 .is_some_and(|timestamps| {
1219 timestamps.created_at.as_deref() == Some(name.as_str())
1220 || timestamps.updated_at.as_deref() == Some(name.as_str())
1221 || timestamps.deleted_at.as_deref() == Some(name.as_str())
1222 })
1223 || self.config.soft_delete_field.as_deref() == Some(name.as_str());
1224 let audience = if output {
1225 &field.permissions.readable
1226 } else {
1227 &field.permissions.writable
1228 };
1229 let audience_allows = roles.map_or_else(
1230 || !matches!(audience, Audience::Nobody),
1231 |roles| audience.allows(roles),
1232 );
1233 if field.hidden || !audience_allows || (!output && generated) {
1234 continue;
1235 }
1236 properties.insert(name.clone(), field_json_schema(field));
1237 if field.required && (output || (!generated && field.default_value.is_none())) {
1238 required.push(Value::String(name.clone()));
1239 }
1240 }
1241 json!({
1242 "type": "object",
1243 "title": self.config.display_name,
1244 "properties": properties,
1245 "required": required,
1246 "additionalProperties": false,
1247 })
1248 }
1249
1250 #[cfg(feature = "mysql")]
1251 pub(crate) fn config(&self) -> &TableConfig {
1252 &self.config
1253 }
1254
1255 pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
1256 Arc::clone(&self.config)
1257 }
1258
1259 pub fn validate_schema(
1261 &self,
1262 columns: &[super::SchemaColumn],
1263 ) -> super::SchemaValidationReport {
1264 self.config.validate_schema(columns)
1265 }
1266
1267 #[cfg(feature = "mysql")]
1272 pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
1273 self.bind_pool(crate::database::AnyPool::MySql(pool))
1274 }
1275
1276 #[cfg(any(feature = "mysql", feature = "postgres"))]
1278 pub fn bind_pool(&self, pool: crate::database::AnyPool) -> TableHandle {
1279 self.bind_source_pool(crate::database::PoolHandle::new(
1280 self.datasource().clone(),
1281 pool,
1282 ))
1283 }
1284
1285 #[cfg(any(feature = "mysql", feature = "postgres"))]
1287 pub fn bind_datasource(&self, datasource: &crate::database::Datasource) -> TableHandle {
1288 self.bind_source_pool(crate::database::PoolHandle::new(
1289 datasource.id().clone(),
1290 datasource.database().pool(),
1291 ))
1292 }
1293
1294 #[cfg(any(feature = "mysql", feature = "postgres"))]
1296 pub fn bind_source_pool(&self, pool: crate::database::PoolHandle) -> TableHandle {
1297 TableHandle {
1298 definition: self.clone(),
1299 pool,
1300 }
1301 }
1302}
1303
1304#[derive(Debug, Clone, Copy)]
1306pub struct FieldMetadata<'a> {
1307 config: &'a FieldConfig,
1308}
1309
1310impl<'a> FieldMetadata<'a> {
1311 pub fn name(self) -> &'a str {
1313 &self.config.name
1314 }
1315
1316 pub fn label(self) -> &'a str {
1318 &self.config.display_name
1319 }
1320
1321 pub fn is_tenant_key(self) -> bool {
1323 self.config.tenant_key
1324 }
1325
1326 pub fn field_type(self) -> &'a FieldType {
1328 &self.config.field_type
1329 }
1330
1331 pub fn is_required(self) -> bool {
1333 self.config.required
1334 }
1335
1336 pub fn default_value(self) -> Option<&'a Value> {
1338 self.config.default_value.as_ref()
1339 }
1340
1341 pub fn is_auto_increment(self) -> bool {
1343 self.config.auto_increment
1344 }
1345
1346 pub fn is_searchable(self) -> bool {
1348 self.config.searchable
1349 }
1350
1351 pub fn is_filterable(self) -> bool {
1353 self.config.filterable
1354 }
1355
1356 pub fn is_sortable(self) -> bool {
1358 self.config.sortable
1359 }
1360
1361 pub fn is_secret(self) -> bool {
1363 self.config.hidden
1364 }
1365}
1366
1367#[cfg(any(feature = "mysql", feature = "postgres"))]
1369#[derive(Debug, Clone)]
1370pub struct TableHandle {
1371 definition: TableDefinition,
1372 pool: crate::database::PoolHandle,
1373}
1374
1375#[cfg(any(feature = "mysql", feature = "postgres"))]
1376impl TableHandle {
1377 pub fn definition(&self) -> &TableDefinition {
1379 &self.definition
1380 }
1381
1382 pub fn query<I, S>(&self, roles: I) -> TableQuery
1384 where
1385 I: IntoIterator<Item = S>,
1386 S: Into<String>,
1387 {
1388 let roles: Arc<[String]> =
1389 Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1390 TableQuery::new_sourced(
1391 self.definition.shared_config(),
1392 roles,
1393 Some(self.pool.pool().clone()),
1394 self.pool.source().clone(),
1395 )
1396 }
1397}
1398
1399fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1400 let mut chars = value.chars();
1401 let first = chars
1402 .next()
1403 .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1404 if value.len() > 64
1405 || !(first == '_' || first.is_ascii_alphabetic())
1406 || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1407 {
1408 return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1409 }
1410 Ok(())
1411}
1412
1413fn has_balanced_generated_expression(expression: &str) -> bool {
1419 let bytes = expression.as_bytes();
1420 let mut depth: i32 = 0;
1421 let mut index = 0;
1422 while index < bytes.len() {
1423 match bytes[index] {
1424 b'\'' => {
1425 let escape_string = is_escape_string_prefix(bytes, index);
1426 index += 1;
1427 while index < bytes.len() {
1428 if escape_string && bytes[index] == b'\\' {
1429 index = (index + 2).min(bytes.len());
1431 continue;
1432 }
1433 if bytes[index] == b'\'' {
1434 if bytes.get(index + 1) == Some(&b'\'') {
1435 index += 2;
1436 continue;
1437 }
1438 index += 1;
1439 break;
1440 }
1441 index += 1;
1442 }
1443 }
1444 b'"' => {
1445 index += 1;
1446 while index < bytes.len() {
1447 if bytes[index] == b'"' {
1448 if bytes.get(index + 1) == Some(&b'"') {
1449 index += 2;
1450 continue;
1451 }
1452 index += 1;
1453 break;
1454 }
1455 index += 1;
1456 }
1457 }
1458 b'(' => {
1459 depth += 1;
1460 index += 1;
1461 }
1462 b')' => {
1463 depth -= 1;
1464 if depth < 0 {
1465 return false;
1466 }
1467 index += 1;
1468 }
1469 _ => index += 1,
1470 }
1471 }
1472 depth == 0
1473}
1474
1475fn is_escape_string_prefix(bytes: &[u8], quote_index: usize) -> bool {
1477 if quote_index == 0 || !matches!(bytes[quote_index - 1], b'E' | b'e') {
1478 return false;
1479 }
1480 quote_index == 1 || !is_identifier_byte(bytes[quote_index - 2])
1481}
1482
1483fn is_identifier_byte(byte: u8) -> bool {
1484 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' || byte >= 0x80
1485}
1486
1487fn has_balanced_check_expression(expression: &str) -> bool {
1494 has_balanced_pg_check_expression(expression) || has_balanced_mysql_check_expression(expression)
1498}
1499
1500pub(crate) fn has_balanced_pg_check_expression(expression: &str) -> bool {
1505 let bytes = expression.as_bytes();
1506 let mut depth: i32 = 0;
1507 let mut index = 0;
1508 while index < bytes.len() {
1509 match bytes[index] {
1510 b'\'' => {
1511 let backslash_escapes =
1512 is_escape_string_prefix(bytes, index) || is_unicode_escape_prefix(bytes, index);
1513 if !skip_quoted(bytes, &mut index, b'\'', backslash_escapes) {
1514 return false;
1515 }
1516 }
1517 b'"' => {
1518 let backslash_escapes = is_unicode_escape_prefix(bytes, index);
1519 if !skip_quoted(bytes, &mut index, b'"', backslash_escapes) {
1520 return false;
1521 }
1522 }
1523 b'$' => {
1524 let Some(tag_end) = dollar_quote_tag_end(bytes, index) else {
1525 index += 1;
1526 continue;
1527 };
1528 let tag = &bytes[index..tag_end];
1529 let mut cursor = tag_end;
1530 loop {
1531 if cursor + tag.len() > bytes.len() {
1532 return false;
1534 }
1535 if &bytes[cursor..cursor + tag.len()] == tag {
1536 index = cursor + tag.len();
1537 break;
1538 }
1539 cursor += 1;
1540 }
1541 }
1542 b'(' => {
1543 depth += 1;
1544 index += 1;
1545 }
1546 b')' => {
1547 depth -= 1;
1548 if depth < 0 {
1549 return false;
1550 }
1551 index += 1;
1552 }
1553 _ => index += 1,
1554 }
1555 }
1556 depth == 0
1557}
1558
1559pub(crate) fn has_balanced_mysql_check_expression(expression: &str) -> bool {
1564 let bytes = expression.as_bytes();
1565 let mut depth: i32 = 0;
1566 let mut index = 0;
1567 while index < bytes.len() {
1568 match bytes[index] {
1569 b'\'' => {
1570 if !skip_quoted(bytes, &mut index, b'\'', true) {
1571 return false;
1572 }
1573 }
1574 b'"' => {
1575 if !skip_quoted(bytes, &mut index, b'"', true) {
1576 return false;
1577 }
1578 }
1579 b'`' => {
1580 if !skip_quoted(bytes, &mut index, b'`', false) {
1581 return false;
1582 }
1583 }
1584 b'#' => {
1585 while index < bytes.len() && bytes[index] != b'\n' {
1586 index += 1;
1587 }
1588 }
1589 b'(' => {
1590 depth += 1;
1591 index += 1;
1592 }
1593 b')' => {
1594 depth -= 1;
1595 if depth < 0 {
1596 return false;
1597 }
1598 index += 1;
1599 }
1600 _ => index += 1,
1601 }
1602 }
1603 depth == 0
1604}
1605
1606fn skip_quoted(bytes: &[u8], index: &mut usize, delimiter: u8, backslash_escapes: bool) -> bool {
1610 *index += 1;
1611 while *index < bytes.len() {
1612 if backslash_escapes && bytes[*index] == b'\\' {
1613 *index = (*index + 2).min(bytes.len());
1614 continue;
1615 }
1616 if bytes[*index] == delimiter {
1617 if bytes.get(*index + 1) == Some(&delimiter) {
1618 *index += 2;
1619 continue;
1620 }
1621 *index += 1;
1622 return true;
1623 }
1624 *index += 1;
1625 }
1626 false
1627}
1628
1629fn is_unicode_escape_prefix(bytes: &[u8], quote_index: usize) -> bool {
1631 if quote_index < 2
1632 || bytes[quote_index - 1] != b'&'
1633 || !matches!(bytes[quote_index - 2], b'U' | b'u')
1634 {
1635 return false;
1636 }
1637 quote_index < 3 || !is_identifier_byte(bytes[quote_index - 3])
1638}
1639
1640fn dollar_quote_tag_end(bytes: &[u8], start: usize) -> Option<usize> {
1642 let mut index = start + 1;
1643 let first = bytes.get(index)?;
1644 if *first == b'$' {
1645 return Some(index + 1);
1647 }
1648 if !(*first == b'_' || first.is_ascii_alphabetic() || *first >= 0x80) {
1649 return None;
1650 }
1651 index += 1;
1652 while let Some(byte) = bytes.get(index) {
1653 if byte.is_ascii_alphanumeric() || *byte == b'_' || *byte >= 0x80 {
1654 index += 1;
1655 } else {
1656 break;
1657 }
1658 }
1659 (bytes.get(index) == Some(&b'$')).then_some(index + 1)
1660}
1661
1662fn validate_field_shape(table: &str, field: &Field, cache: &RegexCache) -> Result<(), BaseError> {
1663 match &field.config.field_type {
1664 FieldType::String { max_length } if !(1..=MAX_VARCHAR_LENGTH).contains(max_length) => {
1665 return Err(BaseError::ConfigError(format!(
1666 "表 {table} 的字符串字段 {} 长度必须在 1..={MAX_VARCHAR_LENGTH}(更长内容请使用 Text 字段)",
1667 field.config.name
1668 )));
1669 }
1670 FieldType::Enum { values } => {
1671 let unique: HashSet<_> = values.iter().collect();
1672 if values.is_empty() || unique.len() != values.len() {
1673 return Err(BaseError::ConfigError(format!(
1674 "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1675 field.config.name
1676 )));
1677 }
1678 }
1679 FieldType::Decimal { precision, scale }
1680 if *precision == 0 || *precision > 65 || *scale > *precision =>
1681 {
1682 return Err(BaseError::ConfigError(format!(
1683 "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1684 field.config.name
1685 )));
1686 }
1687 FieldType::Array(element) if matches!(**element, FieldType::Array(_) | FieldType::Json) => {
1688 return Err(BaseError::ConfigError(format!(
1689 "表 {table} 的数组字段 {} 只支持标量元素,不支持嵌套数组或 JSON 元素",
1690 field.config.name
1691 )));
1692 }
1693 _ => {}
1694 }
1695
1696 if let Some(type_name) = &field.config.native_enum {
1697 if !matches!(field.config.field_type, FieldType::Enum { .. }) {
1698 return Err(BaseError::ConfigError(format!(
1699 "表 {table} 的字段 {} 只有枚举类型可以声明 native_enum",
1700 field.config.name
1701 )));
1702 }
1703 validate_identifier("枚举类型", type_name)?;
1704 if type_name.len() > 63 {
1706 return Err(BaseError::ConfigError(format!(
1707 "表 {table} 的枚举类型名 {type_name} 超过 PostgreSQL 63 字节限制"
1708 )));
1709 }
1710 }
1711
1712 if field.config.auto_increment
1713 && (!field.primary_key
1714 || !matches!(
1715 field.config.field_type,
1716 FieldType::Integer | FieldType::BigInt
1717 ))
1718 {
1719 return Err(BaseError::ConfigError(format!(
1720 "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1721 field.config.name
1722 )));
1723 }
1724 if field.primary_key && !field.config.required {
1725 return Err(BaseError::ConfigError(format!(
1726 "表 {table} 的主键必须为必填字段: {}",
1727 field.config.name
1728 )));
1729 }
1730 if field.config.auto_increment && field.config.default_value.is_some() {
1731 return Err(BaseError::ConfigError(format!(
1732 "表 {table} 的自增字段不能配置默认值: {}",
1733 field.config.name
1734 )));
1735 }
1736 if let Some(expression) = &field.config.generated {
1737 let expression = expression.trim();
1738 if expression.is_empty()
1739 || expression.chars().count() > 2_048
1740 || [";", "--", "/*", "*/"]
1741 .iter()
1742 .any(|marker| expression.contains(marker))
1743 || !has_balanced_generated_expression(expression)
1744 {
1745 return Err(BaseError::ConfigError(format!(
1746 "表 {table} 的生成列 {} 必须是单条、非空、长度受限且括号平衡的受信表达式",
1747 field.config.name
1748 )));
1749 }
1750 if field.config.auto_increment || field.config.default_value.is_some() {
1751 return Err(BaseError::ConfigError(format!(
1752 "表 {table} 的生成列 {} 不能同时声明自增或默认值",
1753 field.config.name
1754 )));
1755 }
1756 }
1757 if let Some(collation) = &field.config.collation {
1758 if collation.trim().is_empty() || collation.len() > 128 {
1759 return Err(BaseError::ConfigError(format!(
1760 "表 {table} 的字段 {} 声明了空或过长的 collation",
1761 field.config.name
1762 )));
1763 }
1764 }
1765 validate_validator_configuration(table, &field.config)?;
1766 if let Some(default) = &field.config.default_value {
1767 if matches!(
1768 field.config.field_type,
1769 FieldType::Text | FieldType::Json | FieldType::Bytes | FieldType::Array(_)
1770 ) {
1771 return Err(BaseError::ConfigError(format!(
1772 "表 {table} 的 TEXT/JSON/BYTES/ARRAY 字段不能配置数据库默认值: {}",
1773 field.config.name
1774 )));
1775 }
1776 field.config.validate(default, cache)?;
1777 }
1778 validate_audience(
1779 table,
1780 &field.config.name,
1781 "读取",
1782 &field.config.permissions.readable,
1783 )?;
1784 validate_audience(
1785 table,
1786 &field.config.name,
1787 "写入",
1788 &field.config.permissions.writable,
1789 )?;
1790 validate_audience(
1791 table,
1792 &field.config.name,
1793 "筛选",
1794 &field.config.permissions.filterable,
1795 )?;
1796 validate_audience(
1797 table,
1798 &field.config.name,
1799 "排序",
1800 &field.config.permissions.sortable,
1801 )?;
1802 if let Some(relation) = &field.config.relation {
1803 validate_identifier("关联表", &relation.table)?;
1804 validate_identifier("关联字段", &relation.field)?;
1805 for display_field in &relation.display_fields {
1806 validate_identifier("关联展示字段", display_field)?;
1807 }
1808 }
1809 if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1810 && !matches!(
1811 field.config.field_type,
1812 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1813 )
1814 {
1815 return Err(BaseError::ConfigError(format!(
1816 "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1817 field.config.name
1818 )));
1819 }
1820 Ok(())
1821}
1822
1823fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1824 let string_compatible = matches!(
1825 field.field_type,
1826 FieldType::String { .. }
1827 | FieldType::Text
1828 | FieldType::Enum { .. }
1829 | FieldType::Date
1830 | FieldType::DateTime
1831 );
1832 let numeric_compatible = matches!(
1833 field.field_type,
1834 FieldType::Integer
1835 | FieldType::BigInt
1836 | FieldType::Float
1837 | FieldType::Double
1838 | FieldType::Decimal { .. }
1839 | FieldType::Timestamp
1840 );
1841 let mut min_length: Option<usize> = None;
1842 let mut max_length: Option<usize> = None;
1843 let mut minimum: Option<f64> = None;
1844 let mut maximum: Option<f64> = None;
1845
1846 for validator in &field.validators {
1847 match validator {
1848 Validator::MinLength(value) => {
1849 ensure_validator_type(table, field, validator, string_compatible)?;
1850 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1851 }
1852 Validator::MaxLength(value) => {
1853 ensure_validator_type(table, field, validator, string_compatible)?;
1854 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1855 }
1856 Validator::Min(value) => {
1857 ensure_validator_type(table, field, validator, numeric_compatible)?;
1858 if !value.is_finite() {
1859 return Err(BaseError::ConfigError(format!(
1860 "表 {table} 的字段 {} 数值下限必须是有限数值",
1861 field.name
1862 )));
1863 }
1864 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1865 }
1866 Validator::Max(value) => {
1867 ensure_validator_type(table, field, validator, numeric_compatible)?;
1868 if !value.is_finite() {
1869 return Err(BaseError::ConfigError(format!(
1870 "表 {table} 的字段 {} 数值上限必须是有限数值",
1871 field.name
1872 )));
1873 }
1874 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1875 }
1876 Validator::Email
1877 | Validator::EmailLoose
1878 | Validator::Phone
1879 | Validator::PhoneLoose
1880 | Validator::Url => {
1881 ensure_validator_type(table, field, validator, string_compatible)?;
1882 }
1883 Validator::Regex(pattern) => {
1884 ensure_validator_type(table, field, validator, string_compatible)?;
1885 #[cfg(feature = "validator")]
1886 regex::Regex::new(pattern).map_err(|error| {
1887 BaseError::ConfigError(format!(
1888 "表 {table} 的字段 {} 正则表达式无效: {error}",
1889 field.name
1890 ))
1891 })?;
1892 #[cfg(not(feature = "validator"))]
1893 return Err(BaseError::ConfigError(format!(
1894 "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1895 field.name,
1896 )));
1897 }
1898 Validator::Custom(_) => {}
1899 }
1900 }
1901
1902 if let (Some(min), Some(max)) = (min_length, max_length) {
1903 if min > max {
1904 return Err(BaseError::ConfigError(format!(
1905 "表 {table} 的字段 {} 最小长度不能大于最大长度",
1906 field.name
1907 )));
1908 }
1909 }
1910 if let (
1911 FieldType::String {
1912 max_length: storage_max,
1913 },
1914 Some(min),
1915 ) = (&field.field_type, min_length)
1916 {
1917 if min > *storage_max {
1918 return Err(BaseError::ConfigError(format!(
1919 "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1920 field.name
1921 )));
1922 }
1923 }
1924 if let (Some(min), Some(max)) = (minimum, maximum) {
1925 if min > max {
1926 return Err(BaseError::ConfigError(format!(
1927 "表 {table} 的字段 {} 数值下限不能大于上限",
1928 field.name
1929 )));
1930 }
1931 }
1932 Ok(())
1933}
1934
1935fn ensure_validator_type(
1936 table: &str,
1937 field: &FieldConfig,
1938 validator: &Validator,
1939 compatible: bool,
1940) -> Result<(), BaseError> {
1941 if compatible {
1942 return Ok(());
1943 }
1944 Err(BaseError::ConfigError(format!(
1945 "表 {table} 的字段 {} 类型不能使用{}验证器",
1946 field.name,
1947 validator.display_name()
1948 )))
1949}
1950
1951fn validate_audience(
1952 table: &str,
1953 field: &str,
1954 operation: &str,
1955 audience: &Audience,
1956) -> Result<(), BaseError> {
1957 if let Audience::Roles(roles) = audience {
1958 if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1959 return Err(BaseError::ConfigError(format!(
1960 "表 {table} 的字段 {field} 的{operation}角色不能为空"
1961 )));
1962 }
1963 }
1964 Ok(())
1965}
1966
1967fn set_unique_role(
1968 table: &str,
1969 role: &str,
1970 enabled: bool,
1971 field: &str,
1972 target: &mut Option<String>,
1973) -> Result<(), BaseError> {
1974 if !enabled {
1975 return Ok(());
1976 }
1977 if let Some(existing) = target {
1978 return Err(BaseError::ConfigError(format!(
1979 "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1980 )));
1981 }
1982 *target = Some(field.to_string());
1983 Ok(())
1984}
1985
1986fn validate_index(
1987 table: &str,
1988 field_names: &HashSet<String>,
1989 index: &PendingIndex,
1990 index_names: &mut HashSet<String>,
1991) -> Result<(), BaseError> {
1992 if index.fields.is_empty() && index.expressions.is_empty() {
1993 return Err(BaseError::ConfigError(format!(
1994 "表 {table} 的索引字段与表达式不能同时为空"
1995 )));
1996 }
1997 let mut seen = HashSet::new();
1998 for field in &index.fields {
1999 if !field_names.contains(field) {
2000 return Err(BaseError::ConfigError(format!(
2001 "表 {table} 的索引字段不存在: {field}"
2002 )));
2003 }
2004 if !seen.insert(field) {
2005 return Err(BaseError::ConfigError(format!(
2006 "表 {table} 的索引重复引用字段: {field}"
2007 )));
2008 }
2009 }
2010 for expression in &index.expressions {
2011 validate_check_expression(table, "索引表达式", expression).map_err(|_| {
2012 BaseError::ConfigError(format!(
2013 "表 {table} 的索引表达式必须是单条、非空且长度受限的受信 SQL: {expression}"
2014 ))
2015 })?;
2016 }
2017 if let Some(predicate) = &index.predicate {
2018 validate_check_expression(table, "部分索引谓词", predicate).map_err(|_| {
2019 BaseError::ConfigError(format!(
2020 "表 {table} 的部分索引谓词必须是单条、非空且长度受限的受信 SQL: {predicate}"
2021 ))
2022 })?;
2023 }
2024 if !index.expressions.is_empty() && index.name.is_none() {
2025 return Err(BaseError::ConfigError(format!(
2026 "表 {table} 的表达式索引必须显式声明名称"
2027 )));
2028 }
2029 let prefix = if index.unique { "uk" } else { "idx" };
2030 let effective_name = index
2031 .name
2032 .clone()
2033 .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
2034 validate_identifier("索引", &effective_name)?;
2035 if !index_names.insert(effective_name.clone()) {
2036 return Err(BaseError::ConfigError(format!(
2037 "表 {table} 存在重复索引名: {effective_name}"
2038 )));
2039 }
2040 Ok(())
2041}
2042
2043fn validate_constraint_name(
2044 table: &str,
2045 name: &str,
2046 names: &mut HashSet<String>,
2047) -> Result<(), BaseError> {
2048 validate_identifier("约束", name)?;
2049 if !names.insert(name.to_string()) {
2050 return Err(BaseError::ConfigError(format!(
2051 "表 {table} 存在重复约束名: {name}"
2052 )));
2053 }
2054 Ok(())
2055}
2056
2057fn validate_check_expression(table: &str, name: &str, expression: &str) -> Result<(), BaseError> {
2058 let expression = expression.trim();
2059 if expression.is_empty()
2060 || expression.chars().count() > 2_048
2061 || [";", "--", "/*", "*/"]
2062 .iter()
2063 .any(|marker| expression.contains(marker))
2064 || !has_balanced_check_expression(expression)
2065 {
2066 return Err(BaseError::ConfigError(format!(
2067 "表 {table} 的 CHECK {name} 必须是单条、非空、长度受限且括号平衡的受信表达式"
2068 )));
2069 }
2070 Ok(())
2071}
2072
2073fn validate_foreign_key(
2074 table: &str,
2075 field_names: &HashSet<String>,
2076 foreign_key: &PendingForeignKey,
2077) -> Result<(), BaseError> {
2078 validate_identifier("外键目标表", &foreign_key.referenced_table)?;
2079 if foreign_key.columns.is_empty()
2080 || foreign_key.columns.len() != foreign_key.referenced_columns.len()
2081 {
2082 return Err(BaseError::ConfigError(format!(
2083 "表 {table} 的外键 {} 本地列与目标列必须非空且数量一致",
2084 foreign_key.name
2085 )));
2086 }
2087 let mut local = HashSet::new();
2088 let mut referenced = HashSet::new();
2089 for column in &foreign_key.columns {
2090 validate_identifier("外键列", column)?;
2091 if !field_names.contains(column) || !local.insert(column) {
2092 return Err(BaseError::ConfigError(format!(
2093 "表 {table} 的外键 {} 引用了缺失或重复的本地列 {column}",
2094 foreign_key.name
2095 )));
2096 }
2097 }
2098 for column in &foreign_key.referenced_columns {
2099 validate_identifier("外键目标列", column)?;
2100 if !referenced.insert(column) {
2101 return Err(BaseError::ConfigError(format!(
2102 "表 {table} 的外键 {} 重复引用目标列 {column}",
2103 foreign_key.name
2104 )));
2105 }
2106 }
2107 Ok(())
2108}
2109
2110fn field_json_schema(field: &FieldConfig) -> Value {
2111 let mut schema = Map::new();
2112 let mut min_length: Option<usize> = None;
2113 let mut max_length: Option<usize> = None;
2114 let mut minimum: Option<f64> = None;
2115 let mut maximum: Option<f64> = None;
2116 let mut patterns = Vec::new();
2117 let mut runtime_validators = Vec::new();
2118 match &field.field_type {
2119 FieldType::String {
2120 max_length: storage_max,
2121 } => {
2122 schema.insert("type".into(), json!("string"));
2123 max_length = Some(*storage_max);
2124 }
2125 FieldType::Text => {
2126 schema.insert("type".into(), json!("string"));
2127 }
2128 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
2129 schema.insert("type".into(), json!("integer"));
2130 }
2131 FieldType::Float | FieldType::Double => {
2132 schema.insert("type".into(), json!("number"));
2133 }
2134 FieldType::Decimal { precision, scale } => {
2135 schema.insert("type".into(), json!("string"));
2136 schema.insert("format".into(), json!("decimal"));
2137 schema.insert("x-precision".into(), json!(precision));
2138 schema.insert("x-scale".into(), json!(scale));
2139 }
2140 FieldType::Boolean => {
2141 schema.insert("type".into(), json!("boolean"));
2142 }
2143 FieldType::Date => {
2144 schema.insert("type".into(), json!("string"));
2145 schema.insert("format".into(), json!("date"));
2146 }
2147 FieldType::DateTime => {
2148 schema.insert("type".into(), json!("string"));
2149 schema.insert("format".into(), json!("date-time"));
2150 }
2151 FieldType::Json => {
2152 schema.insert("type".into(), json!(["object", "array"]));
2153 }
2154 FieldType::Enum { values } => {
2155 schema.insert("type".into(), json!("string"));
2156 schema.insert("enum".into(), json!(values));
2157 }
2158 FieldType::Uuid => {
2159 schema.insert("type".into(), json!("string"));
2160 schema.insert("format".into(), json!("uuid"));
2161 }
2162 FieldType::Bytes => {
2163 schema.insert("type".into(), json!("string"));
2165 schema.insert("format".into(), json!("byte"));
2166 }
2167 FieldType::Array(element) => {
2168 schema.insert("type".into(), json!("array"));
2169 schema.insert("items".into(), storage_type_json_schema(element));
2170 }
2171 }
2172
2173 for validator in &field.validators {
2174 match validator {
2175 Validator::MinLength(value) => {
2176 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
2177 }
2178 Validator::MaxLength(value) => {
2179 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
2180 }
2181 Validator::Min(value) => {
2182 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
2183 }
2184 Validator::Max(value) => {
2185 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
2186 }
2187 Validator::Email => {
2188 #[cfg(feature = "validator")]
2189 patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
2190 #[cfg(not(feature = "validator"))]
2191 patterns.push("@".to_string());
2192 }
2193 Validator::EmailLoose => patterns.push("@".to_string()),
2194 Validator::Phone => {
2195 #[cfg(feature = "validator")]
2196 patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
2197 #[cfg(not(feature = "validator"))]
2198 patterns.push(r"^[0-9+\-]*$".to_string());
2199 }
2200 Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
2201 Validator::Url => patterns.push(r"^https?://".to_string()),
2202 Validator::Regex(pattern) => patterns.push(pattern.clone()),
2203 Validator::Custom(_) => runtime_validators.push("custom"),
2204 }
2205 }
2206
2207 if let Some(value) = min_length {
2208 schema.insert("minLength".into(), json!(value));
2209 }
2210 if let Some(value) = max_length {
2211 schema.insert("maxLength".into(), json!(value));
2212 }
2213 if let Some(value) = minimum {
2214 schema.insert("minimum".into(), json!(value));
2215 }
2216 if let Some(value) = maximum {
2217 schema.insert("maximum".into(), json!(value));
2218 }
2219 match patterns.as_slice() {
2220 [] => {}
2221 [pattern] => {
2222 schema.insert("pattern".into(), json!(pattern));
2223 }
2224 patterns => {
2225 schema.insert(
2226 "allOf".into(),
2227 Value::Array(
2228 patterns
2229 .iter()
2230 .map(|pattern| json!({ "pattern": pattern }))
2231 .collect(),
2232 ),
2233 );
2234 }
2235 }
2236 if !runtime_validators.is_empty() {
2237 schema.insert(
2238 "x-yang-runtime-validators".into(),
2239 json!(runtime_validators),
2240 );
2241 }
2242 if let Some(relation) = &field.relation {
2243 let relation_type = match relation.relation_type {
2244 RelationType::OneToOne => "one_to_one",
2245 RelationType::OneToMany => "one_to_many",
2246 RelationType::ManyToOne => "many_to_one",
2247 RelationType::ManyToMany => "many_to_many",
2248 };
2249 schema.insert(
2250 "x-yang-relation".into(),
2251 json!({
2252 "table": relation.table,
2253 "field": relation.field,
2254 "displayFields": relation.display_fields,
2255 "type": relation_type,
2256 }),
2257 );
2258 }
2259
2260 if !field.required {
2261 if let Some(field_types) = schema.get_mut("type") {
2262 match field_types {
2263 Value::String(field_type) => {
2264 *field_types = json!([field_type.clone(), "null"]);
2265 }
2266 Value::Array(types) if !types.iter().any(|value| value == "null") => {
2267 types.push(json!("null"));
2268 }
2269 _ => {}
2270 }
2271 }
2272 if let Some(Value::Array(values)) = schema.get_mut("enum") {
2273 values.push(Value::Null);
2274 }
2275 }
2276 if !field.display_name.is_empty() {
2277 schema.insert("title".into(), json!(field.display_name));
2278 }
2279 if let Some(default) = &field.default_value {
2280 schema.insert("default".into(), default.clone());
2281 }
2282 Value::Object(schema)
2283}
2284
2285fn storage_type_json_schema(field_type: &FieldType) -> Value {
2287 match field_type {
2288 FieldType::String { max_length } => json!({
2289 "type": "string",
2290 "maxLength": max_length,
2291 }),
2292 FieldType::Text => json!({"type": "string"}),
2293 FieldType::Uuid => json!({"type": "string", "format": "uuid"}),
2294 FieldType::Bytes => json!({"type": "string", "format": "byte"}),
2295 FieldType::Enum { values } => json!({"type": "string", "enum": values}),
2296 FieldType::Decimal { precision, scale } => json!({
2297 "type": "string",
2298 "format": "decimal",
2299 "x-precision": precision,
2300 "x-scale": scale,
2301 }),
2302 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => json!({"type": "integer"}),
2303 FieldType::Float | FieldType::Double => json!({"type": "number"}),
2304 FieldType::Boolean => json!({"type": "boolean"}),
2305 FieldType::Date => json!({"type": "string", "format": "date"}),
2306 FieldType::DateTime => json!({"type": "string", "format": "date-time"}),
2307 FieldType::Json | FieldType::Array(_) => json!({}),
2309 }
2310}
2311
2312#[cfg(test)]
2313mod composite_primary_key_tests {
2314 use super::*;
2315
2316 #[test]
2317 fn table_without_primary_key_is_allowed() {
2318 let definition = Table::new("no_pk")
2319 .fields([Field::string("name", 64).required()])
2320 .build()
2321 .expect("无主键表定义应有效");
2322 assert!(definition.primary_keys().is_empty());
2323 assert_eq!(definition.primary_key(), "");
2324 }
2325
2326 #[test]
2327 fn composite_primary_key_keeps_all_columns() {
2328 let definition = Table::new("composite_pk")
2329 .fields([
2330 Field::bigint("tenant_id").required().primary_key(),
2331 Field::bigint("item_id").required().primary_key(),
2332 Field::string("name", 64),
2333 ])
2334 .build()
2335 .expect("复合主键表定义应有效");
2336 assert_eq!(definition.primary_key(), "tenant_id");
2337 assert_eq!(definition.primary_keys(), ["tenant_id", "item_id"]);
2338 }
2339}
2340
2341#[cfg(test)]
2342mod generated_expression_tests {
2343 use super::*;
2344
2345 fn generated_table(expression: &str) -> Result<TableDefinition, BaseError> {
2346 Table::new("generated_balance")
2347 .fields([
2348 Field::id("id"),
2349 Field::integer("price").required(),
2350 Field::string("name", 32),
2351 Field::bigint("total").generated(expression),
2352 ])
2353 .build()
2354 }
2355
2356 #[test]
2357 fn balanced_generated_expressions_pass() {
2358 generated_table("price * 2").expect("简单表达式应通过");
2359 generated_table("coalesce(price, 0)").expect("函数调用应通过");
2360 generated_table("coalesce(name, ')')").expect("字符串字面量含右括号应通过");
2362 generated_table(r"coalesce(name, E'\')')").expect("E 字符串转义应通过");
2364 }
2365
2366 #[test]
2367 fn generated_expression_injection_is_rejected() {
2368 let error = generated_table("price) STORED, 注入 INTEGER")
2369 .expect_err("闭合外层括号的注入表达式必须拒绝");
2370 assert!(
2371 matches!(error, BaseError::ConfigError(ref message) if message.contains("生成列")),
2372 "实得错误: {error:?}"
2373 );
2374 }
2375}
2376
2377#[cfg(test)]
2378mod check_expression_tests {
2379 use super::*;
2380
2381 fn check_table(expression: &str) -> Result<TableDefinition, BaseError> {
2382 Table::new("check_balance")
2383 .fields([
2384 Field::id("id"),
2385 Field::integer("price").required(),
2386 Field::string("status", 32),
2387 Field::string("note", 64),
2388 ])
2389 .check_named("chk_balance", expression)
2390 .build()
2391 }
2392
2393 #[test]
2394 fn legal_check_expressions_pass() {
2395 check_table("price > 0").expect("简单表达式应通过");
2396 check_table("price > 0 AND status <> 'banned'").expect("字符串字面量应通过");
2397 check_table("(price > 0)").expect("成对分组括号应通过");
2398 check_table("`parent_id` > 0").expect("反引号标识符应通过");
2399 check_table(r"note <> 'it\'s)'").expect("MySQL 反斜杠转义字符串应通过");
2401 check_table("`amount)` > 0").expect("反引号内的括号应通过");
2403 check_table("price > 0 # note (policy 2024\nAND status <> 'cancelled'")
2405 .expect("MySQL # 注释应通过");
2406 check_table("$q$a)b$q$").expect("PostgreSQL 美元引号应通过");
2408 check_table(r"note <> E'\')'").expect("PostgreSQL E 字符串应通过");
2410 }
2411
2412 #[test]
2413 fn check_expression_injection_is_rejected() {
2414 let error = check_table("price > 0), evil INT, CHECK (1=1")
2417 .expect_err("闭合外层括号的注入表达式必须拒绝");
2418 assert!(
2419 matches!(error, BaseError::ConfigError(ref message) if message.contains("CHECK")),
2420 "实得错误: {error:?}"
2421 );
2422 }
2423}