-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
rules.go
1782 lines (1612 loc) · 57.8 KB
/
rules.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"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"github.com/dgraph-io/dgraph/x"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/vektah/gqlparser/v2/parser"
"github.com/vektah/gqlparser/v2/validator"
)
func init() {
schemaDocValidations = append(schemaDocValidations, inputTypeNameValidation,
customQueryNameValidation, customMutationNameValidation)
defnValidations = append(defnValidations, dataTypeCheck, nameCheck)
schemaValidations = append(schemaValidations, dgraphDirectivePredicateValidation)
typeValidations = append(typeValidations, idCountCheck, dgraphDirectiveTypeValidation,
passwordDirectiveValidation, conflictingDirectiveValidation, nonIdFieldsCheck,
remoteTypeValidation)
fieldValidations = append(fieldValidations, listValidityCheck, fieldArgumentCheck,
fieldNameCheck, isValidFieldForList, hasAuthDirective)
validator.AddRule("Check variable type is correct", variableTypeCheck)
validator.AddRule("Check for list type value", listTypeCheck)
}
func dgraphDirectivePredicateValidation(gqlSch *ast.Schema, definitions []string) gqlerror.List {
var errs []*gqlerror.Error
type pred struct {
name string
parentName string
typ string
position *ast.Position
isId bool
isSecret bool
}
preds := make(map[string]pred)
interfacePreds := make(map[string]map[string]bool)
secretError := func(secretPred, newPred pred) *gqlerror.Error {
return gqlerror.ErrorPosf(newPred.position,
"Type %s; Field %s: has the @dgraph predicate, but that conflicts with type %s "+
"@secret directive on the same predicate. @secret predicates are stored encrypted"+
" and so the same predicate can't be used as a %s.", newPred.parentName,
newPred.name, secretPred.parentName, newPred.typ)
}
typeError := func(existingPred, newPred pred) *gqlerror.Error {
return gqlerror.ErrorPosf(newPred.position,
"Type %s; Field %s: has type %s, which is different to type %s; field %s, which has "+
"the same @dgraph directive but type %s. These fields must have either the same "+
"GraphQL types, or use different Dgraph predicates.", newPred.parentName,
newPred.name, newPred.typ, existingPred.parentName, existingPred.name,
existingPred.typ)
}
idError := func(idPred, newPred pred) *gqlerror.Error {
return gqlerror.ErrorPosf(newPred.position,
"Type %s; Field %s: doesn't have @id directive, which conflicts with type %s; field "+
"%s, which has the same @dgraph directive along with @id directive. Both these "+
"fields must either use @id directive, or use different Dgraph predicates.",
newPred.parentName, newPred.name, idPred.parentName, idPred.name)
}
existingInterfaceFieldError := func(interfacePred, newPred pred) *gqlerror.Error {
return gqlerror.ErrorPosf(newPred.position,
"Type %s; Field %s: has the @dgraph directive, which conflicts with interface %s; "+
"field %s, that this type implements. These fields must use different Dgraph "+
"predicates.", newPred.parentName, newPred.name, interfacePred.parentName,
interfacePred.name)
}
conflictingFieldsInImplementedInterfacesError := func(def *ast.Definition,
interfaces []string, pred string) *gqlerror.Error {
return gqlerror.ErrorPosf(def.Position,
"Type %s; implements interfaces %v, all of which have fields with @dgraph predicate:"+
" %s. These fields must use different Dgraph predicates.", def.Name, interfaces,
pred)
}
checkExistingInterfaceFieldError := func(def *ast.Definition, existingPred, newPred pred) {
for _, defName := range def.Interfaces {
if existingPred.parentName == defName {
errs = append(errs, existingInterfaceFieldError(existingPred, newPred))
}
}
}
checkConflictingDirectivesOnInterface := func(def *ast.Definition) {
for _, directive := range def.Directives {
if directive.Name == authDirective {
errs = append(errs, gqlerror.ErrorPosf(def.Position,
"Interface %s; @auth directive is not allowed on interfaces.", def.Name))
}
}
}
checkConflictingFieldsInImplementedInterfacesError := func(typ *ast.Definition) {
fieldsToReport := make(map[string][]string)
interfaces := typ.Interfaces
for i := 0; i < len(interfaces); i++ {
intr1 := interfaces[i]
interfacePreds1 := interfacePreds[intr1]
for j := i + 1; j < len(interfaces); j++ {
intr2 := interfaces[j]
for fname := range interfacePreds[intr2] {
if interfacePreds1[fname] {
if len(fieldsToReport[fname]) == 0 {
fieldsToReport[fname] = append(fieldsToReport[fname], intr1)
}
fieldsToReport[fname] = append(fieldsToReport[fname], intr2)
}
}
}
}
for fname, interfaces := range fieldsToReport {
errs = append(errs, conflictingFieldsInImplementedInterfacesError(typ, interfaces,
fname))
}
}
// make sure all the interfaces are validated before validating any concrete types
// this is required when validating that a type if implements two interfaces, then none of the
// fields in those interfaces has the same dgraph predicate
var interfaces, concreteTypes []string
for _, def := range definitions {
if gqlSch.Types[def].Kind == ast.Interface {
interfaces = append(interfaces, def)
} else {
concreteTypes = append(concreteTypes, def)
}
}
definitions = append(interfaces, concreteTypes...)
for _, key := range definitions {
def := gqlSch.Types[key]
switch def.Kind {
case ast.Object, ast.Interface:
typName := typeName(def)
if def.Kind == ast.Interface {
interfacePreds[def.Name] = make(map[string]bool)
checkConflictingDirectivesOnInterface(def)
} else {
checkConflictingFieldsInImplementedInterfacesError(def)
}
for _, f := range def.Fields {
if f.Type.Name() == "ID" {
continue
}
fname := fieldName(f, typName)
// this field could have originally been defined in an interface that this type
// implements. If we get a parent interface, that means this field gets validated
// during the validation of that interface. So, no need to validate this field here.
if parentInterface(gqlSch, def, f.Name) == nil {
if def.Kind == ast.Interface {
interfacePreds[def.Name][fname] = true
}
var prefix, suffix string
if f.Type.Elem != nil {
prefix = "["
suffix = "]"
}
thisPred := pred{
name: f.Name,
parentName: def.Name,
typ: fmt.Sprintf("%s%s%s", prefix, f.Type.Name(), suffix),
position: f.Position,
isId: f.Directives.ForName(idDirective) != nil,
isSecret: false,
}
if pred, ok := preds[fname]; ok {
if pred.isSecret {
errs = append(errs, secretError(pred, thisPred))
} else if thisPred.typ != pred.typ {
errs = append(errs, typeError(pred, thisPred))
}
if pred.isId != thisPred.isId {
if pred.isId {
errs = append(errs, idError(pred, thisPred))
} else {
errs = append(errs, idError(thisPred, pred))
}
}
if def.Kind == ast.Object {
checkExistingInterfaceFieldError(def, pred, thisPred)
}
} else {
preds[fname] = thisPred
}
}
}
pwdField := getPasswordField(def)
if pwdField != nil {
fname := fieldName(pwdField, typName)
if getDgraphDirPredArg(pwdField) != nil && parentInterfaceForPwdField(gqlSch, def,
pwdField.Name) == nil {
thisPred := pred{
name: pwdField.Name,
parentName: def.Name,
typ: pwdField.Type.Name(),
position: pwdField.Position,
isId: false,
isSecret: true,
}
if pred, ok := preds[fname]; ok {
if thisPred.typ != pred.typ || !pred.isSecret {
errs = append(errs, secretError(thisPred, pred))
}
if def.Kind == ast.Object {
checkExistingInterfaceFieldError(def, pred, thisPred)
}
} else {
preds[fname] = thisPred
}
}
}
}
}
return errs
}
func inputTypeNameValidation(schema *ast.SchemaDocument) gqlerror.List {
var errs []*gqlerror.Error
forbiddenInputTypeNames := map[string]bool{
// The types that we define in schemaExtras
"DateTime": true,
"DgraphIndex": true,
"HTTPMethod": true,
"CustomHTTP": true,
"CustomGraphQL": true,
"IntFilter": true,
"FloatFilter": true,
"DateTimeFilter": true,
"StringTermFilter": true,
"StringRegExpFilter": true,
"StringFullTextFilter": true,
"StringExactFilter": true,
"StringHashFilter": true,
}
definedInputTypes := make([]*ast.Definition, 0)
for _, defn := range schema.Definitions {
defName := defn.Name
if isQueryOrMutation(defName) {
continue
}
if defn.Kind == ast.InputObject {
definedInputTypes = append(definedInputTypes, defn)
continue
}
if defn.Kind != ast.Object && defn.Kind != ast.Interface {
continue
}
// types that are generated by us
forbiddenInputTypeNames[defName+"Ref"] = true
forbiddenInputTypeNames[defName+"Patch"] = true
forbiddenInputTypeNames["Update"+defName+"Input"] = true
forbiddenInputTypeNames["Update"+defName+"Payload"] = true
forbiddenInputTypeNames["Delete"+defName+"Input"] = true
if defn.Kind == ast.Object {
forbiddenInputTypeNames["Add"+defName+"Input"] = true
forbiddenInputTypeNames["Add"+defName+"Payload"] = true
}
forbiddenInputTypeNames[defName+"Filter"] = true
forbiddenInputTypeNames[defName+"Order"] = true
forbiddenInputTypeNames[defName+"Orderable"] = true
}
for _, inputType := range definedInputTypes {
if forbiddenInputTypeNames[inputType.Name] {
errs = append(errs, gqlerror.ErrorPosf(inputType.Position,
"%s is a reserved word, so you can't declare an input type with this name. "+
"Pick a different name for the input type.", inputType.Name))
}
}
return errs
}
func customQueryNameValidation(schema *ast.SchemaDocument) gqlerror.List {
var errs []*gqlerror.Error
forbiddenNames := map[string]bool{}
definedQueries := make([]*ast.FieldDefinition, 0)
for _, defn := range schema.Definitions {
defName := defn.Name
if defName == "Query" {
definedQueries = append(definedQueries, defn.Fields...)
continue
}
if defn.Kind != ast.Object && defn.Kind != ast.Interface {
continue
}
// forbid query names that are generated by us
forbiddenNames["get"+defName] = true
forbiddenNames["check"+defName+"Password"] = true
forbiddenNames["query"+defName] = true
}
for _, qry := range definedQueries {
if forbiddenNames[qry.Name] {
errs = append(errs, gqlerror.ErrorPosf(qry.Position,
"%s is a reserved word, so you can't declare a query with this name. "+
"Pick a different name for the query.", qry.Name))
}
}
return errs
}
func customMutationNameValidation(schema *ast.SchemaDocument) gqlerror.List {
var errs []*gqlerror.Error
forbiddenNames := map[string]bool{}
definedMutations := make([]*ast.FieldDefinition, 0)
for _, defn := range schema.Definitions {
defName := defn.Name
if defName == "Mutation" {
definedMutations = append(definedMutations, defn.Fields...)
continue
}
if defn.Kind != ast.Object && defn.Kind != ast.Interface {
continue
}
// forbid mutation names that are generated by us
switch defn.Kind {
case ast.Interface:
forbiddenNames["update"+defName] = true
forbiddenNames["delete"+defName] = true
case ast.Object:
forbiddenNames["add"+defName] = true
forbiddenNames["update"+defName] = true
forbiddenNames["delete"+defName] = true
}
}
for _, mut := range definedMutations {
if forbiddenNames[mut.Name] {
errs = append(errs, gqlerror.ErrorPosf(mut.Position,
"%s is a reserved word, so you can't declare a mutation with this name. "+
"Pick a different name for the mutation.", mut.Name))
}
}
return errs
}
func dataTypeCheck(schema *ast.Schema, defn *ast.Definition) gqlerror.List {
if defn.Kind == ast.Object || defn.Kind == ast.Enum || defn.Kind == ast.Interface || defn.
Kind == ast.InputObject {
return nil
}
return []*gqlerror.Error{gqlerror.ErrorPosf(
defn.Position,
"You can't add %s definitions. "+
"Only type, interface, input and enums are allowed in initial schema.",
strings.ToLower(string(defn.Kind)))}
}
func nameCheck(schema *ast.Schema, defn *ast.Definition) gqlerror.List {
if (defn.Kind == ast.Object || defn.Kind == ast.Enum) && isReservedKeyWord(defn.Name) {
var errMesg string
if isQueryOrMutationType(defn) {
for _, fld := range defn.Fields {
// If we find any query or mutation field defined without a @custom directive, that
// is an error for us.
custom := fld.Directives.ForName(customDirective)
if custom == nil {
errMesg = "GraphQL Query and Mutation types are only allowed to have fields " +
"with @custom directive. Other fields are built automatically for you. " +
"Found " + defn.Name + " " + fld.Name + " without @custom."
break
}
}
if errMesg == "" {
return nil
}
} else {
errMesg = fmt.Sprintf(
"%s is a reserved word, so you can't declare a type with this name. "+
"Pick a different name for the type.", defn.Name,
)
}
return []*gqlerror.Error{gqlerror.ErrorPosf(defn.Position, errMesg)}
}
return nil
}
func collectFieldNames(idFields []*ast.FieldDefinition) (string, []gqlerror.Location) {
var fieldNames []string
var errLocations []gqlerror.Location
for _, f := range idFields {
fieldNames = append(fieldNames, f.Name)
errLocations = append(errLocations, gqlerror.Location{
Line: f.Position.Line,
Column: f.Position.Column,
})
}
fieldNamesString := fmt.Sprintf(
"%s and %s",
strings.Join(fieldNames[:len(fieldNames)-1], ", "), fieldNames[len(fieldNames)-1],
)
return fieldNamesString, errLocations
}
func conflictingDirectiveValidation(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
var hasAuth, hasRemote bool
for _, dir := range typ.Directives {
if dir.Name == authDirective {
hasAuth = true
}
if dir.Name == remoteDirective {
hasRemote = true
}
}
if hasAuth && hasRemote {
return []*gqlerror.Error{gqlerror.ErrorPosf(typ.Position, `Type %s; cannot have both @%s and @%s directive`,
typ.Name, authDirective, remoteDirective)}
}
return nil
}
func passwordDirectiveValidation(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
dirs := make([]string, 0)
var errs []*gqlerror.Error
for _, dir := range typ.Directives {
if dir.Name != secretDirective {
continue
}
val := dir.Arguments.ForName("field").Value.Raw
if val == "" {
errs = append(errs, gqlerror.ErrorPosf(typ.Position,
`Type %s; Argument "field" of secret directive is empty`, typ.Name))
return errs
}
dirs = append(dirs, val)
}
if len(dirs) > 1 {
val := strings.Join(dirs, ",")
errs = append(errs, gqlerror.ErrorPosf(typ.Position,
"Type %s; has more than one secret fields %s", typ.Name, val))
return errs
}
if len(dirs) == 0 {
return nil
}
val := dirs[0]
for _, f := range typ.Fields {
if f.Name == val {
errs = append(errs, gqlerror.ErrorPosf(typ.Position,
"Type %s; has a secret directive and field of the same name %s",
typ.Name, val))
return errs
}
}
return nil
}
func dgraphDirectiveTypeValidation(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
dir := typ.Directives.ForName(dgraphDirective)
if dir == nil {
return nil
}
typeArg := dir.Arguments.ForName(dgraphTypeArg)
if typeArg == nil || typeArg.Value.Raw == "" {
return []*gqlerror.Error{gqlerror.ErrorPosf(
dir.Position,
"Type %s; type argument for @dgraph directive should not be empty.", typ.Name)}
}
if typeArg.Value.Kind != ast.StringValue {
return []*gqlerror.Error{gqlerror.ErrorPosf(
dir.Position,
"Type %s; type argument for @dgraph directive should of type String.", typ.Name)}
}
return nil
}
// A type should have other fields apart from fields of
// 1. Type ID!
// 2. Fields with @custom directive.
// to be a valid type. Otherwise its not possible to add objects of that type.
func nonIdFieldsCheck(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
if isQueryOrMutation(typ.Name) || typ.Kind == ast.Enum || typ.Kind == ast.Interface ||
typ.Kind == ast.InputObject {
return nil
}
// We don't generate mutations for remote types, so we skip this check for them.
remote := typ.Directives.ForName(remoteDirective)
if remote != nil {
return nil
}
hasNonIdField := false
for _, field := range typ.Fields {
custom := field.Directives.ForName(customDirective)
if isIDField(typ, field) || custom != nil {
continue
}
hasNonIdField = true
break
}
if !hasNonIdField {
return []*gqlerror.Error{gqlerror.ErrorPosf(typ.Position, "Type %s; is invalid, a type must have atleast "+
"one field that is not of ID! type and doesn't have @custom directive.", typ.Name)}
}
return nil
}
func remoteTypeValidation(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
if isQueryOrMutation(typ.Name) {
return nil
}
remote := typ.Directives.ForName(remoteDirective)
if remote == nil {
for _, field := range typ.Fields {
// If the field is being resolved through a custom directive, then we don't care if
// the type for the field is a remote or a non-remote type.
custom := field.Directives.ForName(customDirective)
if custom != nil {
continue
}
t := field.Type.Name()
origTyp := schema.Types[t]
remoteDir := origTyp.Directives.ForName(remoteDirective)
if remoteDir != nil {
return []*gqlerror.Error{gqlerror.ErrorPosf(field.Position, "Type %s; "+
"field %s; is of a type that has @remote directive. Those would need to be "+
"resolved by a @custom directive.", typ.Name, field.Name)}
}
}
for _, implements := range typ.Interfaces {
origTyp := schema.Types[implements]
remoteDir := origTyp.Directives.ForName(remoteDirective)
if remoteDir != nil {
return []*gqlerror.Error{gqlerror.ErrorPosf(typ.Position, "Type %s; "+
"without @remote directive can't implement an interface %s; with have "+
"@remote directive.", typ.Name, implements)}
}
}
return nil
}
// This means that the type was a remote type.
for _, field := range typ.Fields {
custom := field.Directives.ForName(customDirective)
if custom != nil {
return []*gqlerror.Error{gqlerror.ErrorPosf(field.Position, "Type %s; "+
"field %s; can't have @custom directive as a @remote type can't have fields with"+
" @custom directive.", typ.Name, field.Name)}
}
}
for _, implements := range typ.Interfaces {
origTyp := schema.Types[implements]
remoteDir := origTyp.Directives.ForName(remoteDirective)
if remoteDir == nil {
return []*gqlerror.Error{gqlerror.ErrorPosf(typ.Position, "Type %s; "+
"with @remote directive implements interface %s; which doesn't have @remote "+
"directive.", typ.Name, implements)}
}
}
return nil
}
func idCountCheck(schema *ast.Schema, typ *ast.Definition) gqlerror.List {
var idFields []*ast.FieldDefinition
var idDirectiveFields []*ast.FieldDefinition
for _, field := range typ.Fields {
if isIDField(typ, field) {
idFields = append(idFields, field)
}
if d := field.Directives.ForName(idDirective); d != nil {
idDirectiveFields = append(idDirectiveFields, field)
}
}
var errs []*gqlerror.Error
if len(idFields) > 1 {
fieldNamesString, errLocations := collectFieldNames(idFields)
errMessage := fmt.Sprintf(
"Fields %s are listed as IDs for type %s, "+
"but a type can have only one ID field. "+
"Pick a single field as the ID for type %s.",
fieldNamesString, typ.Name, typ.Name,
)
errs = append(errs, &gqlerror.Error{
Message: errMessage,
Locations: errLocations,
})
}
if len(idDirectiveFields) > 1 {
fieldNamesString, errLocations := collectFieldNames(idDirectiveFields)
errMessage := fmt.Sprintf(
"Type %s: fields %s have the @id directive, "+
"but a type can have only one field with @id. "+
"Pick a single field with @id for type %s.",
typ.Name, fieldNamesString, typ.Name,
)
errs = append(errs, &gqlerror.Error{
Message: errMessage,
Locations: errLocations,
})
}
return errs
}
func hasAuthDirective(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
for _, directive := range field.Directives {
if directive.Name != authDirective {
continue
}
return []*gqlerror.Error{gqlerror.ErrorPosf(field.Position,
"Type %s; Field %s: @%s directive is not allowed on fields",
typ.Name, field.Name, authDirective)}
}
return nil
}
func isValidFieldForList(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
if field.Type.Elem == nil && field.Type.NamedType != "" {
return nil
}
// ID and Boolean list are not allowed.
// [Boolean] is not allowed as dgraph schema doesn't support [bool] yet.
switch field.Type.Elem.Name() {
case
"ID",
"Boolean":
return []*gqlerror.Error{gqlerror.ErrorPosf(
field.Position, "Type %s; Field %s: %s lists are invalid.",
typ.Name, field.Name, field.Type.Elem.Name())}
}
return nil
}
func fieldArgumentCheck(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
if isQueryOrMutationType(typ) {
return nil
}
// We don't need to verify the argument names for fields which are part of a remote type as
// we don't add any of our own arguments to them.
remote := typ.Directives.ForName(remoteDirective)
if remote != nil {
return nil
}
for _, arg := range field.Arguments {
if isReservedArgument(arg.Name) {
return []*gqlerror.Error{gqlerror.ErrorPosf(field.Position, "Type %s; Field %s:"+
" can't have %s as an argument because it is a reserved argument.",
typ.Name, field.Name, arg.Name)}
}
}
return nil
}
func fieldNameCheck(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
// field name cannot be a reserved word
if isReservedKeyWord(field.Name) {
return []*gqlerror.Error{gqlerror.ErrorPosf(
field.Position, "Type %s; Field %s: %s is a reserved keyword and "+
"you cannot declare a field with this name.",
typ.Name, field.Name, field.Name)}
}
return nil
}
func listValidityCheck(typ *ast.Definition, field *ast.FieldDefinition) gqlerror.List {
if field.Type.Elem == nil && field.Type.NamedType != "" {
return nil
}
// Nested lists are not allowed.
if field.Type.Elem.Elem != nil {
return []*gqlerror.Error{gqlerror.ErrorPosf(field.Position,
"Type %s; Field %s: Nested lists are invalid.",
typ.Name, field.Name)}
}
return nil
}
func hasInverseValidation(sch *ast.Schema, typ *ast.Definition,
field *ast.FieldDefinition, dir *ast.Directive,
secrets map[string]x.SensitiveByteSlice) gqlerror.List {
var errs []*gqlerror.Error
invTypeName := field.Type.Name()
if sch.Types[invTypeName].Kind != ast.Object && sch.Types[invTypeName].Kind != ast.Interface {
errs = append(errs,
gqlerror.ErrorPosf(
field.Position,
"Type %s; Field %s: Field %[2]s is of type %s, but @hasInverse directive only applies"+
" to fields with object types.", typ.Name, field.Name, invTypeName))
return errs
}
invFieldArg := dir.Arguments.ForName("field")
if invFieldArg == nil {
// This check can be removed once gqlparser bug
// #107(https://github.com/vektah/gqlparser/issues/107) is fixed.
errs = append(errs,
gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: @hasInverse directive doesn't have field argument.",
typ.Name, field.Name))
return errs
}
invFieldName := invFieldArg.Value.Raw
invType := sch.Types[invTypeName]
invField := invType.Fields.ForName(invFieldName)
if invField == nil {
errs = append(errs,
gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: inverse field %s doesn't exist for type %s.",
typ.Name, field.Name, invFieldName, invTypeName))
return errs
}
if errMsg := isInverse(sch, typ.Name, field.Name, invTypeName, invField); errMsg != "" {
errs = append(errs, gqlerror.ErrorPosf(dir.Position, errMsg))
return errs
}
invDirective := invField.Directives.ForName(inverseDirective)
if invDirective == nil {
addDirective := func(fld *ast.FieldDefinition) {
fld.Directives = append(fld.Directives, &ast.Directive{
Name: inverseDirective,
Arguments: []*ast.Argument{
{
Name: inverseArg,
Value: &ast.Value{
Raw: field.Name,
Position: dir.Position,
Kind: ast.EnumValue,
},
},
},
Position: dir.Position,
})
}
addDirective(invField)
// If it was an interface, we also need to copy the @hasInverse directive
// to all implementing types
if invType.Kind == ast.Interface {
for _, t := range sch.Types {
if implements(t, invType) {
f := t.Fields.ForName(invFieldName)
if f != nil {
addDirective(f)
}
}
}
}
}
return nil
}
func implements(typ, intfc *ast.Definition) bool {
for _, t := range typ.Interfaces {
if t == intfc.Name {
return true
}
}
return false
}
func isInverse(sch *ast.Schema, expectedInvType, expectedInvField, typeName string,
field *ast.FieldDefinition) string {
// We might have copied this directive in from an interface we are implementing.
// If so, make the check for that interface.
parentInt := parentInterface(sch, sch.Types[expectedInvType], expectedInvField)
if parentInt != nil {
fld := parentInt.Fields.ForName(expectedInvField)
if fld.Directives != nil && fld.Directives.ForName(inverseDirective) != nil {
expectedInvType = parentInt.Name
}
}
invType := field.Type.Name()
if invType != expectedInvType {
return fmt.Sprintf(
"Type %s; Field %s: @hasInverse is required to link the fields"+
" of same type, but the field %s is of the type %s instead of"+
" %[1]s. To link these make sure the fields are of the same type.",
expectedInvType, expectedInvField, field.Name, field.Type,
)
}
invDirective := field.Directives.ForName(inverseDirective)
if invDirective == nil {
return ""
}
invFieldArg := invDirective.Arguments.ForName("field")
if invFieldArg == nil || invFieldArg.Value.Raw != expectedInvField {
return fmt.Sprintf(
"Type %s; Field %s: @hasInverse should be consistant."+
" %[1]s.%[2]s is the inverse of %[3]s.%[4]s, but"+
" %[3]s.%[4]s is the inverse of %[1]s.%[5]s.",
expectedInvType, expectedInvField, typeName, field.Name,
invFieldArg.Value.Raw,
)
}
return ""
}
// validateSearchArg checks that the argument for search is valid and compatible
// with the type it is applied to.
func validateSearchArg(searchArg string,
sch *ast.Schema,
typ *ast.Definition,
field *ast.FieldDefinition,
dir *ast.Directive) *gqlerror.Error {
isEnum := sch.Types[field.Type.Name()].Kind == ast.Enum
search, ok := supportedSearches[searchArg]
switch {
case !ok:
// This check can be removed once gqlparser bug
// #107(https://github.com/vektah/gqlparser/issues/107) is fixed.
return gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: the argument to @search %s isn't valid."+
"Fields of type %s %s.",
typ.Name, field.Name, searchArg, field.Type.Name(), searchMessage(sch, field))
case search.gqlType != field.Type.Name() && !isEnum:
return gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: has the @search directive but the argument %s "+
"doesn't apply to field type %s. Search by %[3]s applies to fields of type %[5]s. "+
"Fields of type %[4]s %[6]s.",
typ.Name, field.Name, searchArg, field.Type.Name(),
supportedSearches[searchArg].gqlType, searchMessage(sch, field))
case isEnum && !enumDirectives[searchArg]:
return gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: has the @search directive but the argument %s "+
"doesn't apply to field type %s which is an Enum. Enum only supports "+
"hash, exact, regexp and trigram",
typ.Name, field.Name, searchArg, field.Type.Name())
}
return nil
}
func searchValidation(
sch *ast.Schema,
typ *ast.Definition,
field *ast.FieldDefinition,
dir *ast.Directive,
secrets map[string]x.SensitiveByteSlice) gqlerror.List {
var errs []*gqlerror.Error
arg := dir.Arguments.ForName(searchArgs)
if arg == nil {
// If there's no arg, then it can be an enum or has to be a scalar that's
// not ID. The schema generation will add the default search
// for that type.
if sch.Types[field.Type.Name()].Kind == ast.Enum ||
(sch.Types[field.Type.Name()].Kind == ast.Scalar && !isIDField(typ, field)) {
return nil
}
errs = append(errs, gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: has the @search directive but fields of type %s "+
"can't have the @search directive.",
typ.Name, field.Name, field.Type.Name()))
return errs
}
// This check can be removed once gqlparser bug
// #107(https://github.com/vektah/gqlparser/issues/107) is fixed.
if arg.Value.Kind != ast.ListValue {
errs = append(errs, gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: the @search directive requires a list argument, like @search(by: [hash])",
typ.Name, field.Name))
return errs
}
searchArgs := getSearchArgs(field)
searchIndexes := make(map[string]string)
for _, searchArg := range searchArgs {
if err := validateSearchArg(searchArg, sch, typ, field, dir); err != nil {
errs = append(errs, err)
return errs
}
// Checks that the filter indexes aren't repeated and they
// don't clash with each other.
searchIndex := builtInFilters[searchArg]
if val, ok := searchIndexes[searchIndex]; ok {
if field.Type.Name() == "String" || sch.Types[field.Type.Name()].Kind == ast.Enum {
errs = append(errs, gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: the argument to @search '%s' is the same "+
"as the index '%s' provided before and shouldn't "+
"be used together",
typ.Name, field.Name, searchArg, val))
return errs
}
errs = append(errs, gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: has the search directive on %s. %s "+
"allows only one argument for @search.",
typ.Name, field.Name, field.Type.Name(), field.Type.Name()))
return errs
}
for _, index := range filtersCollisions[searchIndex] {
if val, ok := searchIndexes[index]; ok {
errs = append(errs, gqlerror.ErrorPosf(
dir.Position,
"Type %s; Field %s: the arguments '%s' and '%s' can't "+
"be used together as arguments to @search.",
typ.Name, field.Name, searchArg, val))
return errs
}
}
searchIndexes[searchIndex] = searchArg
}
return errs