forked from hasura/graphql-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolved.rs
2109 lines (1984 loc) · 81.3 KB
/
resolved.rs
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
use std::collections::{BTreeMap, HashMap, HashSet};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use open_dds::{
data_source::{self, DataConnectorUrl, DataSourceName},
data_specification::{
self, ArgumentName, CommandGraphQlDefinition, CommandName, FieldAccess, FieldName,
FunctionOrProcedure, GraphQlFieldName, GraphQlRootFieldKind, GraphQlTypeName, InbuiltType,
ModelName, OperatorName, RelationshipName, Role, Type, TypeName, TypeOutputPermission,
},
};
use ndc_client as ndc;
use super::ndc_validation;
#[derive(Error, Debug)]
pub enum Error {
#[error("the following data source is defined more than once: {name:}")]
DuplicateDataSourceDefinition { name: DataSourceName },
#[error("no data connector available for this data source: {data_source:}")]
DataConnectorUnavailable { data_source: DataSourceName },
#[error("the following type is defined more than once: {name:}")]
DuplicateTypeDefinition { name: TypeName },
#[error("the following field in type {type_name:} is defined more than once: {field_name:}")]
DuplicateFieldDefinition {
type_name: TypeName,
field_name: FieldName,
},
#[error("the following model is defined more than once: {name:}")]
DuplicateModelDefinition { name: ModelName },
#[error("the data type {data_type:} for model {model_name:} has not been defined")]
UnknownModelDataType {
model_name: ModelName,
data_type: TypeName,
},
#[error(
"the following argument in model {model_name:} is defined more than once: {argument_name:}"
)]
DuplicateModelArgumentDefinition {
model_name: ModelName,
argument_name: ArgumentName,
},
#[error("unknown model used in model source definition: {model_name:}")]
UnknownModelInModelSource { model_name: ModelName },
#[error("source for the following model is defined more than once: {model_name:}")]
DuplicateModelSourceDefinition { model_name: ModelName },
#[error("the type {type_name:} referenced in type mappings for model {model_name:} has not been defined")]
UnknownModelSourceType {
model_name: ModelName,
type_name: TypeName,
},
#[error("{error:} in model {model_name:}")]
ModelTypeMappingValidationError {
model_name: ModelName,
error: TypeMappingValidationError,
},
// ------- Errors for commands ---------
#[error("the following command is defined more than once: {name:}")]
DuplicateCommandDefinition { name: CommandName },
#[error("the following argument {argument_name:} with argument type {argument_type:} in command {command_name:} has not been defined")]
UnknownCommandArgumentType {
command_name: CommandName,
argument_name: ArgumentName,
argument_type: Type,
},
#[error(
"the following argument in command {command_name:} is defined more than once: {argument_name:}"
)]
DuplicateCommandArgumentDefinition {
command_name: CommandName,
argument_name: ArgumentName,
},
#[error("unknown command used in command source definition: {command_name:}")]
UnknownCommandInCommandSource { command_name: CommandName },
#[error("source for the following command is defined more than once: {command_name:}")]
DuplicateCommandSourceDefinition { command_name: CommandName },
#[error("the data source {data_source:} for command {command_name:} has not been defined")]
UnknownCommandDataSource {
command_name: CommandName,
data_source: DataSourceName,
},
#[error(
"the mapping for type {type_name:} in command {command_name:} is defined more than once"
)]
DuplicateTypeMappingDefinitionInCommandSource {
command_name: CommandName,
type_name: TypeName,
},
#[error(
"unknown argument {argument_name:} referenced in argument mappings for command {command_name:}"
)]
UnknownCommandSourceArgument {
command_name: CommandName,
argument_name: ArgumentName,
},
#[error(
"the mapping for argument {argument_name:} of command {command_name:} has been defined more than once"
)]
DuplicateCommandArgumentMapping {
command_name: CommandName,
argument_name: ArgumentName,
},
#[error("the procedure {procedure:} in the data source {data_source:} for command {command_name:} has not been defined")]
UnknownCommandProcedure {
command_name: CommandName,
data_source: DataSourceName,
procedure: String,
},
#[error("the function {function:} in the data source {data_source:} for command {command_name:} has not been defined")]
UnknownCommandFunction {
command_name: CommandName,
data_source: DataSourceName,
function: String,
},
#[error("{error:} in command {command_name:}")]
CommandTypeMappingValidationError {
command_name: CommandName,
error: TypeMappingValidationError,
},
#[error("mismatch between command source and root field type for command {command_name:}")]
CommandSourceAndRootFieldTypeMismatch { command_name: CommandName },
// ----------------
#[error("the mapping for type {type_name:} in model {model_name:} is incompatible with the type representation")]
IncompatiableTypeMappingDefinition {
model_name: ModelName,
type_name: TypeName,
},
#[error("the mapping for type {type_name:} in model {model_name:} is defined more than once")]
DuplicateTypeMappingDefinition {
model_name: ModelName,
type_name: TypeName,
},
#[error("the data source {data_source:} for model {model_name:} has not been defined")]
UnknownModelDataSource {
model_name: ModelName,
data_source: DataSourceName,
},
#[error("the collection {collection:} in the data source {data_source:} for model {model_name:} has not been defined")]
UnknownModelCollection {
model_name: ModelName,
data_source: DataSourceName,
collection: String,
},
#[error(
"unknown field {field_name:} in field mappings of type {type_name:} in model {model_name:}"
)]
UnknownFieldInFieldMapping {
model_name: ModelName,
type_name: TypeName,
field_name: FieldName,
},
#[error(
"the mapping for field {field_name:} of type {type_name:} in model {model_name:} has been defined more than once"
)]
DuplicateFieldMapping {
model_name: ModelName,
type_name: TypeName,
field_name: FieldName,
},
#[error(
"unknown argument {argument_name:} referenced in argument mappings for model {model_name:}"
)]
UnknownModelSourceArgument {
model_name: ModelName,
argument_name: ArgumentName,
},
#[error(
"the mapping for argument {argument_name:} of model {model_name:} has been defined more than once"
)]
DuplicateModelArgumentMapping {
model_name: ModelName,
argument_name: ArgumentName,
},
#[error("model arguments graphql input configuartion has been specified for model {model_name:} that does not have arguments")]
UnnecessaryModelArgumentsGraphQlInputConfiguration { model_name: ModelName },
#[error("a graphql type has been defined for an unknown type: {type_name:}")]
UnknownGraphQlType { type_name: TypeName },
#[error("multiple graphql types have been defined for type: {type_name:}")]
DuplicateGraphQlType { type_name: TypeName },
#[error("multiple graphql types found with the same name: {graphql_type_name:}")]
ConflictingGraphQlType { graphql_type_name: GraphQlTypeName },
#[error("unknown model used in graphql definition: {model_name:}")]
UnknownModelInGraphQlDefinition { model_name: ModelName },
#[error("unknown command used in graphql definition: {command_name:}")]
UnknownCommandInGraphQlDefinition { command_name: CommandName },
#[error("unknown field {field_name:} in unique identifier defined for model {model_name:}")]
UnknownFieldInUniqueIdentifier {
model_name: ModelName,
field_name: FieldName,
},
#[error("duplicate field {field_name:} in unique identifier defined for model {model_name:}")]
DuplicateFieldInUniqueIdentifier {
model_name: ModelName,
field_name: FieldName,
},
#[error("invalid type represented for model {model_name:}: {type_representation:}")]
InvalidTypeRepresentation {
model_name: ModelName,
type_representation: TypeRepresentation,
},
// Permission errors
#[error("unsupported type in output type permissions definition: {type_name:}; only object types are supported")]
UnsupportedTypeInOutputPermissions { type_name: TypeName },
#[error("multiple output type permissions have been defined for type: {type_name:}")]
DuplicateOutputTypePermissions { type_name: TypeName },
#[error("unknown type used in output permissions: {type_name:}")]
UnknownTypeInOutputPermissionsDefinition { type_name: TypeName },
#[error("unknown field '{field_name:}' used in output permissions of type '{type_name:}'")]
UnknownFieldInOutputPermissionsDefinition {
field_name: FieldName,
type_name: TypeName,
},
#[error("unknown model used in model select permissions definition: {model_name:}")]
UnknownModelInModelSelectPermissions { model_name: ModelName },
#[error("multiple select permissions defined for model: {model_name:}")]
DuplicateModelSelectPermission { model_name: ModelName },
#[error(
"model source is required for model '{model_name:}' to resolve select permission predicate"
)]
ModelSourceRequiredForPredicate { model_name: ModelName },
#[error("unknown field '{field_name:}' used in select permissions of model '{model_name:}'")]
UnknownFieldInSelectPermissionsDefinition {
field_name: FieldName,
model_name: ModelName,
},
#[error("field mapping is missing for field '{field_name:}' used in select permissions of model '{model_name:}'")]
MissingMappingForSelectPermissionPredicateField {
field_name: FieldName,
model_name: ModelName,
},
#[error("field '{field_name:}' used in select permissions of model '{model_name:}' should be mapped to non-array scalar field")]
UnsupportedFieldInSelectPermissionsPredicate {
field_name: FieldName,
model_name: ModelName,
},
#[error(
"Invalid operator used in model '{model_name:}' select permission: '{operator_name:}'"
)]
InvalidOperator {
model_name: ModelName,
operator_name: OperatorName,
},
#[error("unknown command used in command permissions definition: {command_name:}")]
UnknownCommandInCommandPermissions { command_name: CommandName },
#[error("multiple permissions defined for command: {command_name:}")]
DuplicateCommandPermission { command_name: CommandName },
#[error("{message:}")]
UnsupportedFeature { message: String },
#[error("the referenced secret {secret_name:} was not found in the environment")]
SecretNotFound { secret_name: String },
#[error("{0}")]
DeserializationError(#[from] serde_json::Error),
#[error("NDC validation error: {0}")]
NDCValidationError(#[from] super::ndc_validation::NDCValidationError),
#[error(
"duplicate relationship {relationship_name:} associated with source type {type_name:}"
)]
DuplicateRelationshipInSourceType {
type_name: TypeName,
relationship_name: RelationshipName,
},
#[error("unknown model {model_name:} used in relationship {relationship_name:} definition at {unknown_model_source:}")]
UnknownModelUsedInRelationship {
relationship_name: RelationshipName,
model_name: ModelName,
unknown_model_source: String,
},
#[error("Source type {type_name:} referenced in the definition of relationship(s) {relationship_name:} is not defined ")]
RelationshipDefinedOnUnknownType {
relationship_name: RelationshipName,
type_name: TypeName,
},
#[error("{reason:}")]
NotSupported { reason: String },
#[error("The field path provided in the {location:} of the relationship {relationship_name} is empty")]
EmptyFieldPath {
location: String,
relationship_name: RelationshipName,
},
#[error("unknown data source {data_source:} referenced in scalar type representation of {scalar_type:}")]
ScalarTypeFromUnknownDataSource {
data_source: DataSourceName,
scalar_type: String,
},
#[error("cannot find scalar type {scalar_type:} in data source {data_source:}")]
UnknownScalarTypeInDataSource {
data_source: DataSourceName,
scalar_type: String,
},
#[error("unknown type represented for scalar type {scalar_type:}: {type_name:}")]
ScalarTypeUnknownRepresentation {
scalar_type: String,
type_name: TypeName,
},
#[error("multiple type representations defined for scalar {scalar_type:} from data source {data_source:}")]
DuplicateDataConnectorScalarRepresentation {
data_source: DataSourceName,
scalar_type: String,
},
#[error("multiple scalar type graphql expression defined for scalar {scalar_type:} from data source {data_source:}")]
DuplicateScalarGraphQlExpression {
data_source: DataSourceName,
scalar_type: String,
},
#[error(
"scalar type representation required for type {scalar_type:} in data source {data_source:}"
)]
DataConnectorScalarRepresentationRequired {
data_source: DataSourceName,
scalar_type: String,
},
#[error("type mapping required for type {type_name:} in model source {model_name:} backed by data source {data_source:}")]
TypeMappingRequired {
model_name: ModelName,
type_name: TypeName,
data_source: DataSourceName,
},
#[error("Unknown field {field_name:} in global_id defined for the type {type_name:}")]
UnknownFieldInGlobalId {
field_name: FieldName,
type_name: TypeName,
},
#[error("Model {model_name:} is marked as a global ID source but there are no global id fields present in the related object type {type_name:} ")]
NoGlobalFieldsPresentInGlobalIdSource {
type_name: TypeName,
model_name: ModelName,
},
#[error("A field named `id` cannot be present in the object type {type_name} when global_id fields are non-empty.")]
IdFieldConflictingGlobalId { type_name: TypeName },
#[error("Found multiple models {model_1:}, {model_2:} that implement the same object type {object_type:} to be global ID sources.")]
DuplicateModelGlobalIdSource {
model_1: ModelName,
model_2: ModelName,
object_type: TypeName,
},
}
#[derive(Error, Debug)]
pub enum TypeMappingValidationError {
#[error("the type {type_name:} referenced in type mappings has not been defined")]
UnknownSourceType { type_name: TypeName },
#[error("the mapping for type {type_name:} is incompatible with the type representation")]
IncompatiableTypeMappingDefinition { type_name: TypeName },
#[error("unknown field {field_name:} in field mappings of type {type_name:}")]
UnknownSourceField {
type_name: TypeName,
field_name: FieldName,
},
#[error("unknown target column name {column_name:} for field {field_name:} ")]
UnknownTargetColumn {
column_name: String,
field_name: FieldName,
},
#[error(
"the mapping for field {field_name:} of type {type_name:} has been defined more than once"
)]
DuplicateFieldMapping {
type_name: TypeName,
field_name: FieldName,
},
}
/// Resolved and validated metadata for a project. Used internally in the v3 server.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Metadata {
pub types: HashMap<TypeName, TypeRepresentation>,
pub models: IndexMap<ModelName, Model>,
pub commands: IndexMap<CommandName, Command>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, derive_more::Display)]
pub enum TypeRepresentation {
#[display(fmt = "Display")]
Object {
fields: IndexMap<FieldName, FieldDefinition>,
relationships: IndexMap<FieldName, Relationship>,
type_permissions: HashMap<Role, TypeOutputPermission>,
global_id_fields: Vec<FieldName>,
graphql_output_type_name: Option<GraphQlTypeName>,
// TODO: add graphql_output_type_kind if we support creating interfaces.
// TODO: add graphql_input_type_name if we support complex input types.
},
#[display(fmt = "ScalarType")]
ScalarType {
graphql_type_name: Option<GraphQlTypeName>,
},
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct FieldDefinition {
pub field_type: Type,
}
pub struct ScalarTypeInfo {
pub scalar_type: ndc::models::ScalarType,
pub representation: Option<Type>,
pub comparison_expression_name: Option<GraphQlTypeName>,
}
impl ScalarTypeInfo {
fn new(source_scalar: ndc::models::ScalarType) -> Self {
ScalarTypeInfo {
scalar_type: source_scalar,
representation: None,
comparison_expression_name: None,
}
}
}
struct DataSourceContext<'a> {
data_source: &'a data_source::DataSource,
scalars: HashMap<String, ScalarTypeInfo>,
}
impl<'a> DataSourceContext<'a> {
fn new(data_source: &'a data_source::DataSource) -> Self {
DataSourceContext {
data_source,
scalars: data_source
.schema
.scalar_types
.clone()
.into_iter()
.map(|(k, v)| (k, ScalarTypeInfo::new(v)))
.collect(),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct DataSource {
pub name: DataSourceName,
pub data_connector_url: DataConnectorUrl,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ModelArgumentsGraphQlInput {
pub field: GraphQlFieldName,
pub graphql_type: GraphQlTypeName,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct ModelGraphQlApi {
pub arguments_input: Option<ModelArgumentsGraphQlInput>,
pub select_uniques: Vec<SelectUniqueGraphQlDefinition>,
pub select_many: Option<SelectManyGraphQlDefinition>,
pub filter_expression: Option<ModelFilterExpression>,
pub order_by_expression: Option<ModelOrderByExpression>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Model {
pub name: ModelName,
pub data_type: TypeName,
pub type_representation: TypeRepresentation,
pub arguments: IndexMap<ArgumentName, Type>,
pub graphql_api: ModelGraphQlApi,
pub source: Option<ModelSource>,
pub select_permissions: Option<HashMap<Role, SelectPermission>>,
pub global_id_source: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ModelSource {
pub data_source: DataSource,
pub collection: String,
pub type_mappings: HashMap<TypeName, TypeMapping>,
pub argument_mappings: HashMap<ArgumentName, String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum TypeMapping {
Object {
field_mappings: HashMap<FieldName, FieldMapping>,
},
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct FieldMapping {
pub column: String,
pub column_type: Option<ndc::models::Type>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct SelectUniqueGraphQlDefinition {
pub query_root_field: GraphQlFieldName,
pub unique_identifier: IndexMap<FieldName, Type>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ComparisonExpressionInfo {
pub data_source_name: DataSourceName,
pub scalar_type_name: String,
pub type_name: GraphQlTypeName,
pub ndc_column: String,
pub operators: BTreeMap<String, Type>,
}
// TODO: add support for aggregates
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct OrderByExpressionInfo {
pub ndc_column: String,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ModelFilterExpression {
pub where_type_name: GraphQlTypeName,
pub scalar_fields: HashMap<FieldName, ComparisonExpressionInfo>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ModelOrderByExpression {
pub data_source_name: DataSourceName,
pub order_by_type_name: GraphQlTypeName,
pub order_by_fields: HashMap<FieldName, OrderByExpressionInfo>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct SelectManyGraphQlDefinition {
pub query_root_field: GraphQlFieldName,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum RelationshipTarget {
Model {
model: Model,
relationship_type: data_specification::RelationshipType,
},
// TODO: Add support for relationships with Commands.
// Command {
// command: data_specification::CommandName,
// },
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct FieldPath {
/// The path to the `tail`
pub head: Vec<FieldAccess>,
/// The last element in the `FieldPath`
pub tail: FieldAccess,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum RelationshipMappingSource {
Value(data_specification::ValueExpression),
FieldPath(FieldPath),
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum RelationshipMappingTarget {
Argument(data_specification::ArgumentName),
ModelField(FieldPath),
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct RelationshipMapping {
pub source: RelationshipMappingSource,
pub target: RelationshipMappingTarget,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Relationship {
pub name: RelationshipName,
pub source: TypeName,
pub target: RelationshipTarget,
pub target_typename: TypeName,
pub mappings: Vec<RelationshipMapping>,
pub relationship_type: data_specification::RelationshipType,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct CommandGraphQlApi {
pub root_field_kind: GraphQlRootFieldKind,
pub root_field_name: GraphQlFieldName,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Command {
pub name: CommandName,
pub output_type: Type,
pub arguments: IndexMap<ArgumentName, Type>,
pub graphql_api: Option<CommandGraphQlDefinition>,
pub source: Option<CommandSource>,
pub permissions: Option<HashMap<Role, CommandPermission>>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct CommandSource {
pub data_source: DataSource,
pub source: FunctionOrProcedure,
pub type_mappings: HashMap<TypeName, TypeMapping>,
pub argument_mappings: HashMap<ArgumentName, String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct CommandPermission {
pub allow_execution: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct SelectPermission {
// Missing filter implies all rows are selectable
pub filter: Option<ModelPredicate>,
// pub allow_aggregations: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum ModelPredicate {
UnaryFieldComparison {
field: FieldName,
ndc_column: String,
operator: ndc_client::models::UnaryComparisonOperator,
},
BinaryFieldComparison {
field: FieldName,
ndc_column: String,
operator: ndc_client::models::BinaryComparisonOperator,
argument_type: Type,
value: data_specification::ValueExpression,
},
// TODO: Remote relationships are disallowed for now
Relationship {
name: RelationshipName,
predicate: Option<Box<ModelPredicate>>,
},
And(Vec<ModelPredicate>),
Or(Vec<ModelPredicate>),
Not(Box<ModelPredicate>),
}
/*******************
Functions to validate and convert Open DDS spec to internal metadata
*******************/
pub fn resolve_metadata(metadata: &open_dds::Metadata) -> Result<Metadata, Error> {
let metadata_accessor = open_dds::accessor::MetadataAccessor::new(metadata);
let mut data_sources = HashMap::new();
for data_source in &metadata_accessor.data_sources {
if data_sources
.insert(
data_source.name.clone(),
DataSourceContext::new(data_source),
)
.is_some()
{
return Err(Error::DuplicateDataSourceDefinition {
name: data_source.name.clone(),
});
}
}
let mut types: HashMap<TypeName, TypeRepresentation> = HashMap::new();
let mut existing_graphql_types: HashSet<GraphQlTypeName> = HashSet::new();
for object_type_definition in &metadata_accessor.object_types {
if types
.insert(
object_type_definition.name.clone(),
resolve_object_type(object_type_definition, &mut existing_graphql_types)?,
)
.is_some()
{
return Err(Error::DuplicateTypeDefinition {
name: object_type_definition.name.clone(),
});
}
}
for scalar_type in &metadata_accessor.scalar_types {
if types
.insert(
scalar_type.name.clone(),
TypeRepresentation::ScalarType {
graphql_type_name: scalar_type.graphql.as_ref().map(|c| c.type_name.clone()),
},
)
.is_some()
{
return Err(Error::DuplicateTypeDefinition {
name: scalar_type.name.clone(),
});
}
check_conflicting_graphql_types(
&mut existing_graphql_types,
scalar_type.graphql.as_ref().map(|c| &c.type_name),
)?;
}
for output_type_permission in &metadata_accessor.output_permissions {
match types.get_mut(&output_type_permission.type_name) {
None => {
return Err(Error::UnknownTypeInOutputPermissionsDefinition {
type_name: output_type_permission.type_name.clone(),
})
}
Some(object_type) => {
resolve_output_type_permission(object_type, output_type_permission)?;
}
}
}
for scalar_type_representation in &metadata_accessor.data_connector_scalar_representations {
let scalar_type_name: &String = &scalar_type_representation.scalar_type;
let source_context = data_sources
.get_mut(&scalar_type_representation.data_source)
.ok_or_else(|| Error::ScalarTypeFromUnknownDataSource {
scalar_type: scalar_type_name.clone(),
data_source: scalar_type_representation.data_source.clone(),
})?;
let scalar_type = source_context
.scalars
.get_mut(&scalar_type_representation.scalar_type)
.ok_or_else(|| Error::UnknownScalarTypeInDataSource {
scalar_type: scalar_type_name.clone(),
data_source: scalar_type_representation.data_source.clone(),
})?;
if scalar_type.representation.is_none() {
match &scalar_type_representation.representation {
Type::Inbuilt(_) => {} // TODO: Validate Nullable and Array types in Inbuilt
Type::Custom(type_name) => {
let _representation = types.get(type_name).ok_or_else(|| {
Error::ScalarTypeUnknownRepresentation {
scalar_type: scalar_type_name.clone(),
type_name: type_name.clone(),
}
})?;
}
}
scalar_type.representation = Some(scalar_type_representation.representation.clone());
} else {
return Err(Error::DuplicateDataConnectorScalarRepresentation {
data_source: scalar_type_representation.data_source.clone(),
scalar_type: scalar_type_name.clone(),
});
}
scalar_type.comparison_expression_name = scalar_type_representation
.graphql
.as_ref()
.and_then(|c| c.comparison_expression_type_name.clone());
check_conflicting_graphql_types(
&mut existing_graphql_types,
scalar_type.comparison_expression_name.as_ref(),
)?;
}
// TODO: validate types
let mut models = IndexMap::new();
let mut global_id_models = HashMap::new();
for model in &metadata_accessor.models {
let mut resolved_model = resolve_model(model, &types)?;
if resolved_model.global_id_source {
match global_id_models.insert(model.data_type.clone(), model.name.clone()) {
None => {}
Some(duplicate_model_name) => {
return Err(Error::DuplicateModelGlobalIdSource {
model_1: resolved_model.name,
model_2: duplicate_model_name,
object_type: resolved_model.data_type,
})
}
}
}
if let Some(model_source) = &model.source {
resolve_model_source(model_source, &mut resolved_model, &data_sources, &types)?;
}
if let Some(model_graphql_definition) = &model.graphql {
resolve_model_graphql_api(
model_graphql_definition,
&mut resolved_model,
&mut existing_graphql_types,
&data_sources,
)?;
}
if models.insert(model.name.clone(), resolved_model).is_some() {
return Err(Error::DuplicateModelDefinition {
name: model.name.clone(),
});
}
}
for relationship in &metadata_accessor.relationships {
let resolved_relationship = resolve_relationship(relationship, &models)?;
let source_type = types.get_mut(&relationship.source).ok_or_else(|| {
Error::RelationshipDefinedOnUnknownType {
relationship_name: relationship.name.clone(),
type_name: relationship.source.to_owned(),
}
})?;
let relationship_field_name = FieldName(relationship.name.0.clone());
match source_type {
TypeRepresentation::Object {
ref mut relationships,
..
} => {
if relationships
.insert(relationship_field_name, resolved_relationship)
.is_some()
{
return Err(Error::DuplicateRelationshipInSourceType {
type_name: relationship.source.clone(),
relationship_name: relationship.name.clone(),
});
}
}
TypeRepresentation::ScalarType { .. } => {
return Err(Error::NotSupported {
reason: "A relationship can only be defined on an OBJECT type.".to_string(),
})
}
}
}
// resolve all the command without their sources
let mut commands = IndexMap::new();
for command in &metadata_accessor.commands {
let mut resolved_command = resolve_command(command, &types)?;
if let Some(command_source) = &command.source {
resolve_command_source(command_source, &mut resolved_command, &data_sources, &types)?;
}
if commands
.insert(command.name.clone(), resolved_command)
.is_some()
{
return Err(Error::DuplicateCommandDefinition {
name: command.name.clone(),
});
}
}
for command_permissions in &metadata_accessor.command_permissions {
let command_name = &command_permissions.command_name;
let command = commands.get_mut(command_name).ok_or_else(|| {
Error::UnknownCommandInCommandPermissions {
command_name: command_name.clone(),
}
})?;
if command.permissions.is_none() {
command.permissions = Some(resolve_command_permissions(command_permissions)?);
} else {
return Err(Error::DuplicateCommandPermission {
command_name: command_name.clone(),
});
}
}
for select_permissions in &metadata_accessor.select_permissions {
let model_name = &select_permissions.model_name;
let model = models.get_mut(model_name).ok_or_else(|| {
Error::UnknownModelInModelSelectPermissions {
model_name: model_name.clone(),
}
})?;
if model.select_permissions.is_none() {
model.select_permissions = Some(resolve_model_select_permissions(
model,
select_permissions,
&data_sources,
)?);
} else {
return Err(Error::DuplicateModelSelectPermission {
model_name: model_name.clone(),
});
}
}
Ok(Metadata {
types,
models,
commands,
})
}
fn check_conflicting_graphql_types(
existing_graphql_types: &mut HashSet<GraphQlTypeName>,
new_graphql_type: Option<&GraphQlTypeName>,
) -> Result<(), Error> {
if let Some(new_graphql_type) = new_graphql_type {
// Fail on conflicting graphql type names
if !(existing_graphql_types.insert(new_graphql_type.clone())) {
return Err(Error::ConflictingGraphQlType {
graphql_type_name: new_graphql_type.clone(),
});
}
}
Ok(())
}
fn resolve_object_type(
object_type_definition: &data_specification::ObjectDefinition,
existing_graphql_types: &mut HashSet<GraphQlTypeName>,
) -> Result<TypeRepresentation, Error> {
let mut resolved_fields = IndexMap::new();
let mut resolved_global_id_fields = Vec::new();
for field in &object_type_definition.fields {
if resolved_fields
.insert(field.name.clone(), resolve_field(field)?)
.is_some()
{
return Err(Error::DuplicateFieldDefinition {
type_name: object_type_definition.name.clone(),
field_name: field.name.clone(),
});
}
}
match &object_type_definition.global_id {
Some(global_id_fields) => {
// Throw error if the object type has a field called id" and has global fields configured.
// Because, when the global id fields are configured, the `id` field will be auto-generated.
if !global_id_fields.is_empty() && resolved_fields.contains_key(&FieldName("id".into()))
{
return Err(Error::IdFieldConflictingGlobalId {
type_name: object_type_definition.name.clone(),
});
};
for global_id_field in global_id_fields {
if !resolved_fields.contains_key(global_id_field) {
return Err(Error::UnknownFieldInGlobalId {
field_name: global_id_field.clone(),
type_name: object_type_definition.name.clone(),
});
} else {
resolved_global_id_fields.push(global_id_field.clone())
}
}
}
None => {}
}
check_conflicting_graphql_types(
existing_graphql_types,
object_type_definition
.graphql
.as_ref()
.and_then(|c| c.type_name.as_ref()),
)?;
Ok(TypeRepresentation::Object {
fields: resolved_fields,
relationships: IndexMap::new(),
global_id_fields: resolved_global_id_fields,
type_permissions: HashMap::new(),
graphql_output_type_name: object_type_definition
.graphql
.as_ref()
.and_then(|c| c.type_name.clone()),
})
}
fn resolve_field(
field: &open_dds::data_specification::FieldDefinition,
) -> Result<FieldDefinition, Error> {
Ok(FieldDefinition {
field_type: field.field_type.clone(),
})
}
fn resolve_model(
model: &open_dds::data_specification::Model,
types: &HashMap<TypeName, TypeRepresentation>,
) -> Result<Model, Error> {
let model_type_representation =
types
.get(&model.data_type)
.ok_or_else(|| Error::UnknownModelDataType {
model_name: model.name.clone(),
data_type: model.data_type.clone(),
})?;
let mut global_id_source = false;
if model.global_id_source {
if let TypeRepresentation::Object {
global_id_fields, ..
} = model_type_representation
{
// Check if there are any global fields present in the related
// object type, if the model is marked as a global source.
if global_id_fields.is_empty() {
return Err(Error::NoGlobalFieldsPresentInGlobalIdSource {
type_name: model.data_type.clone(),
model_name: model.name.clone(),
});
} else {
global_id_source = true;
};
}
};
let mut arguments = IndexMap::new();
for argument in &model.arguments {
if arguments
.insert(argument.name.clone(), argument.argument_type.clone())