1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//! Schema validation and semantic analysis.
//!
//! This module validates parsed schemas for semantic correctness:
//! - All type references are valid
//! - Relations are properly defined
//! - Required attributes are present
//! - No duplicate definitions
use crate::ast::*;
use crate::error::{SchemaError, SchemaResult};
/// Schema validator for semantic analysis.
#[derive(Debug)]
pub struct Validator {
/// Collected validation errors.
errors: Vec<SchemaError>,
}
impl Default for Validator {
fn default() -> Self {
Self::new()
}
}
impl Validator {
/// Create a new validator.
pub fn new() -> Self {
Self { errors: vec![] }
}
/// Validate a schema and return the validated schema or errors.
pub fn validate(&mut self, mut schema: Schema) -> SchemaResult<Schema> {
self.errors.clear();
// Check for duplicate definitions
self.check_duplicates(&schema);
// Resolve field types (convert Model references to Enum or Composite where appropriate)
self.resolve_field_types(&mut schema);
// Validate each model
for model in schema.models.values() {
self.validate_model(model, &schema);
}
// Validate each enum
for e in schema.enums.values() {
self.validate_enum(e);
}
// Validate each composite type
for t in schema.types.values() {
self.validate_composite_type(t, &schema);
}
// Validate each view
for v in schema.views.values() {
self.validate_view(v, &schema);
}
// Validate each server group
for sg in schema.server_groups.values() {
self.validate_server_group(sg);
}
// Resolve relations
let relations = self.resolve_relations(&schema);
schema.relations = relations;
if self.errors.is_empty() {
Ok(schema)
} else {
Err(SchemaError::ValidationFailed {
count: self.errors.len(),
errors: std::mem::take(&mut self.errors),
})
}
}
/// Check for duplicate model, enum, or type names.
fn check_duplicates(&mut self, schema: &Schema) {
let mut seen = std::collections::HashSet::new();
for name in schema.models.keys() {
if !seen.insert(name.as_str()) {
self.errors
.push(SchemaError::duplicate("model", name.as_str()));
}
}
for name in schema.enums.keys() {
if !seen.insert(name.as_str()) {
self.errors
.push(SchemaError::duplicate("enum", name.as_str()));
}
}
for name in schema.types.keys() {
if !seen.insert(name.as_str()) {
self.errors
.push(SchemaError::duplicate("type", name.as_str()));
}
}
for name in schema.views.keys() {
if !seen.insert(name.as_str()) {
self.errors
.push(SchemaError::duplicate("view", name.as_str()));
}
}
// Check server group names (separately, since they don't conflict with types)
let mut server_group_names = std::collections::HashSet::new();
for name in schema.server_groups.keys() {
if !server_group_names.insert(name.as_str()) {
self.errors
.push(SchemaError::duplicate("serverGroup", name.as_str()));
}
}
}
/// Resolve field types to their correct types (Enum or Composite) instead of Model.
///
/// The parser initially treats all non-scalar type references as Model references.
/// This pass corrects them to Enum or Composite where appropriate.
fn resolve_field_types(&self, schema: &mut Schema) {
// Collect enum and composite type names into owned strings to avoid borrow conflicts
let enum_names: std::collections::HashSet<String> =
schema.enums.keys().map(|s| s.to_string()).collect();
let composite_names: std::collections::HashSet<String> =
schema.types.keys().map(|s| s.to_string()).collect();
// Update field types in models
for model in schema.models.values_mut() {
for field in model.fields.values_mut() {
if let FieldType::Model(ref type_name) = field.field_type {
let name = type_name.as_str();
if enum_names.contains(name) {
field.field_type = FieldType::Enum(type_name.clone());
} else if composite_names.contains(name) {
field.field_type = FieldType::Composite(type_name.clone());
}
}
}
}
// Also update field types in composite types
for composite in schema.types.values_mut() {
for field in composite.fields.values_mut() {
if let FieldType::Model(ref type_name) = field.field_type {
let name = type_name.as_str();
if enum_names.contains(name) {
field.field_type = FieldType::Enum(type_name.clone());
} else if composite_names.contains(name) {
field.field_type = FieldType::Composite(type_name.clone());
}
}
}
}
// Also update field types in views
for view in schema.views.values_mut() {
for field in view.fields.values_mut() {
if let FieldType::Model(ref type_name) = field.field_type {
let name = type_name.as_str();
if enum_names.contains(name) {
field.field_type = FieldType::Enum(type_name.clone());
} else if composite_names.contains(name) {
field.field_type = FieldType::Composite(type_name.clone());
}
}
}
}
}
/// Validate a model definition.
fn validate_model(&mut self, model: &Model, schema: &Schema) {
// Check for @id field
let id_fields: Vec<_> = model.fields.values().filter(|f| f.is_id()).collect();
if id_fields.is_empty() && !self.has_composite_id(model) {
self.errors.push(SchemaError::MissingId {
model: model.name().to_string(),
});
}
// Validate each field
for field in model.fields.values() {
self.validate_field(field, model.name(), schema);
}
// Validate model attributes
for attr in &model.attributes {
self.validate_model_attribute(attr, model);
}
}
/// Check if model has a composite ID (@@id attribute).
fn has_composite_id(&self, model: &Model) -> bool {
model.attributes.iter().any(|a| a.is("id"))
}
/// Validate a field definition.
fn validate_field(&mut self, field: &Field, model_name: &str, schema: &Schema) {
// Validate type references
match &field.field_type {
FieldType::Model(name) => {
// Check if it's actually a model, enum, or composite type
if schema.models.contains_key(name.as_str()) {
// Valid model reference
} else if schema.enums.contains_key(name.as_str()) {
// Parser initially treats non-scalar types as Model references
// This is actually an enum type - we'll handle this during resolution
} else if schema.types.contains_key(name.as_str()) {
// This is a composite type
} else {
self.errors.push(SchemaError::unknown_type(
model_name,
field.name(),
name.as_str(),
));
}
}
FieldType::Enum(name) => {
if !schema.enums.contains_key(name.as_str()) {
self.errors.push(SchemaError::unknown_type(
model_name,
field.name(),
name.as_str(),
));
}
}
FieldType::Composite(name) => {
if !schema.types.contains_key(name.as_str()) {
self.errors.push(SchemaError::unknown_type(
model_name,
field.name(),
name.as_str(),
));
}
}
_ => {}
}
// Validate field attributes
for attr in &field.attributes {
self.validate_field_attribute(attr, field, model_name, schema);
}
// Validate relation fields have @relation or are back-references
// Only check actual model relations (not enums or composite types parsed as Model)
if let FieldType::Model(ref target_name) = field.field_type {
// Skip validation for enum and composite type references
let is_actual_relation = schema.models.contains_key(target_name.as_str())
&& !schema.enums.contains_key(target_name.as_str())
&& !schema.types.contains_key(target_name.as_str());
if is_actual_relation && !field.is_list() {
// One-side of relation should have foreign key fields
let attrs = field.extract_attributes();
if attrs.relation.is_some() {
let rel = attrs.relation.as_ref().unwrap();
// Validate foreign key fields exist
for fk_field in &rel.fields {
if !schema
.models
.get(model_name)
.map(|m| m.fields.contains_key(fk_field.as_str()))
.unwrap_or(false)
{
self.errors.push(SchemaError::invalid_relation(
model_name,
field.name(),
format!("foreign key field '{}' does not exist", fk_field),
));
}
}
}
}
}
}
/// Validate a field attribute.
fn validate_field_attribute(
&mut self,
attr: &Attribute,
field: &Field,
model_name: &str,
schema: &Schema,
) {
match attr.name() {
"id" => {
// @id should be on a scalar or composite type, not a relation
if field.field_type.is_relation() {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "id".to_string(),
message: format!(
"@id cannot be applied to relation field '{}.{}'",
model_name,
field.name()
),
});
}
}
"auto" => {
// @auto should only be on Int or BigInt
if !matches!(
field.field_type,
FieldType::Scalar(ScalarType::Int) | FieldType::Scalar(ScalarType::BigInt)
) {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "auto".to_string(),
message: format!(
"@auto can only be applied to Int or BigInt fields, not '{}.{}'",
model_name,
field.name()
),
});
}
}
"default" => {
// Validate default value type matches field type
if let Some(value) = attr.first_arg() {
self.validate_default_value(value, field, model_name, schema);
}
}
"relation" => {
// Validate relation attribute - should only be on actual model references
let is_model_ref = matches!(&field.field_type, FieldType::Model(name)
if schema.models.contains_key(name.as_str()));
if !is_model_ref {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "relation".to_string(),
message: format!(
"@relation can only be applied to model reference fields, not '{}.{}'",
model_name,
field.name()
),
});
}
}
"updated_at" => {
// @updated_at should only be on DateTime
if !matches!(field.field_type, FieldType::Scalar(ScalarType::DateTime)) {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "updated_at".to_string(),
message: format!(
"@updated_at can only be applied to DateTime fields, not '{}.{}'",
model_name,
field.name()
),
});
}
}
_ => {}
}
}
/// Validate a default value matches the field type.
fn validate_default_value(
&mut self,
value: &AttributeValue,
field: &Field,
model_name: &str,
schema: &Schema,
) {
match (&field.field_type, value) {
// Functions are generally allowed (now(), uuid(), etc.)
(_, AttributeValue::Function(_, _)) => {}
// Int fields should have int defaults
(FieldType::Scalar(ScalarType::Int), AttributeValue::Int(_)) => {}
(FieldType::Scalar(ScalarType::BigInt), AttributeValue::Int(_)) => {}
// Float fields can have int or float defaults
(FieldType::Scalar(ScalarType::Float), AttributeValue::Int(_)) => {}
(FieldType::Scalar(ScalarType::Float), AttributeValue::Float(_)) => {}
(FieldType::Scalar(ScalarType::Decimal), AttributeValue::Int(_)) => {}
(FieldType::Scalar(ScalarType::Decimal), AttributeValue::Float(_)) => {}
// String fields should have string defaults
(FieldType::Scalar(ScalarType::String), AttributeValue::String(_)) => {}
// Boolean fields should have boolean defaults
(FieldType::Scalar(ScalarType::Boolean), AttributeValue::Boolean(_)) => {}
// Enum fields should have ident defaults matching a variant
(FieldType::Enum(enum_name), AttributeValue::Ident(variant)) => {
if let Some(e) = schema.enums.get(enum_name.as_str()) {
if e.get_variant(variant).is_none() {
self.errors.push(SchemaError::invalid_field(
model_name,
field.name(),
format!(
"default value '{}' is not a valid variant of enum '{}'",
variant, enum_name
),
));
}
}
}
// Model type might actually be an enum (parser treats non-scalar as Model initially)
(FieldType::Model(type_name), AttributeValue::Ident(variant)) => {
// Check if this is actually an enum reference
if let Some(e) = schema.enums.get(type_name.as_str()) {
if e.get_variant(variant).is_none() {
self.errors.push(SchemaError::invalid_field(
model_name,
field.name(),
format!(
"default value '{}' is not a valid variant of enum '{}'",
variant, type_name
),
));
}
}
// If it's a real model reference with an ident default, that's an error
// but we skip that here since it's likely a valid enum
}
// Type mismatch
_ => {
self.errors.push(SchemaError::invalid_field(
model_name,
field.name(),
format!(
"default value type does not match field type '{}'",
field.field_type
),
));
}
}
}
/// Validate a model-level attribute.
fn validate_model_attribute(&mut self, attr: &Attribute, model: &Model) {
match attr.name() {
"index" | "unique" => {
// Validate referenced fields exist
if let Some(AttributeValue::FieldRefList(fields)) = attr.first_arg() {
for field_name in fields {
if !model.fields.contains_key(field_name.as_str()) {
self.errors.push(SchemaError::invalid_model(
model.name(),
format!(
"@@{} references non-existent field '{}'",
attr.name(),
field_name
),
));
}
}
}
}
"id" => {
// Composite primary key
if let Some(AttributeValue::FieldRefList(fields)) = attr.first_arg() {
for field_name in fields {
if !model.fields.contains_key(field_name.as_str()) {
self.errors.push(SchemaError::invalid_model(
model.name(),
format!("@@id references non-existent field '{}'", field_name),
));
}
}
}
}
"search" => {
// Full-text search on fields
if let Some(AttributeValue::FieldRefList(fields)) = attr.first_arg() {
for field_name in fields {
if let Some(field) = model.fields.get(field_name.as_str()) {
// Only string fields can be searched
if !matches!(field.field_type, FieldType::Scalar(ScalarType::String)) {
self.errors.push(SchemaError::invalid_model(
model.name(),
format!(
"@@search field '{}' must be of type String",
field_name
),
));
}
} else {
self.errors.push(SchemaError::invalid_model(
model.name(),
format!("@@search references non-existent field '{}'", field_name),
));
}
}
}
}
_ => {}
}
}
/// Validate an enum definition.
fn validate_enum(&mut self, e: &Enum) {
if e.variants.is_empty() {
self.errors.push(SchemaError::invalid_model(
e.name(),
"enum must have at least one variant".to_string(),
));
}
// Check for duplicate variant names
let mut seen = std::collections::HashSet::new();
for variant in &e.variants {
if !seen.insert(variant.name()) {
self.errors.push(SchemaError::duplicate(
format!("enum variant in {}", e.name()),
variant.name(),
));
}
}
}
/// Validate a composite type definition.
fn validate_composite_type(&mut self, t: &CompositeType, schema: &Schema) {
if t.fields.is_empty() {
self.errors.push(SchemaError::invalid_model(
t.name(),
"composite type must have at least one field".to_string(),
));
}
// Validate field types
for field in t.fields.values() {
match &field.field_type {
FieldType::Model(_) => {
self.errors.push(SchemaError::invalid_field(
t.name(),
field.name(),
"composite types cannot have model relations".to_string(),
));
}
FieldType::Enum(name) => {
if !schema.enums.contains_key(name.as_str()) {
self.errors.push(SchemaError::unknown_type(
t.name(),
field.name(),
name.as_str(),
));
}
}
FieldType::Composite(name) => {
if !schema.types.contains_key(name.as_str()) {
self.errors.push(SchemaError::unknown_type(
t.name(),
field.name(),
name.as_str(),
));
}
}
_ => {}
}
}
}
/// Validate a view definition.
fn validate_view(&mut self, v: &View, schema: &Schema) {
// Views should have at least one field
if v.fields.is_empty() {
self.errors.push(SchemaError::invalid_model(
v.name(),
"view must have at least one field".to_string(),
));
}
// Validate field types
for field in v.fields.values() {
self.validate_field(field, v.name(), schema);
}
}
/// Validate a server group definition.
fn validate_server_group(&mut self, sg: &ServerGroup) {
// Server groups should have at least one server
if sg.servers.is_empty() {
self.errors.push(SchemaError::invalid_model(
sg.name.name.as_str(),
"serverGroup must have at least one server".to_string(),
));
}
// Check for duplicate server names within the group
let mut seen_servers = std::collections::HashSet::new();
for server_name in sg.servers.keys() {
if !seen_servers.insert(server_name.as_str()) {
self.errors.push(SchemaError::duplicate(
format!("server in serverGroup {}", sg.name.name),
server_name.as_str(),
));
}
}
// Validate each server
for server in sg.servers.values() {
self.validate_server(server, sg.name.name.as_str());
}
// Validate server group attributes
for attr in &sg.attributes {
self.validate_server_group_attribute(attr, sg);
}
// Check for at least one primary server in read replica strategy
if let Some(strategy) = sg.strategy() {
if strategy == ServerGroupStrategy::ReadReplica {
let has_primary = sg
.servers
.values()
.any(|s| s.role() == Some(ServerRole::Primary));
if !has_primary {
self.errors.push(SchemaError::invalid_model(
sg.name.name.as_str(),
"ReadReplica strategy requires at least one server with role = \"primary\""
.to_string(),
));
}
}
}
}
/// Validate an individual server definition.
fn validate_server(&mut self, server: &Server, group_name: &str) {
// Server should have a URL property
if server.url().is_none() {
self.errors.push(SchemaError::invalid_model(
group_name,
format!("server '{}' must have a 'url' property", server.name.name),
));
}
// Validate weight is positive if specified
if let Some(weight) = server.weight() {
if weight == 0 {
self.errors.push(SchemaError::invalid_model(
group_name,
format!(
"server '{}' weight must be greater than 0",
server.name.name
),
));
}
}
// Validate priority is positive if specified
if let Some(priority) = server.priority() {
if priority == 0 {
self.errors.push(SchemaError::invalid_model(
group_name,
format!(
"server '{}' priority must be greater than 0",
server.name.name
),
));
}
}
}
/// Validate a server group attribute.
fn validate_server_group_attribute(&mut self, attr: &Attribute, sg: &ServerGroup) {
match attr.name() {
"strategy" => {
// Validate strategy value
if let Some(arg) = attr.first_arg() {
let value_str = arg
.as_string()
.map(|s| s.to_string())
.or_else(|| arg.as_ident().map(|s| s.to_string()));
if let Some(val) = value_str {
if ServerGroupStrategy::parse(&val).is_none() {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "strategy".to_string(),
message: format!(
"invalid strategy '{}' for serverGroup '{}'. Valid values: ReadReplica, Sharding, MultiRegion, HighAvailability, Custom",
val,
sg.name.name
),
});
}
}
}
}
"loadBalance" => {
// Validate load balance value
if let Some(arg) = attr.first_arg() {
let value_str = arg
.as_string()
.map(|s| s.to_string())
.or_else(|| arg.as_ident().map(|s| s.to_string()));
if let Some(val) = value_str {
if LoadBalanceStrategy::parse(&val).is_none() {
self.errors.push(SchemaError::InvalidAttribute {
attribute: "loadBalance".to_string(),
message: format!(
"invalid loadBalance '{}' for serverGroup '{}'. Valid values: RoundRobin, Random, LeastConnections, Weighted, Nearest, Sticky",
val,
sg.name.name
),
});
}
}
}
}
_ => {} // Other attributes are allowed
}
}
/// Resolve all relations in the schema.
fn resolve_relations(&mut self, schema: &Schema) -> Vec<Relation> {
let mut relations = Vec::new();
for model in schema.models.values() {
for field in model.fields.values() {
if let FieldType::Model(ref target_model) = field.field_type {
// Skip if this is actually an enum reference (parser treats non-scalar as Model initially)
if schema.enums.contains_key(target_model.as_str()) {
continue;
}
// Skip if this is actually a composite type reference
if schema.types.contains_key(target_model.as_str()) {
continue;
}
// Skip if the target model doesn't exist (error was already reported)
if !schema.models.contains_key(target_model.as_str()) {
continue;
}
let attrs = field.extract_attributes();
let relation_type = if field.is_list() {
// This model has many of target
RelationType::OneToMany
} else {
// This model has one of target
RelationType::ManyToOne
};
let mut relation = Relation::new(
model.name(),
field.name(),
target_model.as_str(),
relation_type,
);
if let Some(rel_attr) = &attrs.relation {
if let Some(name) = &rel_attr.name {
relation = relation.with_name(name.as_str());
}
if !rel_attr.fields.is_empty() {
relation = relation.with_from_fields(rel_attr.fields.clone());
}
if !rel_attr.references.is_empty() {
relation = relation.with_to_fields(rel_attr.references.clone());
}
if let Some(action) = rel_attr.on_delete {
relation = relation.with_on_delete(action);
}
if let Some(action) = rel_attr.on_update {
relation = relation.with_on_update(action);
}
if let Some(map) = &rel_attr.map {
relation = relation.with_map(map.as_str());
}
}
relations.push(relation);
}
}
}
relations
}
}
/// Validate a schema string and return the validated schema.
pub fn validate_schema(input: &str) -> SchemaResult<Schema> {
let schema = crate::parser::parse_schema(input)?;
let mut validator = Validator::new();
validator.validate(schema)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_simple_model() {
let schema = validate_schema(
r#"
model User {
id Int @id @auto
email String @unique
}
"#,
)
.unwrap();
assert_eq!(schema.models.len(), 1);
}
#[test]
fn test_validate_model_missing_id() {
let result = validate_schema(
r#"
model User {
email String
name String
}
"#,
);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, SchemaError::ValidationFailed { .. }));
}
#[test]
fn test_validate_model_with_composite_id() {
let schema = validate_schema(
r#"
model PostTag {
post_id Int
tag_id Int
@@id([post_id, tag_id])
}
"#,
)
.unwrap();
assert_eq!(schema.models.len(), 1);
}
#[test]
fn test_validate_unknown_type_reference() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
profile UnknownType
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_enum_reference() {
let schema = validate_schema(
r#"
enum Role {
User
Admin
}
model User {
id Int @id @auto
role Role @default(User)
}
"#,
)
.unwrap();
assert_eq!(schema.models.len(), 1);
assert_eq!(schema.enums.len(), 1);
}
#[test]
fn test_validate_invalid_enum_default() {
let result = validate_schema(
r#"
enum Role {
User
Admin
}
model User {
id Int @id @auto
role Role @default(Unknown)
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_auto_on_non_int() {
let result = validate_schema(
r#"
model User {
id String @id @auto
email String
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_updated_at_on_non_datetime() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
updated_at String @updated_at
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_empty_enum() {
let result = validate_schema(
r#"
enum Empty {
}
model User {
id Int @id @auto
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_duplicate_model_names() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
model User {
id Int @id @auto
}
"#,
);
// Note: This might parse as a single model due to grammar
// The duplicate check happens at validation time
assert!(result.is_ok() || result.is_err());
}
#[test]
fn test_validate_relation() {
let schema = validate_schema(
r#"
model User {
id Int @id @auto
posts Post[]
}
model Post {
id Int @id @auto
author_id Int
author User @relation(fields: [author_id], references: [id])
}
"#,
)
.unwrap();
assert_eq!(schema.models.len(), 2);
assert!(!schema.relations.is_empty());
}
#[test]
fn test_validate_index_with_invalid_field() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
email String
@@index([nonexistent])
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_search_on_non_string_field() {
let result = validate_schema(
r#"
model Post {
id Int @id @auto
views Int
@@search([views])
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_composite_type() {
let schema = validate_schema(
r#"
type Address {
street String
city String
country String @default("US")
}
model User {
id Int @id @auto
address Address
}
"#,
);
// Note: Composite type support depends on parser handling
assert!(schema.is_ok() || schema.is_err());
}
// ==================== Server Group Validation Tests ====================
#[test]
fn test_validate_server_group_basic() {
let schema = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup MainCluster {
server primary {
url = "postgres://localhost/db"
role = "primary"
}
}
"#,
)
.unwrap();
assert_eq!(schema.server_groups.len(), 1);
}
#[test]
fn test_validate_server_group_empty_servers() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup EmptyCluster {
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_server_group_missing_url() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
server db {
role = "primary"
}
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_server_group_invalid_strategy() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
@@strategy(InvalidStrategy)
server db {
url = "postgres://localhost/db"
}
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_server_group_valid_strategy() {
let schema = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
@@strategy(ReadReplica)
@@loadBalance(RoundRobin)
server primary {
url = "postgres://localhost/db"
role = "primary"
}
}
"#,
)
.unwrap();
assert_eq!(schema.server_groups.len(), 1);
}
#[test]
fn test_validate_server_group_read_replica_needs_primary() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
@@strategy(ReadReplica)
server replica1 {
url = "postgres://localhost/db"
role = "replica"
}
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_server_group_with_replicas() {
let schema = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
@@strategy(ReadReplica)
server primary {
url = "postgres://primary/db"
role = "primary"
weight = 1
}
server replica1 {
url = "postgres://replica1/db"
role = "replica"
weight = 2
}
server replica2 {
url = "postgres://replica2/db"
role = "replica"
weight = 2
region = "us-west-1"
}
}
"#,
)
.unwrap();
let cluster = schema.get_server_group("Cluster").unwrap();
assert_eq!(cluster.servers.len(), 3);
}
#[test]
fn test_validate_server_group_zero_weight() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
server db {
url = "postgres://localhost/db"
weight = 0
}
}
"#,
);
assert!(result.is_err());
}
#[test]
fn test_validate_server_group_invalid_load_balance() {
let result = validate_schema(
r#"
model User {
id Int @id @auto
}
serverGroup Cluster {
@@loadBalance(InvalidStrategy)
server db {
url = "postgres://localhost/db"
}
}
"#,
);
assert!(result.is_err());
}
}