-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
parser.go
3056 lines (2814 loc) · 76.6 KB
/
parser.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 2015-2018 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 gql
import (
"bytes"
"fmt"
"sort"
"strconv"
"strings"
"github.com/dgraph-io/dgraph/lex"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
"github.com/pkg/errors"
)
const (
uid = "uid"
value = "val"
typ = "type"
)
// GraphQuery stores the parsed Query in a tree format. This gets converted to
// pb.y used query.SubGraph before processing the query.
type GraphQuery struct {
UID []uint64
Attr string
Langs []string
Alias string
IsCount bool
IsInternal bool
IsGroupby bool
Var string
NeedsVar []VarContext
Func *Function
Expand string // Which variable to expand with.
Args map[string]string
// Query can have multiple sort parameters.
Order []*pb.Order
Children []*GraphQuery
Filter *FilterTree
MathExp *MathTree
Normalize bool
Recurse bool
RecurseArgs RecurseArgs
ShortestPathArgs ShortestPathArgs
Cascade bool
IgnoreReflex bool
Facets *pb.FacetParams
FacetsFilter *FilterTree
GroupbyAttrs []GroupByAttr
FacetVar map[string]string
FacetOrder string
FacetDesc bool
// Internal fields below.
// If gq.fragment is nonempty, then it is a fragment reference / spread.
fragment string
// Indicates whether count of uids is requested as a child node. If there
// is an alias, then UidCountAlias will be set (otherwise it will be the
// empty string).
UidCount bool
UidCountAlias string
// True for blocks that don't have a starting function and hence no starting nodes. They are
// used to aggregate and get variables defined in another block.
IsEmpty bool
}
// RecurseArgs stores the arguments needed to process the @recurse directive.
type RecurseArgs struct {
Depth uint64
AllowLoop bool
}
// SHortestPathArgs stores the arguments needed to process the shortest path query.
type ShortestPathArgs struct {
// From, To can have a uid or a uid function as the argument.
// 1. from: 0x01
// 2. from: uid(0x01)
// 3. from: uid(p) // a variable
From *Function
To *Function
}
// GroupByAttr stores the arguments needed to process the @groupby directive.
type GroupByAttr struct {
Attr string
Alias string
Langs []string
}
// pair denotes the key value pair that is part of the GraphQL query root in parenthesis.
type pair struct {
Key string
Val string
}
// fragmentNode is an internal structure for doing dfs on fragments.
type fragmentNode struct {
Name string
Gq *GraphQuery
Entered bool // Entered in dfs.
Exited bool // Exited in dfs.
}
// fragmentMap is used to associate fragment names to their corresponding fragmentNode.
type fragmentMap map[string]*fragmentNode
const (
AnyVar = 0
UidVar = 1
ValueVar = 2
ListVar = 3
)
// VarContext stores information about the vars needed to complete a query.
type VarContext struct {
Name string
Typ int // 1 for UID vars, 2 for value vars
}
// varInfo holds information on GQL variables.
type varInfo struct {
Value string
Type string
}
// varMap is a map with key as GQL variable name.
type varMap map[string]varInfo
// FilterTree is the result of parsing the filter directive.
// Either you can have `Op and Children` on non-leaf nodes
// Or Func at leaf nodes.
type FilterTree struct {
Op string
Child []*FilterTree
Func *Function
}
// Arg stores an argument to a function.
type Arg struct {
Value string
IsValueVar bool // If argument is val(a)
IsGraphQLVar bool
}
// Function holds the information about gql functions.
type Function struct {
Attr string
Lang string // language of the attribute value
Name string // Specifies the name of the function.
Args []Arg // Contains the arguments of the function.
UID []uint64
NeedsVar []VarContext // If the function requires some variable
IsCount bool // gt(count(friends),0)
IsValueVar bool // eq(val(s), 5)
}
// filterOpPrecedence is a map from filterOp (a string) to its precedence.
var filterOpPrecedence = map[string]int{
"not": 3,
"and": 2,
"or": 1,
}
var mathOpPrecedence = map[string]int{
"u-": 500,
"floor": 105,
"ceil": 104,
"since": 103,
"exp": 100,
"ln": 99,
"sqrt": 98,
"cond": 90,
"pow": 89,
"logbase": 88,
"max": 85,
"min": 84,
"/": 50,
"*": 49,
"%": 48,
"-": 47,
"+": 46,
"<": 10,
">": 9,
"<=": 8,
">=": 7,
"==": 6,
"!=": 5,
}
// IsAggregator returns true if the function name is an aggregation function.
func (f *Function) IsAggregator() bool {
return isAggregator(f.Name)
}
// IsPasswordVerifier returns true if the function name is "checkpwd".
func (f *Function) IsPasswordVerifier() bool {
return f.Name == "checkpwd"
}
// DebugPrint is useful for debugging.
func (gq *GraphQuery) DebugPrint(prefix string) {
glog.Infof("%s[%x %q %q]\n", prefix, gq.UID, gq.Attr, gq.Alias)
for _, c := range gq.Children {
c.DebugPrint(prefix + "|->")
}
}
func (gq *GraphQuery) isFragment() bool {
return gq.fragment != ""
}
func (fn *fragmentNode) expand(fmap fragmentMap) error {
if fn.Exited {
// This fragment node has already been expanded.
return nil
}
if fn.Entered {
return errors.Errorf("Cycle detected: %s", fn.Name)
}
fn.Entered = true
if err := fn.Gq.expandFragments(fmap); err != nil {
return err
}
fn.Exited = true
return nil
}
func (gq *GraphQuery) expandFragments(fmap fragmentMap) error {
// We have to make a copy of children to preserve order and replace
// fragment references with fragment content. The copy is newChildren.
var newChildren []*GraphQuery
// Expand non-fragments. Do not append to gq.Children.
for _, child := range gq.Children {
if child.isFragment() {
fname := child.fragment // Name of fragment being referenced.
fchild := fmap[fname]
if fchild == nil {
return errors.Errorf("Missing fragment: %s", fname)
}
if err := fchild.expand(fmap); err != nil {
return err
}
newChildren = append(newChildren, fchild.Gq.Children...)
} else {
if err := child.expandFragments(fmap); err != nil {
return err
}
newChildren = append(newChildren, child)
}
}
gq.Children = newChildren
return nil
}
func convertToVarMap(variables map[string]string) (vm varMap) {
vm = make(map[string]varInfo)
for k, v := range variables {
vm[k] = varInfo{
Value: v,
}
}
return vm
}
// Request stores the query text and the variable mapping.
type Request struct {
Str string
Variables map[string]string
}
func checkValueType(vm varMap) error {
for k, v := range vm {
typ := v.Type
if len(typ) == 0 {
return errors.Errorf("Type of variable %v not specified", k)
}
// Ensure value is not nil if the variable is required.
if typ[len(typ)-1] == '!' {
if v.Value == "" {
return errors.Errorf("Variable %v should be initialised", k)
}
typ = typ[:len(typ)-1]
}
// Type check the values.
if v.Value != "" {
switch typ {
case "int":
{
if _, err := strconv.ParseInt(v.Value, 0, 64); err != nil {
return errors.Wrapf(err, "Expected an int but got %v", v.Value)
}
}
case "float":
{
if _, err := strconv.ParseFloat(v.Value, 64); err != nil {
return errors.Wrapf(err, "Expected a float but got %v", v.Value)
}
}
case "bool":
{
if _, err := strconv.ParseBool(v.Value); err != nil {
return errors.Wrapf(err, "Expected a bool but got %v", v.Value)
}
}
case "string": // Value is a valid string. No checks required.
default:
return errors.Errorf("Type %q not supported", typ)
}
}
}
return nil
}
func substituteVar(f string, res *string, vmap varMap) error {
if len(f) > 0 && f[0] == '$' {
va, ok := vmap[f]
if !ok || va.Type == "" {
return errors.Errorf("Variable not defined %v", f)
}
*res = va.Value
}
return nil
}
func substituteVariables(gq *GraphQuery, vmap varMap) error {
for k, v := range gq.Args {
// v won't be empty as its handled in parseGqlVariables.
val := gq.Args[k]
if err := substituteVar(v, &val, vmap); err != nil {
return err
}
gq.Args[k] = val
}
idVal, ok := gq.Args["id"]
if ok && len(gq.UID) == 0 {
if idVal == "" {
return errors.Errorf("Id can't be empty")
}
uids, err := parseID(idVal)
if err != nil {
return err
}
gq.UID = append(gq.UID, uids...)
// Deleting it here because we don't need to fill it in query.go.
delete(gq.Args, "id")
}
if gq.Func != nil {
if err := substituteVar(gq.Func.Attr, &gq.Func.Attr, vmap); err != nil {
return err
}
for idx, v := range gq.Func.Args {
if !v.IsGraphQLVar {
continue
}
if err := substituteVar(v.Value, &gq.Func.Args[idx].Value, vmap); err != nil {
return err
}
if gq.Func.Name == "regexp" {
// Value should have been populated from the map that the user gave us in the
// GraphQL variable map. Let's parse the expression and flags from the variable
// string.
ra, err := parseRegexArgs(gq.Func.Args[idx].Value)
if err != nil {
return err
}
// We modify the value of this arg and add a new arg for the flags. Regex functions
// should have two args.
gq.Func.Args[idx].Value = ra.expr
gq.Func.Args = append(gq.Func.Args, Arg{Value: ra.flags})
}
}
}
for _, child := range gq.Children {
if err := substituteVariables(child, vmap); err != nil {
return err
}
}
if gq.Filter != nil {
if err := substituteVariablesFilter(gq.Filter, vmap); err != nil {
return err
}
}
return nil
}
func substituteVariablesFilter(f *FilterTree, vmap varMap) error {
if f.Func != nil {
if err := substituteVar(f.Func.Attr, &f.Func.Attr, vmap); err != nil {
return err
}
for idx, v := range f.Func.Args {
if f.Func.Name == uid {
// This is to support GraphQL variables in uid functions.
idVal, ok := vmap[v.Value]
if !ok {
return errors.Errorf("Couldn't find value for GraphQL variable: [%s]", v.Value)
}
if idVal.Value == "" {
return errors.Errorf("Id can't be empty")
}
uids, err := parseID(idVal.Value)
if err != nil {
return err
}
f.Func.UID = append(f.Func.UID, uids...)
continue
}
if err := substituteVar(v.Value, &f.Func.Args[idx].Value, vmap); err != nil {
return err
}
}
}
for _, fChild := range f.Child {
if err := substituteVariablesFilter(fChild, vmap); err != nil {
return err
}
}
return nil
}
// Vars struct contains the list of variables defined and used by a
// query block.
type Vars struct {
Defines []string
Needs []string
}
// Result struct contains the Query list, its corresponding variable use list
// and the mutation block.
type Result struct {
Query []*GraphQuery
QueryVars []*Vars
Schema *pb.SchemaRequest
}
// Parse initializes and runs the lexer. It also constructs the GraphQuery subgraph
// from the lexed items.
func Parse(r Request) (Result, error) {
return ParseWithNeedVars(r, nil)
}
// ParseWithNeedVars performs parsing of a query with given needVars.
//
// The needVars parameter is passed in the case of upsert block.
// For example, when parsing the query block inside -
// upsert {
// query {
// me(func: eq(email, "someone@gmail.com"), first: 1) {
// v as uid
// }
// }
//
// mutation {
// set {
// uid(v) <name> "Some One" .
// uid(v) <email> "someone@gmail.com" .
// }
// }
// }
//
// The variable name v needs to be passed through the needVars parameter. Otherwise, an error
// is reported complaining that the variable v is defined but not used in the query block.
func ParseWithNeedVars(r Request, needVars []string) (res Result, rerr error) {
query := r.Str
vmap := convertToVarMap(r.Variables)
lexer := lex.NewLexer(query)
lexer.Run(lexTopLevel)
if err := lexer.ValidateResult(); err != nil {
return res, err
}
var qu *GraphQuery
it := lexer.NewIterator()
fmap := make(fragmentMap)
for it.Next() {
item := it.Item()
switch item.Typ {
case itemOpType:
if item.Val == "mutation" {
return res, item.Errorf("Mutation block no longer allowed.")
}
if item.Val == "schema" {
if res.Schema != nil {
return res, item.Errorf("Only one schema block allowed ")
}
if res.Query != nil {
return res, item.Errorf("Schema block is not allowed with query block")
}
if res.Schema, rerr = getSchema(it); rerr != nil {
return res, rerr
}
} else if item.Val == "fragment" {
// TODO(jchiu0): This is to be done in ParseSchema once it is ready.
fnode, rerr := getFragment(it)
if rerr != nil {
return res, rerr
}
fmap[fnode.Name] = fnode
} else if item.Val == "query" {
if res.Schema != nil {
return res, item.Errorf("Schema block is not allowed with query block")
}
if qu, rerr = getVariablesAndQuery(it, vmap); rerr != nil {
return res, rerr
}
res.Query = append(res.Query, qu)
}
case itemLeftCurl:
if qu, rerr = getQuery(it); rerr != nil {
return res, rerr
}
res.Query = append(res.Query, qu)
case itemName:
it.Prev()
if qu, rerr = getQuery(it); rerr != nil {
return res, rerr
}
res.Query = append(res.Query, qu)
}
}
if len(res.Query) != 0 {
res.QueryVars = make([]*Vars, 0, len(res.Query))
for i := 0; i < len(res.Query); i++ {
qu := res.Query[i]
// Try expanding fragments using fragment map.
if err := qu.expandFragments(fmap); err != nil {
return res, err
}
// Substitute all variables with corresponding values
if err := substituteVariables(qu, vmap); err != nil {
return res, err
}
res.QueryVars = append(res.QueryVars, &Vars{})
// Collect vars used and defined in Result struct.
qu.collectVars(res.QueryVars[i])
}
allVars := res.QueryVars
// Add the variables that are needed outside the query block.
// For example, mutation block in upsert block will be using
// variables from the query block that is getting parsed here.
if len(needVars) != 0 {
allVars = append(allVars, &Vars{Needs: needVars})
}
if err := checkDependency(allVars); err != nil {
return res, err
}
}
if err := validateResult(&res); err != nil {
return res, err
}
return res, nil
}
func validateResult(res *Result) error {
seenQueryAliases := make(map[string]bool)
for _, q := range res.Query {
if q.Alias == "var" || q.Alias == "shortest" {
continue
}
if _, found := seenQueryAliases[q.Alias]; found {
return errors.Errorf("Duplicate aliases not allowed: %v", q.Alias)
}
seenQueryAliases[q.Alias] = true
}
return nil
}
func flatten(vl []*Vars) (needs []string, defines []string) {
needs, defines = make([]string, 0, 10), make([]string, 0, 10)
for _, it := range vl {
needs = append(needs, it.Needs...)
defines = append(defines, it.Defines...)
}
return
}
func checkDependency(vl []*Vars) error {
needs, defines := flatten(vl)
needs = x.RemoveDuplicates(needs)
lenBefore := len(defines)
defines = x.RemoveDuplicates(defines)
if len(defines) != lenBefore {
return errors.Errorf("Some variables are declared multiple times.")
}
if len(defines) > len(needs) {
return errors.Errorf("Some variables are defined but not used\nDefined:%v\nUsed:%v\n",
defines, needs)
}
if len(defines) < len(needs) {
return errors.Errorf("Some variables are used but not defined\nDefined:%v\nUsed:%v\n",
defines, needs)
}
for i := 0; i < len(defines); i++ {
if defines[i] != needs[i] {
return errors.Errorf("Variables are not used properly. \nDefined:%v\nUsed:%v\n",
defines, needs)
}
}
return nil
}
func (gq *GraphQuery) collectVars(v *Vars) {
if gq.Var != "" {
v.Defines = append(v.Defines, gq.Var)
}
if gq.FacetVar != nil {
for _, va := range gq.FacetVar {
v.Defines = append(v.Defines, va)
}
}
for _, va := range gq.NeedsVar {
v.Needs = append(v.Needs, va.Name)
}
for _, ch := range gq.Children {
ch.collectVars(v)
}
if gq.Filter != nil {
gq.Filter.collectVars(v)
}
if gq.MathExp != nil {
gq.MathExp.collectVars(v)
}
shortestPathFrom := gq.ShortestPathArgs.From
if shortestPathFrom != nil && len(shortestPathFrom.NeedsVar) > 0 {
v.Needs = append(v.Needs, shortestPathFrom.NeedsVar[0].Name)
}
shortestPathTo := gq.ShortestPathArgs.To
if shortestPathTo != nil && len(shortestPathTo.NeedsVar) > 0 {
v.Needs = append(v.Needs, shortestPathTo.NeedsVar[0].Name)
}
}
func (f *MathTree) collectVars(v *Vars) {
if f == nil {
return
}
if f.Var != "" {
v.Needs = append(v.Needs, f.Var)
return
}
for _, fch := range f.Child {
fch.collectVars(v)
}
}
func (f *FilterTree) collectVars(v *Vars) {
if f.Func != nil {
for _, va := range f.Func.NeedsVar {
v.Needs = append(v.Needs, va.Name)
}
}
for _, fch := range f.Child {
fch.collectVars(v)
}
}
func (f *FilterTree) hasVars() bool {
if (f.Func != nil) && (len(f.Func.NeedsVar) > 0) {
return true
}
for _, fch := range f.Child {
if fch.hasVars() {
return true
}
}
return false
}
// getVariablesAndQuery checks if the query has a variable list and stores it in
// vmap. For variable list to be present, the query should have a name which is
// also checked for. It also calls getQuery to create the GraphQuery object tree.
func getVariablesAndQuery(it *lex.ItemIterator, vmap varMap) (gq *GraphQuery, rerr error) {
var name string
L2:
for it.Next() {
item := it.Item()
switch item.Typ {
case itemName:
if name != "" {
return nil, item.Errorf("Multiple word query name not allowed.")
}
name = item.Val
case itemLeftRound:
if name == "" {
return nil, item.Errorf("Variables can be defined only in named queries.")
}
if rerr = parseGqlVariables(it, vmap); rerr != nil {
return nil, rerr
}
if rerr = checkValueType(vmap); rerr != nil {
return nil, rerr
}
case itemLeftCurl:
if gq, rerr = getQuery(it); rerr != nil {
return nil, rerr
}
break L2
}
}
return gq, nil
}
func parseRecurseArgs(it *lex.ItemIterator, gq *GraphQuery) error {
if ok := trySkipItemTyp(it, itemLeftRound); !ok {
// We don't have a (, we can return.
return nil
}
var key, val string
var ok bool
for it.Next() {
item := it.Item()
if item.Typ != itemName {
return item.Errorf("Expected key inside @recurse()")
}
key = strings.ToLower(item.Val)
if ok := trySkipItemTyp(it, itemColon); !ok {
return it.Errorf("Expected colon(:) after %s", key)
}
if item, ok = tryParseItemType(it, itemName); !ok {
return item.Errorf("Expected value inside @recurse() for key: %s", key)
}
val = item.Val
switch key {
case "depth":
depth, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return err
}
gq.RecurseArgs.Depth = depth
case "loop":
allowLoop, err := strconv.ParseBool(val)
if err != nil {
return err
}
gq.RecurseArgs.AllowLoop = allowLoop
default:
return item.Errorf("Unexpected key: [%s] inside @recurse block", key)
}
if _, ok := tryParseItemType(it, itemRightRound); ok {
return nil
}
if _, ok := tryParseItemType(it, itemComma); !ok {
return it.Errorf("Expected comma after value: %s inside recurse block", val)
}
}
return nil
}
// getQuery creates a GraphQuery object tree by calling getRoot
// and goDeep functions by looking at '{'.
func getQuery(it *lex.ItemIterator) (gq *GraphQuery, rerr error) {
// First, get the root
gq, rerr = getRoot(it)
if rerr != nil {
return nil, rerr
}
var seenFilter bool
L:
// Recurse to deeper levels through godeep.
if !it.Next() {
return nil, it.Errorf("Expecting more lexer items while parsing query")
}
item := it.Item()
if item.Typ == itemLeftCurl {
if rerr = godeep(it, gq); rerr != nil {
return nil, rerr
}
} else if item.Typ == itemAt {
it.Next()
item := it.Item()
if item.Typ == itemName {
switch strings.ToLower(item.Val) {
case "filter":
if seenFilter {
return nil, item.Errorf("Repeated filter at root")
}
seenFilter = true
filter, err := parseFilter(it)
if err != nil {
return nil, err
}
gq.Filter = filter
case "normalize":
gq.Normalize = true
case "cascade":
gq.Cascade = true
case "groupby":
gq.IsGroupby = true
if err := parseGroupby(it, gq); err != nil {
return nil, err
}
case "ignorereflex":
gq.IgnoreReflex = true
case "recurse":
gq.Recurse = true
if err := parseRecurseArgs(it, gq); err != nil {
return nil, err
}
default:
return nil, item.Errorf("Unknown directive [%s]", item.Val)
}
goto L
}
} else if item.Typ == itemRightCurl {
// Do nothing.
} else if item.Typ == itemName {
it.Prev()
return gq, nil
} else {
return nil, item.Errorf("Malformed Query. Missing {. Got %v", item.Val)
}
return gq, nil
}
// getFragment parses a fragment definition (not reference).
func getFragment(it *lex.ItemIterator) (*fragmentNode, error) {
var name string
for it.Next() {
item := it.Item()
if item.Typ == itemName {
v := strings.TrimSpace(item.Val)
if len(v) > 0 && name == "" {
// Currently, we take the first nontrivial token as the
// fragment name and ignore everything after that until we see
// a left curl.
name = v
}
} else if item.Typ == itemLeftCurl {
break
} else {
return nil, item.Errorf("Unexpected item in fragment: %v %v", item.Typ, item.Val)
}
}
if name == "" {
return nil, it.Errorf("Empty fragment name")
}
gq := &GraphQuery{
Args: make(map[string]string),
}
if err := godeep(it, gq); err != nil {
return nil, err
}
fn := &fragmentNode{
Name: name,
Gq: gq,
}
return fn, nil
}
// parses till rightSquare is found (parses [a, b]) excluding leftSquare
// This function can be reused for query later
func parseListItemNames(it *lex.ItemIterator) ([]string, error) {
var items []string
for it.Next() {
item := it.Item()
switch item.Typ {
case itemRightSquare:
return items, nil
case itemName:
val := collectName(it, item.Val)
items = append(items, val)
case itemComma:
it.Next()
item = it.Item()
if item.Typ != itemName {
return items, item.Errorf("Invalid scheam block")
}
val := collectName(it, item.Val)
items = append(items, val)
default:
return items, item.Errorf("Invalid schema block")
}
}
return items, it.Errorf("Expecting ] to end list but none was found")
}
// parseSchemaPredsOrTypes parses till rightround is found
func parseSchemaPredsOrTypes(it *lex.ItemIterator, s *pb.SchemaRequest) error {
// pred or type should be followed by colon
it.Next()
item := it.Item()
if item.Typ != itemName && !(item.Val == "pred" || item.Val == "type") {
return item.Errorf("Invalid schema block")
}
parseTypes := false
if item.Val == "type" {
parseTypes = true
}
it.Next()
item = it.Item()
if item.Typ != itemColon {
return item.Errorf("Invalid schema block")
}
// can be a or [a,b]
it.Next()
item = it.Item()
if item.Typ == itemName {
if parseTypes {
s.Types = append(s.Types, item.Val)
} else {
s.Predicates = append(s.Predicates, item.Val)
}
} else if item.Typ == itemLeftSquare {
names, err := parseListItemNames(it)
if err != nil {
return err
}
if parseTypes {
s.Types = names
} else {
s.Predicates = names
}
} else {
return item.Errorf("Invalid schema block")
}
it.Next()
item = it.Item()
if item.Typ == itemRightRound {
return nil
}
return item.Errorf("Invalid schema blocks")
}
// parses till rightcurl is found
func parseSchemaFields(it *lex.ItemIterator, s *pb.SchemaRequest) error {
for it.Next() {
item := it.Item()
switch item.Typ {
case itemRightCurl:
return nil
case itemName:
s.Fields = append(s.Fields, item.Val)
default:
return item.Errorf("Invalid schema block.")
}
}
return it.Errorf("Expecting } to end fields list, but none was found")