-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
gqlschema.go
2400 lines (2098 loc) · 65.6 KB
/
gqlschema.go
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
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package schema
import (
"fmt"
"sort"
"strings"
"github.com/dgraph-io/dgraph/x"
"github.com/dgraph-io/gqlparser/v2/ast"
"github.com/dgraph-io/gqlparser/v2/gqlerror"
"github.com/dgraph-io/gqlparser/v2/parser"
)
const (
inverseDirective = "hasInverse"
inverseArg = "field"
searchDirective = "search"
searchArgs = "by"
dgraphDirective = "dgraph"
dgraphTypeArg = "type"
dgraphPredArg = "pred"
idDirective = "id"
subscriptionDirective = "withSubscription"
secretDirective = "secret"
authDirective = "auth"
customDirective = "custom"
remoteDirective = "remote" // types with this directive are not stored in Dgraph.
lambdaDirective = "lambda"
generateDirective = "generate"
generateQueryArg = "query"
generateGetField = "get"
generateQueryField = "query"
generatePasswordField = "password"
generateAggregateField = "aggregate"
generateMutationArg = "mutation"
generateAddField = "add"
generateUpdateField = "update"
generateDeleteField = "delete"
generateSubscriptionArg = "subscription"
cascadeDirective = "cascade"
cascadeArg = "fields"
cacheControlDirective = "cacheControl"
CacheControlHeader = "Cache-Control"
// custom directive args and fields
dqlArg = "dql"
httpArg = "http"
httpUrl = "url"
httpMethod = "method"
httpBody = "body"
httpGraphql = "graphql"
mode = "mode"
BATCH = "BATCH"
SINGLE = "SINGLE"
// geo type names and fields
Point = "Point"
Polygon = "Polygon"
MultiPolygon = "MultiPolygon"
Latitude = "latitude"
Longitude = "longitude"
Points = "points"
Coordinates = "coordinates"
Polygons = "polygons"
deprecatedDirective = "deprecated"
NumUid = "numUids"
Msg = "msg"
Typename = "__typename"
// schemaExtras is everything that gets added to an input schema to make it
// GraphQL valid and for the completion algorithm to use to build in search
// capability into the schema.
schemaExtras = `
"""
The Int64 scalar type represents a signed 64‐bit numeric non‐fractional value.
Int64 can represent values in range [-(2^63),(2^63 - 1)].
"""
scalar Int64
"""
The DateTime scalar type represents date and time as a string in RFC3339 format.
For example: "1985-04-12T23:20:50.52Z" represents 20 minutes and 50.52 seconds after the 23rd hour of April 12th, 1985 in UTC.
"""
scalar DateTime
input IntRange{
min: Int!
max: Int!
}
input FloatRange{
min: Float!
max: Float!
}
input Int64Range{
min: Int64!
max: Int64!
}
input DateTimeRange{
min: DateTime!
max: DateTime!
}
input StringRange{
min: String!
max: String!
}
enum DgraphIndex {
int
int64
float
bool
hash
exact
term
fulltext
trigram
regexp
year
month
day
hour
geo
}
input AuthRule {
and: [AuthRule]
or: [AuthRule]
not: AuthRule
rule: String
}
enum HTTPMethod {
GET
POST
PUT
PATCH
DELETE
}
enum Mode {
BATCH
SINGLE
}
input CustomHTTP {
url: String!
method: HTTPMethod!
body: String
graphql: String
mode: Mode
forwardHeaders: [String!]
secretHeaders: [String!]
introspectionHeaders: [String!]
skipIntrospection: Boolean
}
type Point {
longitude: Float!
latitude: Float!
}
input PointRef {
longitude: Float!
latitude: Float!
}
input NearFilter {
distance: Float!
coordinate: PointRef!
}
input PointGeoFilter {
near: NearFilter
within: WithinFilter
}
type PointList {
points: [Point!]!
}
input PointListRef {
points: [PointRef!]!
}
type Polygon {
coordinates: [PointList!]!
}
input PolygonRef {
coordinates: [PointListRef!]!
}
type MultiPolygon {
polygons: [Polygon!]!
}
input MultiPolygonRef {
polygons: [PolygonRef!]!
}
input WithinFilter {
polygon: PolygonRef!
}
input ContainsFilter {
point: PointRef
polygon: PolygonRef
}
input IntersectsFilter {
polygon: PolygonRef
multiPolygon: MultiPolygonRef
}
input PolygonGeoFilter {
near: NearFilter
within: WithinFilter
contains: ContainsFilter
intersects: IntersectsFilter
}
input GenerateQueryParams {
get: Boolean
query: Boolean
password: Boolean
aggregate: Boolean
}
input GenerateMutationParams {
add: Boolean
update: Boolean
delete: Boolean
}
directive @hasInverse(field: String!) on FIELD_DEFINITION
directive @search(by: [DgraphIndex!]) on FIELD_DEFINITION
directive @dgraph(type: String, pred: String) on OBJECT | INTERFACE | FIELD_DEFINITION
directive @id on FIELD_DEFINITION
directive @withSubscription on OBJECT | INTERFACE
directive @secret(field: String!, pred: String) on OBJECT | INTERFACE
directive @auth(
password: AuthRule
query: AuthRule,
add: AuthRule,
update: AuthRule,
delete: AuthRule) on OBJECT | INTERFACE
directive @custom(http: CustomHTTP, dql: String) on FIELD_DEFINITION
directive @remote on OBJECT | INTERFACE | UNION | INPUT_OBJECT | ENUM
directive @cascade(fields: [String]) on FIELD
directive @lambda on FIELD_DEFINITION
directive @cacheControl(maxAge: Int!) on QUERY
directive @generate(
query: GenerateQueryParams,
mutation: GenerateMutationParams,
subscription: Boolean) on OBJECT | INTERFACE
input IntFilter {
eq: Int
le: Int
lt: Int
ge: Int
gt: Int
between: IntRange
}
input Int64Filter {
eq: Int64
le: Int64
lt: Int64
ge: Int64
gt: Int64
between: Int64Range
}
input FloatFilter {
eq: Float
le: Float
lt: Float
ge: Float
gt: Float
between: FloatRange
}
input DateTimeFilter {
eq: DateTime
le: DateTime
lt: DateTime
ge: DateTime
gt: DateTime
between: DateTimeRange
}
input StringTermFilter {
allofterms: String
anyofterms: String
}
input StringRegExpFilter {
regexp: String
}
input StringFullTextFilter {
alloftext: String
anyoftext: String
}
input StringExactFilter {
eq: String
in: [String]
le: String
lt: String
ge: String
gt: String
between: StringRange
}
input StringHashFilter {
eq: String
in: [String]
}
`
)
// Filters for Boolean and enum aren't needed in here schemaExtras because they are
// generated directly for the bool field / enum. E.g. if
// `type T { b: Boolean @search }`,
// then the filter allows `filter: {b: true}`. That's better than having
// `input BooleanFilter { eq: Boolean }`, which would require writing
// `filter: {b: {eq: true}}`.
//
// It'd be nice to be able to just write `filter: isPublished` for say a Post
// with a Boolean isPublished field, but there's no way to get that in GraphQL
// because input union types aren't yet sorted out in GraphQL. So it's gotta
// be `filter: {isPublished: true}`
type directiveValidator func(
sch *ast.Schema,
typ *ast.Definition,
field *ast.FieldDefinition,
dir *ast.Directive,
secrets map[string]x.SensitiveByteSlice) gqlerror.List
type searchTypeIndex struct {
gqlType string
dgIndex string
}
var numUids = &ast.FieldDefinition{
Name: NumUid,
Type: &ast.Type{NamedType: "Int"},
}
// search arg -> supported GraphQL type
// == supported Dgraph index -> GraphQL type it applies to
var supportedSearches = map[string]searchTypeIndex{
"int": {"Int", "int"},
"int64": {"Int64", "int"},
"float": {"Float", "float"},
"bool": {"Boolean", "bool"},
"hash": {"String", "hash"},
"exact": {"String", "exact"},
"term": {"String", "term"},
"fulltext": {"String", "fulltext"},
"trigram": {"String", "trigram"},
"regexp": {"String", "trigram"},
"year": {"DateTime", "year"},
"month": {"DateTime", "month"},
"day": {"DateTime", "day"},
"hour": {"DateTime", "hour"},
"point": {"Point", "geo"},
"polygon": {"Polygon", "geo"},
"multiPolygon": {"MultiPolygon", "geo"},
}
// GraphQL scalar/object type -> default search arg
// used if the schema specifies @search without an arg
var defaultSearches = map[string]string{
"Boolean": "bool",
"Int": "int",
"Int64": "int64",
"Float": "float",
"String": "term",
"DateTime": "year",
"Point": "point",
"Polygon": "polygon",
"MultiPolygon": "multiPolygon",
}
// graphqlSpecScalars holds all the scalar types supported by the graphql spec.
var graphqlSpecScalars = map[string]bool{
"Int": true,
"Float": true,
"String": true,
"Boolean": true,
"ID": true,
}
// Dgraph index filters that have contains intersecting filter
// directive.
var filtersCollisions = map[string][]string{
"StringHashFilter": {"StringExactFilter"},
"StringExactFilter": {"StringHashFilter"},
}
// GraphQL types that can be used for ordering in orderasc and orderdesc.
var orderable = map[string]bool{
"Int": true,
"Int64": true,
"Float": true,
"String": true,
"DateTime": true,
}
// GraphQL types that can be summed. Types that have a well defined addition function.
var summable = map[string]bool{
"Int": true,
"Int64": true,
"Float": true,
}
var enumDirectives = map[string]bool{
"trigram": true,
"hash": true,
"exact": true,
"regexp": true,
}
// index name -> GraphQL input filter for that index
var builtInFilters = map[string]string{
"bool": "Boolean",
"int": "IntFilter",
"int64": "Int64Filter",
"float": "FloatFilter",
"year": "DateTimeFilter",
"month": "DateTimeFilter",
"day": "DateTimeFilter",
"hour": "DateTimeFilter",
"term": "StringTermFilter",
"trigram": "StringRegExpFilter",
"regexp": "StringRegExpFilter",
"fulltext": "StringFullTextFilter",
"exact": "StringExactFilter",
"hash": "StringHashFilter",
"point": "PointGeoFilter",
"polygon": "PolygonGeoFilter",
"multiPolygon": "PolygonGeoFilter",
}
// GraphQL in-built type -> Dgraph scalar
var inbuiltTypeToDgraph = map[string]string{
"ID": "uid",
"Boolean": "bool",
"Int": "int",
"Int64": "int",
"Float": "float",
"String": "string",
"DateTime": "dateTime",
"Password": "password",
"Point": "geo",
"Polygon": "geo",
"MultiPolygon": "geo",
}
func ValidatorNoOp(
sch *ast.Schema,
typ *ast.Definition,
field *ast.FieldDefinition,
dir *ast.Directive,
secrets map[string]x.SensitiveByteSlice) gqlerror.List {
return nil
}
var directiveValidators = map[string]directiveValidator{
inverseDirective: hasInverseValidation,
searchDirective: searchValidation,
dgraphDirective: dgraphDirectiveValidation,
idDirective: idValidation,
subscriptionDirective: ValidatorNoOp,
secretDirective: passwordValidation,
authDirective: ValidatorNoOp, // Just to get it printed into generated schema
customDirective: customDirectiveValidation,
remoteDirective: ValidatorNoOp,
deprecatedDirective: ValidatorNoOp,
lambdaDirective: lambdaDirectiveValidation,
generateDirective: ValidatorNoOp,
}
// directiveLocationMap stores the directives and their locations for the ones which can be
// applied at type level in the user supplied schema. It is used during validation.
var directiveLocationMap = map[string]map[ast.DefinitionKind]bool{
inverseDirective: nil,
searchDirective: nil,
dgraphDirective: {ast.Object: true, ast.Interface: true},
idDirective: nil,
subscriptionDirective: {ast.Object: true, ast.Interface: true},
secretDirective: {ast.Object: true, ast.Interface: true},
authDirective: {ast.Object: true, ast.Interface: true},
customDirective: nil,
remoteDirective: {ast.Object: true, ast.Interface: true, ast.Union: true,
ast.InputObject: true, ast.Enum: true},
cascadeDirective: nil,
generateDirective: {ast.Object: true, ast.Interface: true},
}
// Struct to store parameters of @generate directive
type GenerateDirectiveParams struct {
generateGetQuery bool
generateFilterQuery bool
generatePasswordQuery bool
generateAggregateQuery bool
generateAddMutation bool
generateUpdateMutation bool
generateDeleteMutation bool
generateSubscription bool
}
func parseGenerateDirectiveParams(defn *ast.Definition) *GenerateDirectiveParams {
ret := &GenerateDirectiveParams{
generateGetQuery: true,
generateFilterQuery: true,
generatePasswordQuery: true,
generateAggregateQuery: true,
generateAddMutation: true,
generateUpdateMutation: true,
generateDeleteMutation: true,
generateSubscription: false,
}
if dir := defn.Directives.ForName(generateDirective); dir != nil {
if queryArg := dir.Arguments.ForName(generateQueryArg); queryArg != nil {
if getField := queryArg.Value.Children.ForName(generateGetField); getField != nil {
if getFieldVal, err := getField.Value(nil); err == nil {
ret.generateGetQuery = getFieldVal.(bool)
}
}
if queryField := queryArg.Value.Children.ForName(generateQueryField); queryField != nil {
if queryFieldVal, err := queryField.Value(nil); err == nil {
ret.generateFilterQuery = queryFieldVal.(bool)
}
}
if passwordField := queryArg.Value.Children.ForName(generatePasswordField); passwordField != nil {
if passwordFieldVal, err := passwordField.Value(nil); err == nil {
ret.generatePasswordQuery = passwordFieldVal.(bool)
}
}
if aggregateField := queryArg.Value.Children.ForName(generateAggregateField); aggregateField != nil {
if aggregateFieldVal, err := aggregateField.Value(nil); err == nil {
ret.generateAggregateQuery = aggregateFieldVal.(bool)
}
}
}
if mutationArg := dir.Arguments.ForName(generateMutationArg); mutationArg != nil {
if addField := mutationArg.Value.Children.ForName(generateAddField); addField != nil {
if addFieldVal, err := addField.Value(nil); err == nil {
ret.generateAddMutation = addFieldVal.(bool)
}
}
if updateField := mutationArg.Value.Children.ForName(generateUpdateField); updateField != nil {
if updateFieldVal, err := updateField.Value(nil); err == nil {
ret.generateUpdateMutation = updateFieldVal.(bool)
}
}
if deleteField := mutationArg.Value.Children.ForName(generateDeleteField); deleteField != nil {
if deleteFieldVal, err := deleteField.Value(nil); err == nil {
ret.generateDeleteMutation = deleteFieldVal.(bool)
}
}
}
if subscriptionArg := dir.Arguments.ForName(generateSubscriptionArg); subscriptionArg != nil {
if subscriptionVal, err := subscriptionArg.Value.Value(nil); err == nil {
ret.generateSubscription = subscriptionVal.(bool)
}
}
}
return ret
}
var schemaDocValidations []func(schema *ast.SchemaDocument) gqlerror.List
var schemaValidations []func(schema *ast.Schema, definitions []string) gqlerror.List
var defnValidations, typeValidations []func(schema *ast.Schema, defn *ast.Definition) gqlerror.List
var fieldValidations []func(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List
func copyAstFieldDef(src *ast.FieldDefinition) *ast.FieldDefinition {
var dirs ast.DirectiveList
dirs = append(dirs, src.Directives...)
// We add arguments for filters and order statements later.
dst := &ast.FieldDefinition{
Name: src.Name,
DefaultValue: src.DefaultValue,
Type: src.Type,
Directives: dirs,
Arguments: src.Arguments,
Position: src.Position,
}
return dst
}
// expandSchema adds schemaExtras to the doc and adds any fields inherited from interfaces into
// implementing types
func expandSchema(doc *ast.SchemaDocument) *gqlerror.Error {
docExtras, gqlErr := parser.ParseSchema(&ast.Source{Input: schemaExtras})
if gqlErr != nil {
x.Panic(gqlErr)
}
// Cache the interface definitions in a map. They could also be defined after types which
// implement them.
interfaces := make(map[string]*ast.Definition)
for _, defn := range doc.Definitions {
if defn.Kind == ast.Interface {
interfaces[defn.Name] = defn
}
}
// Walk through type definitions which implement an interface and fill in the fields from the
// interface.
for _, defn := range doc.Definitions {
if defn.Kind == ast.Object && len(defn.Interfaces) > 0 {
fieldSeen := make(map[string]string)
// fieldSeen a map from field name to interface name in which the field was seen.
defFields := make(map[string]int64)
// defFields is used to keep track of fields in the defn before any inherited fields are added to it.
for _, d := range defn.Fields {
defFields[d.Name]++
}
initialDefFields := defn.Fields
// initialDefFields store initial field definitions of the type.
for _, implements := range defn.Interfaces {
i, ok := interfaces[implements]
if !ok {
// This would fail schema validation later.
continue
}
fields := make([]*ast.FieldDefinition, 0, len(i.Fields))
for _, field := range i.Fields {
// If field name is repeated multiple times in type then it will result in validation error later.
if defFields[field.Name] == 1 {
if field.Type.String() != initialDefFields.ForName(field.Name).Type.String() {
return gqlerror.ErrorPosf(defn.Position, "For type %s to implement interface"+
" %s the field %s must have type %s", defn.Name, i.Name, field.Name, field.Type.String())
}
if fieldSeen[field.Name] == "" {
// Overwrite the existing field definition in type with the field definition of interface
*defn.Fields.ForName(field.Name) = *field
} else if field.Type.NamedType != IDType {
// If field definition is already written,just add interface definition in type
// It will later results in validation error because of repeated fields
fields = append(fields, copyAstFieldDef(field))
}
} else if field.Type.NamedType == IDType && fieldSeen[field.Name] != "" {
// If ID type is already seen in any other interface then we don't copy it again
// And validator won't throw error for id types later
if field.Type.String() != defn.Fields.ForName(field.Name).Type.String() {
return gqlerror.ErrorPosf(defn.Position, "field %s is of type %s in interface %s"+
" and is of type %s in interface %s",
field.Name, field.Type.String(), i.Name, defn.Fields.ForName(field.Name).Type.String(), fieldSeen[field.Name])
}
} else {
// Creating a copy here is important, otherwise arguments like filter, order
// etc. are added multiple times if the pointer is shared.
fields = append(fields, copyAstFieldDef(field))
}
fieldSeen[field.Name] = i.Name
}
defn.Fields = append(fields, defn.Fields...)
passwordDirective := i.Directives.ForName("secret")
if passwordDirective != nil {
defn.Directives = append(defn.Directives, passwordDirective)
}
}
}
}
doc.Definitions = append(doc.Definitions, docExtras.Definitions...)
doc.Directives = append(doc.Directives, docExtras.Directives...)
return nil
}
// preGQLValidation validates schema before GraphQL validation. Validation
// before GraphQL validation means the schema only has allowed structures, and
// means we can give better errors than GrqphQL validation would give if their
// schema contains something that will fail because of the extras we inject into
// the schema.
func preGQLValidation(schema *ast.SchemaDocument) gqlerror.List {
var errs []*gqlerror.Error
for _, defn := range schema.Definitions {
if defn.BuiltIn {
// prelude definitions are built in and we don't want to validate them.
continue
}
errs = append(errs, applyDefnValidations(defn, nil, defnValidations)...)
}
errs = append(errs, applySchemaDocValidations(schema)...)
return errs
}
// postGQLValidation validates schema after gql validation. Some validations
// are easier to run once we know that the schema is GraphQL valid and that validation
// has fleshed out the schema structure; we just need to check if it also satisfies
// the extra rules.
func postGQLValidation(schema *ast.Schema, definitions []string,
secrets map[string]x.SensitiveByteSlice) gqlerror.List {
var errs []*gqlerror.Error
for _, defn := range definitions {
typ := schema.Types[defn]
errs = append(errs, applyDefnValidations(typ, schema, typeValidations)...)
for _, field := range typ.Fields {
errs = append(errs, applyFieldValidations(typ, field)...)
for _, dir := range field.Directives {
if directiveValidators[dir.Name] == nil {
continue
}
errs = append(errs, directiveValidators[dir.Name](schema, typ, field, dir, secrets)...)
}
}
}
errs = append(errs, applySchemaValidations(schema, definitions)...)
return errs
}
func applySchemaDocValidations(schema *ast.SchemaDocument) gqlerror.List {
var errs []*gqlerror.Error
for _, rule := range schemaDocValidations {
newErrs := rule(schema)
for _, err := range newErrs {
errs = appendIfNotNull(errs, err)
}
}
return errs
}
func applySchemaValidations(schema *ast.Schema, definitions []string) gqlerror.List {
var errs []*gqlerror.Error
for _, rule := range schemaValidations {
newErrs := rule(schema, definitions)
for _, err := range newErrs {
errs = appendIfNotNull(errs, err)
}
}
return errs
}
func applyDefnValidations(defn *ast.Definition, schema *ast.Schema,
rules []func(schema *ast.Schema, defn *ast.Definition) gqlerror.List) gqlerror.List {
var errs []*gqlerror.Error
for _, rule := range rules {
errs = append(errs, rule(schema, defn)...)
}
return errs
}
func applyFieldValidations(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
var errs []*gqlerror.Error
for _, rule := range fieldValidations {
errs = append(errs, rule(typ, field)...)
}
return errs
}
// completeSchema generates all the required types and fields for
// query/mutation/update for all the types mentioned in the schema.
func completeSchema(sch *ast.Schema, definitions []string) {
query := sch.Types["Query"]
if query != nil {
query.Kind = ast.Object
sch.Query = query
} else {
sch.Query = &ast.Definition{
Kind: ast.Object,
Name: "Query",
Fields: make([]*ast.FieldDefinition, 0),
}
}
mutation := sch.Types["Mutation"]
if mutation != nil {
mutation.Kind = ast.Object
sch.Mutation = mutation
} else {
sch.Mutation = &ast.Definition{
Kind: ast.Object,
Name: "Mutation",
Fields: make([]*ast.FieldDefinition, 0),
}
}
sch.Subscription = &ast.Definition{
Kind: ast.Object,
Name: "Subscription",
Fields: make([]*ast.FieldDefinition, 0),
}
for _, key := range definitions {
if isQueryOrMutation(key) {
continue
}
defn := sch.Types[key]
if defn.Kind == ast.Union {
// TODO: properly check the case of reverse predicates (~) with union members and clean
// them from unionRef or unionFilter as required.
addUnionReferenceType(sch, defn)
addUnionFilterType(sch, defn)
addUnionMemberTypeEnum(sch, defn)
continue
}
if defn.Kind != ast.Interface && defn.Kind != ast.Object {
continue
}
params := parseGenerateDirectiveParams(defn)
// Common types to both Interface and Object.
addReferenceType(sch, defn)
if params.generateUpdateMutation {
addPatchType(sch, defn)
addUpdateType(sch, defn)
addUpdatePayloadType(sch, defn)
}
if params.generateDeleteMutation {
addDeletePayloadType(sch, defn)
}
switch defn.Kind {
case ast.Interface:
// addInputType doesn't make sense as interface is like an abstract class and we can't
// create objects of its type.
if params.generateUpdateMutation {
addUpdateMutation(sch, defn)
}
if params.generateDeleteMutation {
addDeleteMutation(sch, defn)
}
case ast.Object:
// types and inputs needed for mutations
if params.generateAddMutation {
addInputType(sch, defn)
addAddPayloadType(sch, defn)
}
addMutations(sch, defn, params)
}
// types and inputs needed for query and search
addFilterType(sch, defn)
addTypeOrderable(sch, defn)
addFieldFilters(sch, defn)
addAggregationResultType(sch, defn)
addQueries(sch, defn, params)
addTypeHasFilter(sch, defn)
// We need to call this at last as aggregateFields
// should not be part of HasFilter or UpdatePayloadType etc.
addAggregateFields(sch, defn)
}
}
func cleanupInput(sch *ast.Schema, def *ast.Definition, seen map[string]bool) {
// seen helps us avoid cycles
if def == nil || seen[def.Name] {
return
}
i := 0
// recursively walk over fields for an input type and delete those which are themselves empty.
for _, f := range def.Fields {
nt := f.Type.Name()
enum := sch.Types[nt] != nil && sch.Types[nt].Kind == "ENUM"
// Lets skip scalar types and enums.
if _, ok := inbuiltTypeToDgraph[nt]; ok || enum {
def.Fields[i] = f
i++
continue
}
seen[def.Name] = true
cleanupInput(sch, sch.Types[nt], seen)
// If after calling cleanup on an input type, it got deleted then it doesn't need to be
// in the fields for this type anymore.
if sch.Types[nt] == nil {
continue
}
def.Fields[i] = f
i++
}
def.Fields = def.Fields[:i]
// In case of UpdateTypeInput, if TypePatch gets cleaned up then it becomes
// input UpdateTypeInput {
// filter: TypeFilter!
// }
// In this case, UpdateTypeInput should also be deleted.
if len(def.Fields) == 0 || (strings.HasPrefix(def.Name, "Update") && len(def.Fields) == 1) {
delete(sch.Types, def.Name)
}
}
func cleanSchema(sch *ast.Schema) {
// Let's go over inputs of the type TRef, TPatch AddTInput, UpdateTInput and delete the ones which
// don't have field inside them.
for k := range sch.Types {
if strings.HasSuffix(k, "Ref") || strings.HasSuffix(k, "Patch") ||
((strings.HasPrefix(k, "Add") || strings.HasPrefix(k, "Update")) && strings.HasSuffix(k, "Input")) {
cleanupInput(sch, sch.Types[k], map[string]bool{})
}
}
// Let's go over mutations and cleanup those which don't have AddTInput/UpdateTInput defined in the schema
// anymore.
i := 0 // helps us overwrite the array with valid entries.
for _, field := range sch.Mutation.Fields {
custom := field.Directives.ForName("custom")
// We would only modify add/update
if custom != nil || !(strings.HasPrefix(field.Name, "add") || strings.HasPrefix(field.Name, "update")) {
sch.Mutation.Fields[i] = field
i++
continue
}
// addT / updateT type mutations have an input which is AddTInput / UpdateTInput so if that doesn't exist anymore,
// we can delete the AddTPayload / UpdateTPayload and also skip this mutation.
var typeName, input string
if strings.HasPrefix(field.Name, "add") {
typeName = field.Name[3:]
input = "Add" + typeName + "Input"
} else if strings.HasPrefix(field.Name, "update") {
typeName = field.Name[6:]
input = "Update" + typeName + "Input"
}
if sch.Types[input] == nil {
delete(sch.Types, input)
continue
}
sch.Mutation.Fields[i] = field
i++
}
sch.Mutation.Fields = sch.Mutation.Fields[:i]
}
func addUnionReferenceType(schema *ast.Schema, defn *ast.Definition) {
refTypeName := defn.Name + "Ref"
refType := &ast.Definition{
Kind: ast.InputObject,
Name: refTypeName,
}
for _, typName := range defn.Types {
refType.Fields = append(refType.Fields, &ast.FieldDefinition{