-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathgqlschema.go
1689 lines (1469 loc) · 43.8 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/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/vektah/gqlparser/v2/parser"
)
const (
inverseDirective = "hasInverse"
inverseArg = "field"
searchDirective = "search"
searchArgs = "by"
dgraphDirective = "dgraph"
dgraphTypeArg = "type"
dgraphPredArg = "pred"
idDirective = "id"
secretDirective = "secret"
authDirective = "auth"
customDirective = "custom"
remoteDirective = "remote" // types with this directive are not stored in Dgraph.
cascadeDirective = "cascade"
SubscriptionDirective = "withSubscription"
// custom directive args and fields
dqlArg = "dql"
mode = "mode"
BATCH = "BATCH"
SINGLE = "SINGLE"
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 currently represent values in range [-(2^53)+1, (2^53)-1] without any error.
Values out of this range but representable by a signed 64-bit integer, may get coercion error.
"""
scalar Int64
scalar DateTime
enum DgraphIndex {
int
int64
float
bool
hash
exact
term
fulltext
trigram
regexp
year
month
day
hour
}
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
}
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(
query: AuthRule,
add: AuthRule,
update: AuthRule,
delete:AuthRule) on OBJECT
directive @custom(http: CustomHTTP, dql: String) on FIELD_DEFINITION
directive @remote on OBJECT | INTERFACE
directive @cascade(fields :[String]) on FIELD
input IntFilter {
eq: Int
le: Int
lt: Int
ge: Int
gt: Int
}
input Int64Filter {
eq: Int64
le: Int64
lt: Int64
ge: Int64
gt: Int64
}
input FloatFilter {
eq: Float
le: Float
lt: Float
ge: Float
gt: Float
}
input DateTimeFilter {
eq: DateTime
le: DateTime
lt: DateTime
ge: DateTime
gt: DateTime
}
input StringTermFilter {
allofterms: String
anyofterms: String
}
input StringRegExpFilter {
regexp: String
}
input StringFullTextFilter {
alloftext: String
anyoftext: String
}
input StringExactFilter {
eq: String
le: String
lt: String
ge: String
gt: String
}
input StringHashFilter {
eq: 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"},
}
// GraphQL scalar 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",
}
// 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,
}
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",
}
// GraphQL scalar -> Dgraph scalar
var scalarToDgraph = map[string]string{
"ID": "uid",
"Boolean": "bool",
"Int": "int",
"Int64": "int",
"Float": "float",
"String": "string",
"DateTime": "dateTime",
"Password": "password",
}
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,
secretDirective: passwordValidation,
customDirective: customDirectiveValidation,
remoteDirective: ValidatorNoOp,
deprecatedDirective: ValidatorNoOp,
SubscriptionDirective: ValidatorNoOp,
// Just go get it printed into generated schema
authDirective: ValidatorNoOp,
}
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) {
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 {
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 {
// 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))
}
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...)
}
// 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.Interface && defn.Kind != ast.Object {
continue
}
// Common types to both Interface and Object.
addReferenceType(sch, defn)
addPatchType(sch, defn)
addUpdateType(sch, defn)
addUpdatePayloadType(sch, defn)
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.
addUpdateMutation(sch, defn)
addDeleteMutation(sch, defn)
case ast.Object:
// types and inputs needed for mutations
addInputType(sch, defn)
addAddPayloadType(sch, defn)
addMutations(sch, defn)
}
// types and inputs needed for query and search
addFilterType(sch, defn)
addTypeOrderable(sch, defn)
addFieldFilters(sch, defn)
addQueries(sch, defn)
}
}
func addInputType(schema *ast.Schema, defn *ast.Definition) {
schema.Types["Add"+defn.Name+"Input"] = &ast.Definition{
Kind: ast.InputObject,
Name: "Add" + defn.Name + "Input",
Fields: getFieldsWithoutIDType(schema, defn),
}
}
func addReferenceType(schema *ast.Schema, defn *ast.Definition) {
var flds ast.FieldList
if defn.Kind == ast.Interface {
if !hasID(defn) && !hasXID(defn) {
return
}
flds = append(getIDField(defn), getXIDField(defn)...)
} else {
flds = append(getIDField(defn), getFieldsWithoutIDType(schema, defn)...)
}
if len(flds) == 1 && (hasID(defn) || hasXID(defn)) {
flds[0].Type.NonNull = true
} else {
for _, fld := range flds {
fld.Type.NonNull = false
}
}
schema.Types[defn.Name+"Ref"] = &ast.Definition{
Kind: ast.InputObject,
Name: defn.Name + "Ref",
Fields: flds,
}
}
func addUpdateType(schema *ast.Schema, defn *ast.Definition) {
if !hasFilterable(defn) {
return
}
if _, ok := schema.Types[defn.Name+"Patch"]; !ok {
return
}
updType := &ast.Definition{
Kind: ast.InputObject,
Name: "Update" + defn.Name + "Input",
Fields: append(
ast.FieldList{&ast.FieldDefinition{
Name: "filter",
Type: &ast.Type{
NamedType: defn.Name + "Filter",
NonNull: true,
},
}},
&ast.FieldDefinition{
Name: "set",
Type: &ast.Type{
NamedType: defn.Name + "Patch",
},
},
&ast.FieldDefinition{
Name: "remove",
Type: &ast.Type{
NamedType: defn.Name + "Patch",
},
}),
}
schema.Types["Update"+defn.Name+"Input"] = updType
}
func addPatchType(schema *ast.Schema, defn *ast.Definition) {
if !hasFilterable(defn) {
return
}
nonIDFields := getNonIDFields(schema, defn)
if len(nonIDFields) == 0 {
// The user might just have an external id field and nothing else. We don't generate patch
// type in that case.
return
}
patchDefn := &ast.Definition{
Kind: ast.InputObject,
Name: defn.Name + "Patch",
Fields: nonIDFields,
}
schema.Types[defn.Name+"Patch"] = patchDefn
for _, fld := range patchDefn.Fields {
fld.Type.NonNull = false
}
}
// addFieldFilters adds field arguments that allow filtering to all fields of
// defn that can be searched. For example, if there's another type
// `type R { ... f: String @search(by: [term]) ... }`
// and defn has a field of type R, e.g. if defn is like
// `type T { ... g: R ... }`
// then a query should be able to filter on g by term search on f, like
// query {
// getT(id: 0x123) {
// ...
// g(filter: { f: { anyofterms: "something" } }, first: 10) { ... }
// ...
// }
// }
func addFieldFilters(schema *ast.Schema, defn *ast.Definition) {
for _, fld := range defn.Fields {
custom := fld.Directives.ForName(customDirective)
// Filtering and ordering for fields with @custom directive is handled by the remote
// endpoint.
if custom != nil {
continue
}
// Filtering makes sense both for lists (= return only items that match
// this filter) and for singletons (= only have this value in the result
// if it satisfies this filter)
addFilterArgument(schema, fld)
// Ordering and pagination, however, only makes sense for fields of
// list types (not scalar lists).
if _, scalar := scalarToDgraph[fld.Type.Name()]; !scalar && fld.Type.Elem != nil {
addOrderArgument(schema, fld)
// Pagination even makes sense when there's no orderables because
// Dgraph will do UID order by default.
addPaginationArguments(fld)
}
}
}
func addFilterArgument(schema *ast.Schema, fld *ast.FieldDefinition) {
fldType := fld.Type.Name()
if hasFilterable(schema.Types[fldType]) {
fld.Arguments = append(fld.Arguments,
&ast.ArgumentDefinition{
Name: "filter",
Type: &ast.Type{NamedType: fldType + "Filter"},
})
}
}
func addOrderArgument(schema *ast.Schema, fld *ast.FieldDefinition) {
fldType := fld.Type.Name()
if hasOrderables(schema.Types[fldType]) {
fld.Arguments = append(fld.Arguments,
&ast.ArgumentDefinition{
Name: "order",
Type: &ast.Type{NamedType: fldType + "Order"},
})
}
}
func addPaginationArguments(fld *ast.FieldDefinition) {
fld.Arguments = append(fld.Arguments,
&ast.ArgumentDefinition{Name: "first", Type: &ast.Type{NamedType: "Int"}},
&ast.ArgumentDefinition{Name: "offset", Type: &ast.Type{NamedType: "Int"}},
)
}
// getFilterTypes converts search arguments of a field to graphql filter types.
func getFilterTypes(schema *ast.Schema, fld *ast.FieldDefinition, filterName string) []string {
searchArgs := getSearchArgs(fld)
filterNames := make([]string, len(searchArgs))
for i, search := range searchArgs {
filterNames[i] = builtInFilters[search]
if (search == "hash" || search == "exact") && schema.Types[fld.Type.Name()].Kind == ast.Enum {
stringFilterName := fmt.Sprintf("String%sFilter", strings.Title(search))
var l ast.FieldList
for _, i := range schema.Types[stringFilterName].Fields {
l = append(l, &ast.FieldDefinition{
Name: i.Name,
Type: fld.Type,
Description: i.Description,
DefaultValue: i.DefaultValue,
})
}
filterNames[i] = fld.Type.Name() + "_" + search
schema.Types[filterNames[i]] = &ast.Definition{
Kind: ast.InputObject,
Name: filterNames[i],
Fields: l,
}
}
}
return filterNames
}
// mergeAndAddFilters merges multiple filterTypes into one and adds it to the schema.
func mergeAndAddFilters(filterTypes []string, schema *ast.Schema, filterName string) {
if len(filterTypes) <= 1 {
// Filters only require to be merged if there are alteast 2
return
}
var fieldList ast.FieldList
for _, typeName := range filterTypes {
fieldList = append(fieldList, schema.Types[typeName].Fields...)
}
schema.Types[filterName] = &ast.Definition{
Kind: ast.InputObject,
Name: filterName,
Fields: fieldList,
}
}
// addFilterType add a `input TFilter { ... }` type to the schema, if defn
// is a type that has fields that can be filtered on. This type filter is used
// in constructing the corresponding query
// queryT(filter: TFilter, ... )
// and in adding search to any fields of this type, like:
// type R {
// f(filter: TFilter, ... ): T
// ...
// }
func addFilterType(schema *ast.Schema, defn *ast.Definition) {
if !hasFilterable(defn) {
return
}
filterName := defn.Name + "Filter"
filter := &ast.Definition{
Kind: ast.InputObject,
Name: filterName,
}
for _, fld := range defn.Fields {
if isID(fld) {
filter.Fields = append(filter.Fields,
&ast.FieldDefinition{
Name: fld.Name,
Type: ast.ListType(&ast.Type{
NamedType: IDType,
NonNull: true,
}, nil),
})
continue
}
filterTypes := getFilterTypes(schema, fld, filterName)
if len(filterTypes) > 0 {
filterName := strings.Join(filterTypes, "_")
filter.Fields = append(filter.Fields,
&ast.FieldDefinition{
Name: fld.Name,
Type: &ast.Type{
NamedType: filterName,
},
})
mergeAndAddFilters(filterTypes, schema, filterName)
}
}
// Not filter makes sense even if the filter has only one field. And/Or would only make sense
// if the filter has more than one field or if it has one non-id field.
if (len(filter.Fields) == 1 && !isID(filter.Fields[0])) || len(filter.Fields) > 1 {
filter.Fields = append(filter.Fields,
&ast.FieldDefinition{Name: "and", Type: &ast.Type{NamedType: filterName}},
&ast.FieldDefinition{Name: "or", Type: &ast.Type{NamedType: filterName}},
)
}
filter.Fields = append(filter.Fields,
&ast.FieldDefinition{Name: "not", Type: &ast.Type{NamedType: filterName}})
schema.Types[filterName] = filter
}
func hasFilterable(defn *ast.Definition) bool {
return fieldAny(defn.Fields,
func(fld *ast.FieldDefinition) bool {
return len(getSearchArgs(fld)) != 0 || isID(fld)
})
}
func hasOrderables(defn *ast.Definition) bool {
return fieldAny(defn.Fields,
func(fld *ast.FieldDefinition) bool { return orderable[fld.Type.Name()] })
}
func hasID(defn *ast.Definition) bool {
return fieldAny(defn.Fields, isID)
}
func hasXID(defn *ast.Definition) bool {
return fieldAny(defn.Fields, hasIDDirective)
}
// fieldAny returns true if any field in fields satisfies pred
func fieldAny(fields ast.FieldList, pred func(*ast.FieldDefinition) bool) bool {
for _, fld := range fields {
if pred(fld) {
return true
}
}
return false
}
func addHashIfRequired(fld *ast.FieldDefinition, indexes []string) []string {
id := fld.Directives.ForName(idDirective)
if id != nil {
// If @id directive is applied along with @search, we check if the search has hash as an
// arg. If it doesn't, then we add it.
containsHash := false
for _, index := range indexes {
if index == "hash" {
containsHash = true
}
}
if !containsHash {
indexes = append(indexes, "hash")
}
}
return indexes
}
func getDefaultSearchIndex(fldName string) string {
if search, ok := defaultSearches[fldName]; ok {
return search
}
// it's an enum - always has hash index
return "hash"
}
// getSearchArgs returns the name of the search applied to fld, or ""
// if fld doesn't have a search directive.
func getSearchArgs(fld *ast.FieldDefinition) []string {
search := fld.Directives.ForName(searchDirective)
id := fld.Directives.ForName(idDirective)
if search == nil {
if id == nil {
return nil
}
// If search directive wasn't supplied but id was, then hash is the only index
// that we apply.
return []string{"hash"}
}
if len(search.Arguments) == 0 ||
len(search.Arguments.ForName(searchArgs).Value.Children) == 0 {
return []string{getDefaultSearchIndex(fld.Type.Name())}
}
val := search.Arguments.ForName(searchArgs).Value
res := make([]string, len(val.Children))
for i, child := range val.Children {
res[i] = child.Value.Raw
}
res = addHashIfRequired(fld, res)
sort.Strings(res)
return res
}
// addTypeOrderable adds an input type that allows ordering in query.
// Two things are added: an enum with the names of all the orderable fields,
// for a type T that's called TOrderable; and an input type that allows saying
// order asc or desc, for type T that's called TOrder.
// TOrder's fields are TOrderable's. So you
// might get:
// enum PostOrderable { datePublished, numLikes, ... }, and
// input PostOrder { asc : PostOrderable, desc: PostOrderable ...}
// Together they allow things like
// order: { asc: datePublished }
// and
// order: { asc: datePublished, then: { desc: title } }
//
// Dgraph allows multiple orderings `orderasc: datePublished, orderasc: title`
// to order by datePublished and then by title when dataPublished is the same.
// GraphQL doesn't allow the same field to be repeated, so
// `orderasc: datePublished, orderasc: title` wouldn't be valid. Instead, our
// GraphQL orderings are given by the structure
// `order: { asc: datePublished, then: { asc: title } }`.
// a further `then` would be a third ordering, etc.
func addTypeOrderable(schema *ast.Schema, defn *ast.Definition) {
if !hasOrderables(defn) {
return
}
orderName := defn.Name + "Order"
orderableName := defn.Name + "Orderable"
schema.Types[orderName] = &ast.Definition{
Kind: ast.InputObject,
Name: orderName,
Fields: ast.FieldList{
&ast.FieldDefinition{Name: "asc", Type: &ast.Type{NamedType: orderableName}},
&ast.FieldDefinition{Name: "desc", Type: &ast.Type{NamedType: orderableName}},
&ast.FieldDefinition{Name: "then", Type: &ast.Type{NamedType: orderName}},
},
}
order := &ast.Definition{
Kind: ast.Enum,
Name: orderableName,
}
for _, fld := range defn.Fields {
if orderable[fld.Type.Name()] {
order.EnumValues = append(order.EnumValues,
&ast.EnumValueDefinition{Name: fld.Name})
}
}
schema.Types[orderableName] = order
}
func addAddPayloadType(schema *ast.Schema, defn *ast.Definition) {
qry := &ast.FieldDefinition{
Name: camelCase(defn.Name),
Type: ast.ListType(&ast.Type{
NamedType: defn.Name,
}, nil),
}
addFilterArgument(schema, qry)
addOrderArgument(schema, qry)
addPaginationArguments(qry)