1use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{IndexConfig, TableConfig, TimestampFields};
9#[cfg(feature = "mysql")]
10use super::TableQuery;
11use super::{FieldType, SortOrder, Validator};
12use crate::error::BaseError;
13use serde_json::{json, Map, Value};
14use std::collections::{HashMap, HashSet};
15use std::sync::Arc;
16
17pub fn col(name: impl Into<String>) -> ColumnName {
19 ColumnName(name.into())
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub struct ColumnName(String);
25
26impl ColumnName {
27 pub fn asc(self) -> Order {
29 Order {
30 field: self.0,
31 direction: SortOrder::Asc,
32 }
33 }
34
35 pub fn desc(self) -> Order {
37 Order {
38 field: self.0,
39 direction: SortOrder::Desc,
40 }
41 }
42
43 fn into_name(self) -> String {
44 self.0
45 }
46}
47
48impl From<&str> for ColumnName {
49 fn from(value: &str) -> Self {
50 Self(value.to_string())
51 }
52}
53
54impl From<String> for ColumnName {
55 fn from(value: String) -> Self {
56 Self(value)
57 }
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Order {
63 field: String,
64 direction: SortOrder,
65}
66
67#[derive(Debug, Clone)]
72#[must_use = "字段定义必须传给 Table::fields"]
73pub struct Field {
74 config: FieldConfig,
75 primary_key: bool,
76 unique: bool,
77 unique_name: Option<String>,
78 index: bool,
79 index_name: Option<String>,
80 created_at: bool,
81 updated_at: bool,
82 deleted_at: bool,
83 soft_delete: bool,
84 relation_display_fields: Option<Vec<String>>,
85}
86
87impl Field {
88 fn new(name: impl Into<String>, field_type: FieldType) -> Self {
89 Self {
90 config: FieldConfig::new(name, field_type),
91 primary_key: false,
92 unique: false,
93 unique_name: None,
94 index: false,
95 index_name: None,
96 created_at: false,
97 updated_at: false,
98 deleted_at: false,
99 soft_delete: false,
100 relation_display_fields: None,
101 }
102 }
103
104 pub fn id(name: impl Into<String>) -> Self {
106 Self::new(name, FieldType::BigInt)
107 .required()
108 .primary_key()
109 .auto_increment()
110 .not_writable()
111 }
112
113 pub fn string(name: impl Into<String>, max_length: usize) -> Self {
115 Self::new(name, FieldType::String { max_length })
116 }
117
118 pub fn integer(name: impl Into<String>) -> Self {
120 Self::new(name, FieldType::Integer)
121 }
122
123 pub fn bigint(name: impl Into<String>) -> Self {
125 Self::new(name, FieldType::BigInt)
126 }
127
128 pub fn float(name: impl Into<String>) -> Self {
130 Self::new(name, FieldType::Float)
131 }
132
133 pub fn double(name: impl Into<String>) -> Self {
135 Self::new(name, FieldType::Double)
136 }
137
138 pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
140 Self::new(name, FieldType::Decimal { precision, scale })
141 }
142
143 pub fn boolean(name: impl Into<String>) -> Self {
145 Self::new(name, FieldType::Boolean)
146 }
147
148 pub fn date(name: impl Into<String>) -> Self {
150 Self::new(name, FieldType::Date)
151 }
152
153 pub fn datetime(name: impl Into<String>) -> Self {
155 Self::new(name, FieldType::DateTime)
156 }
157
158 pub fn timestamp(name: impl Into<String>) -> Self {
160 Self::new(name, FieldType::Timestamp)
161 }
162
163 pub fn json(name: impl Into<String>) -> Self {
165 Self::new(name, FieldType::Json)
166 }
167
168 pub fn text(name: impl Into<String>) -> Self {
170 Self::new(name, FieldType::Text)
171 }
172
173 pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
175 where
176 I: IntoIterator<Item = S>,
177 S: Into<String>,
178 {
179 Self::new(
180 name,
181 FieldType::Enum {
182 values: values.into_iter().map(Into::into).collect(),
183 },
184 )
185 }
186
187 pub fn created_at(name: impl Into<String>) -> Self {
189 let mut field = Self::bigint(name).required().not_writable();
190 field.created_at = true;
191 field
192 }
193
194 pub fn updated_at(name: impl Into<String>) -> Self {
196 let mut field = Self::bigint(name).required().not_writable();
197 field.updated_at = true;
198 field
199 }
200
201 pub fn soft_delete(name: impl Into<String>) -> Self {
203 let mut field = Self::bigint(name).not_writable();
204 field.deleted_at = true;
205 field.soft_delete = true;
206 field
207 }
208
209 pub fn label(mut self, label: impl Into<String>) -> Self {
211 self.config.display_name = label.into();
212 self
213 }
214
215 pub fn required(mut self) -> Self {
217 self.config.required = true;
218 self
219 }
220
221 pub fn nullable(mut self) -> Self {
223 self.config.required = false;
224 self
225 }
226
227 pub fn default(mut self, value: impl Into<Value>) -> Self {
229 self.config.default_value = Some(value.into());
230 self
231 }
232
233 pub fn auto_increment(mut self) -> Self {
235 self.config.auto_increment = true;
236 self
237 }
238
239 pub fn primary_key(mut self) -> Self {
241 self.primary_key = true;
242 self
243 }
244
245 pub fn unique(mut self) -> Self {
247 self.unique = true;
248 self
249 }
250
251 pub fn unique_named(mut self, name: impl Into<String>) -> Self {
253 self.unique = true;
254 self.unique_name = Some(name.into());
255 self
256 }
257
258 pub fn index(mut self) -> Self {
260 self.index = true;
261 self
262 }
263
264 pub fn index_named(mut self, name: impl Into<String>) -> Self {
266 self.index = true;
267 self.index_name = Some(name.into());
268 self
269 }
270
271 pub fn validator(mut self, validator: Validator) -> Self {
273 self.config.validators.push(validator);
274 self
275 }
276
277 pub fn min_length(self, value: usize) -> Self {
279 self.validator(Validator::MinLength(value))
280 }
281
282 pub fn max_length(self, value: usize) -> Self {
284 self.validator(Validator::MaxLength(value))
285 }
286
287 pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
289 self.min_length(*range.start()).max_length(*range.end())
290 }
291
292 pub fn min(self, value: f64) -> Self {
294 self.validator(Validator::Min(value))
295 }
296
297 pub fn max(self, value: f64) -> Self {
299 self.validator(Validator::Max(value))
300 }
301
302 pub fn email(self) -> Self {
304 self.validator(Validator::Email)
305 }
306
307 pub fn phone(self) -> Self {
309 self.validator(Validator::Phone)
310 }
311
312 pub fn url(self) -> Self {
314 self.validator(Validator::Url)
315 }
316
317 pub fn regex(self, pattern: impl Into<String>) -> Self {
319 self.validator(Validator::Regex(pattern.into()))
320 }
321
322 pub fn readable(mut self) -> Self {
324 self.config.permissions.readable = Audience::Everyone;
325 self
326 }
327
328 pub fn not_readable(mut self) -> Self {
330 self.config.permissions.readable = Audience::Nobody;
331 self
332 }
333
334 pub fn readable_by<I, S>(mut self, roles: I) -> Self
336 where
337 I: IntoIterator<Item = S>,
338 S: Into<String>,
339 {
340 self.config.permissions.readable = Audience::roles(roles);
341 self
342 }
343
344 pub fn writable_by<I, S>(mut self, roles: I) -> Self
346 where
347 I: IntoIterator<Item = S>,
348 S: Into<String>,
349 {
350 self.config.permissions.writable = Audience::roles(roles);
351 self
352 }
353
354 pub fn writable(mut self) -> Self {
356 self.config.permissions.writable = Audience::Everyone;
357 self
358 }
359
360 pub fn not_writable(mut self) -> Self {
362 self.config.permissions.writable = Audience::Nobody;
363 self
364 }
365
366 pub fn searchable(mut self) -> Self {
372 self.config.searchable = true;
373 self
374 }
375
376 pub fn filterable(mut self) -> Self {
378 self.config.filterable = true;
379 self.config.permissions.filterable = Audience::Everyone;
380 self
381 }
382
383 pub fn not_filterable(mut self) -> Self {
385 self.config.filterable = false;
386 self.config.permissions.filterable = Audience::Nobody;
387 self
388 }
389
390 pub fn filterable_by<I, S>(mut self, roles: I) -> Self
392 where
393 I: IntoIterator<Item = S>,
394 S: Into<String>,
395 {
396 self.config.filterable = true;
397 self.config.permissions.filterable = Audience::roles(roles);
398 self
399 }
400
401 pub fn sortable(mut self) -> Self {
403 self.config.sortable = true;
404 self.config.permissions.sortable = Audience::Everyone;
405 self
406 }
407
408 pub fn not_sortable(mut self) -> Self {
410 self.config.sortable = false;
411 self.config.permissions.sortable = Audience::Nobody;
412 self
413 }
414
415 pub fn sortable_by<I, S>(mut self, roles: I) -> Self
417 where
418 I: IntoIterator<Item = S>,
419 S: Into<String>,
420 {
421 self.config.sortable = true;
422 self.config.permissions.sortable = Audience::roles(roles);
423 self
424 }
425
426 pub fn tenant_key(mut self) -> Self {
428 self.config.tenant_key = true;
429 self
430 }
431
432 pub fn secret(mut self) -> Self {
438 self.config.hidden = true;
439 self.config.permissions = FieldPermissions {
440 readable: Audience::Nobody,
441 writable: Audience::Nobody,
442 filterable: Audience::Nobody,
443 sortable: Audience::Nobody,
444 };
445 self.config.searchable = false;
446 self.config.filterable = false;
447 self.config.sortable = false;
448 self
449 }
450
451 pub fn relation(
453 mut self,
454 table: impl Into<String>,
455 field: impl Into<String>,
456 relation_type: RelationType,
457 ) -> Self {
458 self.config.relation = Some(RelationConfig {
459 table: table.into(),
460 field: field.into(),
461 display_fields: Vec::new(),
462 relation_type,
463 });
464 self
465 }
466
467 pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
469 where
470 I: IntoIterator<Item = S>,
471 S: Into<String>,
472 {
473 self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
474 self
475 }
476}
477
478#[derive(Debug, Clone)]
479struct PendingIndex {
480 name: Option<String>,
481 fields: Vec<String>,
482 unique: bool,
483}
484
485#[derive(Debug, Clone)]
487#[must_use = "表构建器必须调用 build"]
488pub struct Table {
489 name: String,
490 label: Option<String>,
491 fields: Vec<Field>,
492 indexes: Vec<PendingIndex>,
493 default_order: Vec<Order>,
494}
495
496impl Table {
497 pub fn new(name: impl Into<String>) -> Self {
499 Self {
500 name: name.into(),
501 label: None,
502 fields: Vec::new(),
503 indexes: Vec::new(),
504 default_order: Vec::new(),
505 }
506 }
507
508 pub fn label(mut self, label: impl Into<String>) -> Self {
510 self.label = Some(label.into());
511 self
512 }
513
514 pub fn fields<I>(mut self, fields: I) -> Self
516 where
517 I: IntoIterator<Item = Field>,
518 {
519 self.fields.extend(fields);
520 self
521 }
522
523 pub fn unique<I, C>(mut self, fields: I) -> Self
525 where
526 I: IntoIterator<Item = C>,
527 C: Into<ColumnName>,
528 {
529 self.indexes.push(PendingIndex {
530 name: None,
531 fields: fields
532 .into_iter()
533 .map(|field| field.into().into_name())
534 .collect(),
535 unique: true,
536 });
537 self
538 }
539
540 pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
542 where
543 I: IntoIterator<Item = C>,
544 C: Into<ColumnName>,
545 {
546 self.indexes.push(PendingIndex {
547 name: Some(name.into()),
548 fields: fields
549 .into_iter()
550 .map(|field| field.into().into_name())
551 .collect(),
552 unique: true,
553 });
554 self
555 }
556
557 pub fn index<I, C>(mut self, fields: I) -> Self
559 where
560 I: IntoIterator<Item = C>,
561 C: Into<ColumnName>,
562 {
563 self.indexes.push(PendingIndex {
564 name: None,
565 fields: fields
566 .into_iter()
567 .map(|field| field.into().into_name())
568 .collect(),
569 unique: false,
570 });
571 self
572 }
573
574 pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
576 where
577 I: IntoIterator<Item = C>,
578 C: Into<ColumnName>,
579 {
580 self.indexes.push(PendingIndex {
581 name: Some(name.into()),
582 fields: fields
583 .into_iter()
584 .map(|field| field.into().into_name())
585 .collect(),
586 unique: false,
587 });
588 self
589 }
590
591 pub fn default_order(mut self, order: Order) -> Self {
593 self.default_order = vec![order];
594 self
595 }
596
597 pub fn then_order(mut self, order: Order) -> Self {
599 self.default_order.push(order);
600 self
601 }
602
603 pub fn build(self) -> Result<TableDefinition, BaseError> {
605 validate_identifier("表", &self.name)?;
606 if self.fields.is_empty() {
607 return Err(BaseError::ConfigError(format!(
608 "表 {} 至少需要一个字段",
609 self.name
610 )));
611 }
612
613 let mut field_names = HashSet::with_capacity(self.fields.len());
614 let mut configs = HashMap::with_capacity(self.fields.len());
615 let mut primary_key: Option<String> = None;
616 let mut created_at: Option<String> = None;
617 let mut updated_at: Option<String> = None;
618 let mut deleted_at: Option<String> = None;
619 let mut soft_delete: Option<String> = None;
620 let mut tenant_key: Option<String> = None;
621 let mut indexes = self.indexes;
622
623 for mut field in self.fields {
624 validate_identifier("字段", &field.config.name)?;
625 if !field_names.insert(field.config.name.clone()) {
626 return Err(BaseError::ConfigError(format!(
627 "表 {} 存在重复字段: {}",
628 self.name, field.config.name
629 )));
630 }
631 if field.config.display_name.is_empty() {
632 field.config.display_name = field.config.name.clone();
633 }
634 if let Some(display_fields) = field.relation_display_fields.take() {
635 let relation = field.config.relation.as_mut().ok_or_else(|| {
636 BaseError::ConfigError(format!(
637 "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
638 self.name, field.config.name
639 ))
640 })?;
641 relation.display_fields = display_fields;
642 }
643 validate_field_shape(&self.name, &field)?;
644
645 if field.primary_key && primary_key.replace(field.config.name.clone()).is_some() {
646 return Err(BaseError::ConfigError(format!(
647 "表 {} 只能定义一个主键",
648 self.name
649 )));
650 }
651 if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
652 return Err(BaseError::ConfigError(format!(
653 "表 {} 只能定义一个租户隔离字段",
654 self.name
655 )));
656 }
657 set_unique_role(
658 &self.name,
659 "created_at",
660 field.created_at,
661 &field.config.name,
662 &mut created_at,
663 )?;
664 set_unique_role(
665 &self.name,
666 "updated_at",
667 field.updated_at,
668 &field.config.name,
669 &mut updated_at,
670 )?;
671 set_unique_role(
672 &self.name,
673 "deleted_at",
674 field.deleted_at,
675 &field.config.name,
676 &mut deleted_at,
677 )?;
678 set_unique_role(
679 &self.name,
680 "soft_delete",
681 field.soft_delete,
682 &field.config.name,
683 &mut soft_delete,
684 )?;
685
686 if field.unique {
687 indexes.push(PendingIndex {
688 name: field.unique_name.take(),
689 fields: vec![field.config.name.clone()],
690 unique: true,
691 });
692 }
693 if field.index {
694 indexes.push(PendingIndex {
695 name: field.index_name.take(),
696 fields: vec![field.config.name.clone()],
697 unique: false,
698 });
699 }
700 configs.insert(field.config.name.clone(), field.config);
701 }
702
703 let primary_key = primary_key
704 .ok_or_else(|| BaseError::ConfigError(format!("表 {} 必须定义一个主键", self.name)))?;
705
706 let mut unique_indexes = Vec::new();
707 let mut normal_indexes = Vec::new();
708 let mut index_names = HashSet::new();
709 for index in indexes {
710 validate_index(&self.name, &field_names, &index, &mut index_names)?;
711 let config = IndexConfig::new(index.name, index.fields);
712 if index.unique {
713 unique_indexes.push(config);
714 } else {
715 normal_indexes.push(config);
716 }
717 }
718
719 let mut orders = Vec::with_capacity(self.default_order.len());
720 for order in self.default_order {
721 if !field_names.contains(&order.field) {
722 return Err(BaseError::ConfigError(format!(
723 "表 {} 的默认排序字段不存在: {}",
724 self.name, order.field
725 )));
726 }
727 orders.push((order.field, order.direction));
728 }
729
730 let timestamp_fields =
731 if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
732 Some(TimestampFields::new(created_at, updated_at, deleted_at))
733 } else {
734 None
735 };
736 let table_ref = yang_db::TableRef::new(self.name.clone())
737 .map_err(|error| BaseError::ConfigError(error.to_string()))?;
738 let field_refs = field_names
739 .iter()
740 .map(|name| {
741 yang_db::FieldRef::new(name.clone())
742 .map(|field| (name.clone(), field))
743 .map_err(|error| BaseError::ConfigError(error.to_string()))
744 })
745 .collect::<Result<HashMap<_, _>, _>>()?;
746
747 Ok(TableDefinition {
748 config: Arc::new(TableConfig {
749 table_name: self.name.clone(),
750 table_ref,
751 display_name: self.label.unwrap_or(self.name),
752 primary_key,
753 fields: configs,
754 field_refs,
755 unique_indexes,
756 indexes: normal_indexes,
757 default_order: orders,
758 soft_delete_field: soft_delete,
759 timestamp_fields,
760 }),
761 })
762 }
763}
764
765#[derive(Debug, Clone)]
767pub struct TableDefinition {
768 pub(crate) config: Arc<TableConfig>,
769}
770
771impl TableDefinition {
772 pub fn name(&self) -> &str {
774 &self.config.table_name
775 }
776
777 pub fn label(&self) -> &str {
779 &self.config.display_name
780 }
781
782 pub fn primary_key(&self) -> &str {
784 &self.config.primary_key
785 }
786
787 pub fn field_count(&self) -> usize {
789 self.config.fields.len()
790 }
791
792 pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
794 self.config
795 .fields
796 .get(name)
797 .map(|config| FieldMetadata { config })
798 }
799
800 pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
802 let mut fields: Vec<_> = self
803 .config
804 .fields
805 .values()
806 .map(|config| FieldMetadata { config })
807 .collect();
808 fields.sort_by(|left, right| left.name().cmp(right.name()));
809 fields
810 }
811
812 pub fn soft_delete_field(&self) -> Option<&str> {
814 self.config.soft_delete_field.as_deref()
815 }
816
817 pub fn tenant_key_field(&self) -> Option<&str> {
819 self.config
820 .fields
821 .values()
822 .find(|field| field.tenant_key)
823 .map(|field| field.name.as_str())
824 }
825
826 pub fn input_schema(&self) -> Value {
831 self.json_schema(false, None)
832 }
833
834 pub fn output_schema(&self) -> Value {
839 self.json_schema(true, None)
840 }
841
842 pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
844 self.json_schema(false, Some(roles))
845 }
846
847 pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
849 self.json_schema(true, Some(roles))
850 }
851
852 #[cfg(feature = "mysql")]
854 pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
855 self.config.fields.get(name).map(field_json_schema)
856 }
857
858 fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
859 let mut properties = Map::new();
860 let mut required = Vec::new();
861 let mut names: Vec<_> = self.config.fields.keys().collect();
862 names.sort();
863 for name in names {
864 let field = &self.config.fields[name];
865 let generated = field.auto_increment
866 || self
867 .config
868 .timestamp_fields
869 .as_ref()
870 .is_some_and(|timestamps| {
871 timestamps.created_at.as_deref() == Some(name.as_str())
872 || timestamps.updated_at.as_deref() == Some(name.as_str())
873 || timestamps.deleted_at.as_deref() == Some(name.as_str())
874 })
875 || self.config.soft_delete_field.as_deref() == Some(name.as_str());
876 let audience = if output {
877 &field.permissions.readable
878 } else {
879 &field.permissions.writable
880 };
881 let audience_allows = roles.map_or_else(
882 || !matches!(audience, Audience::Nobody),
883 |roles| audience.allows(roles),
884 );
885 if field.hidden || !audience_allows || (!output && generated) {
886 continue;
887 }
888 properties.insert(name.clone(), field_json_schema(field));
889 if field.required && (output || (!generated && field.default_value.is_none())) {
890 required.push(Value::String(name.clone()));
891 }
892 }
893 json!({
894 "type": "object",
895 "title": self.config.display_name,
896 "properties": properties,
897 "required": required,
898 "additionalProperties": false,
899 })
900 }
901
902 #[cfg(feature = "mysql")]
903 pub(crate) fn config(&self) -> &TableConfig {
904 &self.config
905 }
906
907 pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
908 Arc::clone(&self.config)
909 }
910
911 pub fn validate_schema(
913 &self,
914 columns: &[super::SchemaColumn],
915 ) -> super::SchemaValidationReport {
916 self.config.validate_schema(columns)
917 }
918
919 #[cfg(feature = "mysql")]
921 pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
922 TableHandle {
923 definition: self.clone(),
924 pool,
925 }
926 }
927}
928
929#[derive(Debug, Clone, Copy)]
931pub struct FieldMetadata<'a> {
932 config: &'a FieldConfig,
933}
934
935impl<'a> FieldMetadata<'a> {
936 pub fn name(self) -> &'a str {
938 &self.config.name
939 }
940
941 pub fn label(self) -> &'a str {
943 &self.config.display_name
944 }
945
946 pub fn is_tenant_key(self) -> bool {
948 self.config.tenant_key
949 }
950
951 pub fn field_type(self) -> &'a FieldType {
953 &self.config.field_type
954 }
955
956 pub fn is_required(self) -> bool {
958 self.config.required
959 }
960
961 pub fn default_value(self) -> Option<&'a Value> {
963 self.config.default_value.as_ref()
964 }
965
966 pub fn is_auto_increment(self) -> bool {
968 self.config.auto_increment
969 }
970
971 pub fn is_searchable(self) -> bool {
973 self.config.searchable
974 }
975
976 pub fn is_filterable(self) -> bool {
978 self.config.filterable
979 }
980
981 pub fn is_sortable(self) -> bool {
983 self.config.sortable
984 }
985
986 pub fn is_secret(self) -> bool {
988 self.config.hidden
989 }
990}
991
992#[cfg(feature = "mysql")]
994#[derive(Debug, Clone)]
995pub struct TableHandle {
996 definition: TableDefinition,
997 pool: Arc<sqlx::MySqlPool>,
998}
999
1000#[cfg(feature = "mysql")]
1001impl TableHandle {
1002 pub fn definition(&self) -> &TableDefinition {
1004 &self.definition
1005 }
1006
1007 pub fn query<I, S>(&self, roles: I) -> TableQuery
1009 where
1010 I: IntoIterator<Item = S>,
1011 S: Into<String>,
1012 {
1013 let roles: Arc<[String]> =
1014 Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1015 TableQuery::new(
1016 self.definition.shared_config(),
1017 roles,
1018 Some(Arc::clone(&self.pool)),
1019 )
1020 }
1021}
1022
1023fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1024 let mut chars = value.chars();
1025 let first = chars
1026 .next()
1027 .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1028 if value.len() > 64
1029 || !(first == '_' || first.is_ascii_alphabetic())
1030 || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1031 {
1032 return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1033 }
1034 Ok(())
1035}
1036
1037fn validate_field_shape(table: &str, field: &Field) -> Result<(), BaseError> {
1038 match &field.config.field_type {
1039 FieldType::String { max_length } if *max_length == 0 => {
1040 return Err(BaseError::ConfigError(format!(
1041 "表 {table} 的字符串字段 {} 长度必须大于 0",
1042 field.config.name
1043 )));
1044 }
1045 FieldType::Enum { values } => {
1046 let unique: HashSet<_> = values.iter().collect();
1047 if values.is_empty() || unique.len() != values.len() {
1048 return Err(BaseError::ConfigError(format!(
1049 "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1050 field.config.name
1051 )));
1052 }
1053 }
1054 FieldType::Decimal { precision, scale }
1055 if *precision == 0 || *precision > 65 || *scale > *precision =>
1056 {
1057 return Err(BaseError::ConfigError(format!(
1058 "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1059 field.config.name
1060 )));
1061 }
1062 _ => {}
1063 }
1064
1065 if field.config.auto_increment
1066 && (!field.primary_key
1067 || !matches!(
1068 field.config.field_type,
1069 FieldType::Integer | FieldType::BigInt
1070 ))
1071 {
1072 return Err(BaseError::ConfigError(format!(
1073 "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1074 field.config.name
1075 )));
1076 }
1077 if field.primary_key && !field.config.required {
1078 return Err(BaseError::ConfigError(format!(
1079 "表 {table} 的主键必须为必填字段: {}",
1080 field.config.name
1081 )));
1082 }
1083 if field.config.auto_increment && field.config.default_value.is_some() {
1084 return Err(BaseError::ConfigError(format!(
1085 "表 {table} 的自增字段不能配置默认值: {}",
1086 field.config.name
1087 )));
1088 }
1089 validate_validator_configuration(table, &field.config)?;
1090 if let Some(default) = &field.config.default_value {
1091 if matches!(field.config.field_type, FieldType::Text | FieldType::Json) {
1092 return Err(BaseError::ConfigError(format!(
1093 "表 {table} 的 TEXT/JSON 字段不能配置数据库默认值: {}",
1094 field.config.name
1095 )));
1096 }
1097 field.config.validate(default)?;
1098 }
1099 validate_audience(
1100 table,
1101 &field.config.name,
1102 "读取",
1103 &field.config.permissions.readable,
1104 )?;
1105 validate_audience(
1106 table,
1107 &field.config.name,
1108 "写入",
1109 &field.config.permissions.writable,
1110 )?;
1111 validate_audience(
1112 table,
1113 &field.config.name,
1114 "筛选",
1115 &field.config.permissions.filterable,
1116 )?;
1117 validate_audience(
1118 table,
1119 &field.config.name,
1120 "排序",
1121 &field.config.permissions.sortable,
1122 )?;
1123 if let Some(relation) = &field.config.relation {
1124 validate_identifier("关联表", &relation.table)?;
1125 validate_identifier("关联字段", &relation.field)?;
1126 for display_field in &relation.display_fields {
1127 validate_identifier("关联展示字段", display_field)?;
1128 }
1129 }
1130 if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1131 && !matches!(
1132 field.config.field_type,
1133 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1134 )
1135 {
1136 return Err(BaseError::ConfigError(format!(
1137 "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1138 field.config.name
1139 )));
1140 }
1141 Ok(())
1142}
1143
1144fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1145 let string_compatible = matches!(
1146 field.field_type,
1147 FieldType::String { .. }
1148 | FieldType::Text
1149 | FieldType::Enum { .. }
1150 | FieldType::Date
1151 | FieldType::DateTime
1152 );
1153 let numeric_compatible = matches!(
1154 field.field_type,
1155 FieldType::Integer
1156 | FieldType::BigInt
1157 | FieldType::Float
1158 | FieldType::Double
1159 | FieldType::Decimal { .. }
1160 | FieldType::Timestamp
1161 );
1162 let mut min_length: Option<usize> = None;
1163 let mut max_length: Option<usize> = None;
1164 let mut minimum: Option<f64> = None;
1165 let mut maximum: Option<f64> = None;
1166
1167 for validator in &field.validators {
1168 match validator {
1169 Validator::MinLength(value) => {
1170 ensure_validator_type(table, field, validator, string_compatible)?;
1171 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1172 }
1173 Validator::MaxLength(value) => {
1174 ensure_validator_type(table, field, validator, string_compatible)?;
1175 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1176 }
1177 Validator::Min(value) => {
1178 ensure_validator_type(table, field, validator, numeric_compatible)?;
1179 if !value.is_finite() {
1180 return Err(BaseError::ConfigError(format!(
1181 "表 {table} 的字段 {} 数值下限必须是有限数值",
1182 field.name
1183 )));
1184 }
1185 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1186 }
1187 Validator::Max(value) => {
1188 ensure_validator_type(table, field, validator, numeric_compatible)?;
1189 if !value.is_finite() {
1190 return Err(BaseError::ConfigError(format!(
1191 "表 {table} 的字段 {} 数值上限必须是有限数值",
1192 field.name
1193 )));
1194 }
1195 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1196 }
1197 Validator::Email
1198 | Validator::EmailLoose
1199 | Validator::Phone
1200 | Validator::PhoneLoose
1201 | Validator::Url => {
1202 ensure_validator_type(table, field, validator, string_compatible)?;
1203 }
1204 Validator::Regex(pattern) => {
1205 ensure_validator_type(table, field, validator, string_compatible)?;
1206 #[cfg(feature = "validator")]
1207 regex::Regex::new(pattern).map_err(|error| {
1208 BaseError::ConfigError(format!(
1209 "表 {table} 的字段 {} 正则表达式无效: {error}",
1210 field.name
1211 ))
1212 })?;
1213 #[cfg(not(feature = "validator"))]
1214 return Err(BaseError::ConfigError(format!(
1215 "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1216 field.name,
1217 )));
1218 }
1219 Validator::Custom(_) => {}
1220 }
1221 }
1222
1223 if let (Some(min), Some(max)) = (min_length, max_length) {
1224 if min > max {
1225 return Err(BaseError::ConfigError(format!(
1226 "表 {table} 的字段 {} 最小长度不能大于最大长度",
1227 field.name
1228 )));
1229 }
1230 }
1231 if let (
1232 FieldType::String {
1233 max_length: storage_max,
1234 },
1235 Some(min),
1236 ) = (&field.field_type, min_length)
1237 {
1238 if min > *storage_max {
1239 return Err(BaseError::ConfigError(format!(
1240 "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1241 field.name
1242 )));
1243 }
1244 }
1245 if let (Some(min), Some(max)) = (minimum, maximum) {
1246 if min > max {
1247 return Err(BaseError::ConfigError(format!(
1248 "表 {table} 的字段 {} 数值下限不能大于上限",
1249 field.name
1250 )));
1251 }
1252 }
1253 Ok(())
1254}
1255
1256fn ensure_validator_type(
1257 table: &str,
1258 field: &FieldConfig,
1259 validator: &Validator,
1260 compatible: bool,
1261) -> Result<(), BaseError> {
1262 if compatible {
1263 return Ok(());
1264 }
1265 Err(BaseError::ConfigError(format!(
1266 "表 {table} 的字段 {} 类型不能使用{}验证器",
1267 field.name,
1268 validator.display_name()
1269 )))
1270}
1271
1272fn validate_audience(
1273 table: &str,
1274 field: &str,
1275 operation: &str,
1276 audience: &Audience,
1277) -> Result<(), BaseError> {
1278 if let Audience::Roles(roles) = audience {
1279 if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1280 return Err(BaseError::ConfigError(format!(
1281 "表 {table} 的字段 {field} 的{operation}角色不能为空"
1282 )));
1283 }
1284 }
1285 Ok(())
1286}
1287
1288fn set_unique_role(
1289 table: &str,
1290 role: &str,
1291 enabled: bool,
1292 field: &str,
1293 target: &mut Option<String>,
1294) -> Result<(), BaseError> {
1295 if !enabled {
1296 return Ok(());
1297 }
1298 if let Some(existing) = target {
1299 return Err(BaseError::ConfigError(format!(
1300 "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1301 )));
1302 }
1303 *target = Some(field.to_string());
1304 Ok(())
1305}
1306
1307fn validate_index(
1308 table: &str,
1309 field_names: &HashSet<String>,
1310 index: &PendingIndex,
1311 index_names: &mut HashSet<String>,
1312) -> Result<(), BaseError> {
1313 if index.fields.is_empty() {
1314 return Err(BaseError::ConfigError(format!(
1315 "表 {table} 的索引字段不能为空"
1316 )));
1317 }
1318 let mut seen = HashSet::new();
1319 for field in &index.fields {
1320 if !field_names.contains(field) {
1321 return Err(BaseError::ConfigError(format!(
1322 "表 {table} 的索引字段不存在: {field}"
1323 )));
1324 }
1325 if !seen.insert(field) {
1326 return Err(BaseError::ConfigError(format!(
1327 "表 {table} 的索引重复引用字段: {field}"
1328 )));
1329 }
1330 }
1331 let prefix = if index.unique { "uk" } else { "idx" };
1332 let effective_name = index
1333 .name
1334 .clone()
1335 .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
1336 validate_identifier("索引", &effective_name)?;
1337 if !index_names.insert(effective_name.clone()) {
1338 return Err(BaseError::ConfigError(format!(
1339 "表 {table} 存在重复索引名: {effective_name}"
1340 )));
1341 }
1342 Ok(())
1343}
1344
1345fn field_json_schema(field: &FieldConfig) -> Value {
1346 let mut schema = Map::new();
1347 let mut min_length: Option<usize> = None;
1348 let mut max_length: Option<usize> = None;
1349 let mut minimum: Option<f64> = None;
1350 let mut maximum: Option<f64> = None;
1351 let mut patterns = Vec::new();
1352 let mut runtime_validators = Vec::new();
1353 match &field.field_type {
1354 FieldType::String {
1355 max_length: storage_max,
1356 } => {
1357 schema.insert("type".into(), json!("string"));
1358 max_length = Some(*storage_max);
1359 }
1360 FieldType::Text => {
1361 schema.insert("type".into(), json!("string"));
1362 }
1363 FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
1364 schema.insert("type".into(), json!("integer"));
1365 }
1366 FieldType::Float | FieldType::Double => {
1367 schema.insert("type".into(), json!("number"));
1368 }
1369 FieldType::Decimal { precision, scale } => {
1370 schema.insert("type".into(), json!("string"));
1371 schema.insert("format".into(), json!("decimal"));
1372 schema.insert("x-precision".into(), json!(precision));
1373 schema.insert("x-scale".into(), json!(scale));
1374 }
1375 FieldType::Boolean => {
1376 schema.insert("type".into(), json!("boolean"));
1377 }
1378 FieldType::Date => {
1379 schema.insert("type".into(), json!("string"));
1380 schema.insert("format".into(), json!("date"));
1381 }
1382 FieldType::DateTime => {
1383 schema.insert("type".into(), json!("string"));
1384 schema.insert("format".into(), json!("date-time"));
1385 }
1386 FieldType::Json => {
1387 schema.insert("type".into(), json!(["object", "array"]));
1388 }
1389 FieldType::Enum { values } => {
1390 schema.insert("type".into(), json!("string"));
1391 schema.insert("enum".into(), json!(values));
1392 }
1393 }
1394
1395 for validator in &field.validators {
1396 match validator {
1397 Validator::MinLength(value) => {
1398 min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1399 }
1400 Validator::MaxLength(value) => {
1401 max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1402 }
1403 Validator::Min(value) => {
1404 minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1405 }
1406 Validator::Max(value) => {
1407 maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1408 }
1409 Validator::Email => {
1410 #[cfg(feature = "validator")]
1411 patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
1412 #[cfg(not(feature = "validator"))]
1413 patterns.push("@".to_string());
1414 }
1415 Validator::EmailLoose => patterns.push("@".to_string()),
1416 Validator::Phone => {
1417 #[cfg(feature = "validator")]
1418 patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
1419 #[cfg(not(feature = "validator"))]
1420 patterns.push(r"^[0-9+\-]*$".to_string());
1421 }
1422 Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
1423 Validator::Url => patterns.push(r"^https?://".to_string()),
1424 Validator::Regex(pattern) => patterns.push(pattern.clone()),
1425 Validator::Custom(_) => runtime_validators.push("custom"),
1426 }
1427 }
1428
1429 if let Some(value) = min_length {
1430 schema.insert("minLength".into(), json!(value));
1431 }
1432 if let Some(value) = max_length {
1433 schema.insert("maxLength".into(), json!(value));
1434 }
1435 if let Some(value) = minimum {
1436 schema.insert("minimum".into(), json!(value));
1437 }
1438 if let Some(value) = maximum {
1439 schema.insert("maximum".into(), json!(value));
1440 }
1441 match patterns.as_slice() {
1442 [] => {}
1443 [pattern] => {
1444 schema.insert("pattern".into(), json!(pattern));
1445 }
1446 patterns => {
1447 schema.insert(
1448 "allOf".into(),
1449 Value::Array(
1450 patterns
1451 .iter()
1452 .map(|pattern| json!({ "pattern": pattern }))
1453 .collect(),
1454 ),
1455 );
1456 }
1457 }
1458 if !runtime_validators.is_empty() {
1459 schema.insert(
1460 "x-yang-runtime-validators".into(),
1461 json!(runtime_validators),
1462 );
1463 }
1464 if let Some(relation) = &field.relation {
1465 let relation_type = match relation.relation_type {
1466 RelationType::OneToOne => "one_to_one",
1467 RelationType::OneToMany => "one_to_many",
1468 RelationType::ManyToOne => "many_to_one",
1469 RelationType::ManyToMany => "many_to_many",
1470 };
1471 schema.insert(
1472 "x-yang-relation".into(),
1473 json!({
1474 "table": relation.table,
1475 "field": relation.field,
1476 "displayFields": relation.display_fields,
1477 "type": relation_type,
1478 }),
1479 );
1480 }
1481
1482 if !field.required {
1483 if let Some(field_types) = schema.get_mut("type") {
1484 match field_types {
1485 Value::String(field_type) => {
1486 *field_types = json!([field_type.clone(), "null"]);
1487 }
1488 Value::Array(types) if !types.iter().any(|value| value == "null") => {
1489 types.push(json!("null"));
1490 }
1491 _ => {}
1492 }
1493 }
1494 if let Some(Value::Array(values)) = schema.get_mut("enum") {
1495 values.push(Value::Null);
1496 }
1497 }
1498 if !field.display_name.is_empty() {
1499 schema.insert("title".into(), json!(field.display_name));
1500 }
1501 if let Some(default) = &field.default_value {
1502 schema.insert("default".into(), default.clone());
1503 }
1504 Value::Object(schema)
1505}