-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
query.go
2737 lines (2481 loc) · 72.1 KB
/
query.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 query
import (
"context"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/glog"
otrace "go.opencensus.io/trace"
"google.golang.org/grpc/metadata"
"github.com/dgraph-io/dgo/protos/api"
"github.com/dgraph-io/dgraph/algo"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/task"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/types/facets"
"github.com/dgraph-io/dgraph/worker"
"github.com/dgraph-io/dgraph/x"
)
const (
FacetDelimeter = "|"
)
/*
* QUERY:
* Let's take this query from GraphQL as example:
* {
* me {
* id
* firstName
* lastName
* birthday {
* month
* day
* }
* friends {
* name
* }
* }
* }
*
* REPRESENTATION:
* This would be represented in SubGraph format pb.y, as such:
* SubGraph [result uid = me]
* |
* Children
* |
* --> SubGraph [Attr = "xid"]
* --> SubGraph [Attr = "firstName"]
* --> SubGraph [Attr = "lastName"]
* --> SubGraph [Attr = "birthday"]
* |
* Children
* |
* --> SubGraph [Attr = "month"]
* --> SubGraph [Attr = "day"]
* --> SubGraph [Attr = "friends"]
* |
* Children
* |
* --> SubGraph [Attr = "name"]
*
* ALGORITHM:
* This is a rough and simple algorithm of how to process this SubGraph query
* and populate the results:
*
* For a given entity, a new SubGraph can be started off with NewGraph(id).
* Given a SubGraph, is the Query field empty? [Step a]
* - If no, run (or send it to server serving the attribute) query
* and populate result.
* Iterate over children and copy Result Uids to child Query Uids.
* Set Attr. Then for each child, use goroutine to run Step:a.
* Wait for goroutines to finish.
* Return errors, if any.
*/
// Latency is used to keep track of the latency involved in parsing and processing
// the query. It also contains information about the time it took to convert the
// result into a format(JSON/Protocol Buffer) that the client expects.
type Latency struct {
Start time.Time `json:"-"`
Parsing time.Duration `json:"query_parsing"`
Processing time.Duration `json:"processing"`
Json time.Duration `json:"json_conversion"`
}
type params struct {
Alias string
Count int
Offset int
AfterUID uint64
DoCount bool
GetUid bool
Order []*pb.Order
Var string
NeedsVar []gql.VarContext
ParentVars map[string]varValue
FacetVar map[string]string
uidToVal map[uint64]types.Val
Langs []string
// directives.
Normalize bool
Recurse bool
RecurseArgs gql.RecurseArgs
Cascade bool
IgnoreReflex bool
From uint64
To uint64
Facet *pb.FacetParams
FacetOrder string
FacetOrderDesc bool
ExploreDepth uint64
MaxWeight float64
MinWeight float64
isInternal bool // Determines if processTask has to be called or not.
ignoreResult bool // Node results are ignored.
Expand string // Value is either _all_/variable-name or empty.
isGroupBy bool
groupbyAttrs []gql.GroupByAttr
uidCount bool
uidCountAlias string
numPaths int
parentIds []uint64 // This is a stack that is maintained and passed down to children.
IsEmpty bool // Won't have any SrcUids or DestUids. Only used to get aggregated vars
expandAll bool // expand all languages
shortest bool
}
type pathMetadata struct {
weight float64 // Total weight of the path.
}
// Function holds the information about gql functions.
type Function struct {
Name string // Specifies the name of the function.
Args []gql.Arg // Contains the arguments of the function.
IsCount bool // gt(count(friends),0)
IsValueVar bool // eq(val(s), 10)
}
// SubGraph is the way to represent data pb.y. It contains both the
// query and the response. Once generated, this can then be encoded to other
// client convenient formats, like GraphQL / JSON.
type SubGraph struct {
ReadTs uint64
Attr string
Params params
counts []uint32
valueMatrix []*pb.ValueList
uidMatrix []*pb.List
facetsMatrix []*pb.FacetsList
ExpandPreds []*pb.ValueList
GroupbyRes []*groupResults // one result for each uid list.
LangTags []*pb.LangList
// SrcUIDs is a list of unique source UIDs. They are always copies of destUIDs
// of parent nodes in GraphQL structure.
SrcUIDs *pb.List
SrcFunc *Function
FilterOp string
Filters []*SubGraph
facetsFilter *pb.FilterTree
MathExp *mathTree
Children []*SubGraph
// destUIDs is a list of destination UIDs, after applying filters, pagination.
DestUIDs *pb.List
List bool // whether predicate is of list type
pathMeta *pathMetadata
}
func (sg *SubGraph) recurse(set func(sg *SubGraph)) {
set(sg)
for _, child := range sg.Children {
child.recurse(set)
}
for _, filter := range sg.Filters {
filter.recurse(set)
}
}
func (sg *SubGraph) IsGroupBy() bool {
return sg.Params.isGroupBy
}
func (sg *SubGraph) IsInternal() bool {
return sg.Params.isInternal
}
func (sg *SubGraph) createSrcFunction(gf *gql.Function) {
if gf == nil {
return
}
// type function is just an alias for eq("type", type).
if gf.Name == "type" {
sg.Attr = "type"
sg.SrcFunc = &Function{
Name: "eq",
Args: append(gf.Args[:0:0], gf.Args...),
IsCount: false,
IsValueVar: false,
}
return
}
sg.SrcFunc = &Function{
Name: gf.Name,
Args: append(gf.Args[:0:0], gf.Args...),
IsCount: gf.IsCount,
IsValueVar: gf.IsValueVar,
}
if gf.Lang != "" {
sg.Params.Langs = append(sg.Params.Langs, gf.Lang)
}
}
// DebugPrint prints out the SubGraph tree in a nice format for debugging purposes.
func (sg *SubGraph) DebugPrint(prefix string) {
var src, dst int
if sg.SrcUIDs != nil {
src = len(sg.SrcUIDs.Uids)
}
if sg.DestUIDs != nil {
dst = len(sg.DestUIDs.Uids)
}
glog.Infof("%s[%q Alias:%q Func:%v SrcSz:%v Op:%q DestSz:%v IsCount: %v ValueSz:%v]\n",
prefix, sg.Attr, sg.Params.Alias, sg.SrcFunc, src, sg.FilterOp,
dst, sg.Params.DoCount, len(sg.valueMatrix))
for _, f := range sg.Filters {
f.DebugPrint(prefix + "|-f->")
}
for _, c := range sg.Children {
c.DebugPrint(prefix + "|->")
}
}
// getValue gets the value from the task.
func getValue(tv *pb.TaskValue) (types.Val, error) {
vID := types.TypeID(tv.ValType)
val := types.ValueForType(vID)
val.Value = tv.Val
return val, nil
}
var (
ErrEmptyVal = errors.New("Query: harmless error, e.g. task.Val is nil")
ErrWrongAgg = errors.New("Wrong level for var aggregation")
)
func (sg *SubGraph) isSimilar(ssg *SubGraph) bool {
if sg.Attr != ssg.Attr {
return false
}
if len(sg.Params.Langs) != len(ssg.Params.Langs) {
return false
}
for i := 0; i < len(sg.Params.Langs) && i < len(ssg.Params.Langs); i++ {
if sg.Params.Langs[i] != ssg.Params.Langs[i] {
return false
}
}
if sg.Params.DoCount {
return ssg.Params.DoCount
}
if ssg.Params.DoCount {
return false
}
if sg.SrcFunc != nil {
if ssg.SrcFunc != nil && sg.SrcFunc.Name == ssg.SrcFunc.Name {
return true
}
return false
}
return true
}
func (sg *SubGraph) fieldName() string {
fieldName := sg.Attr
if sg.Params.Alias != "" {
fieldName = sg.Params.Alias
}
return fieldName
}
func addCount(pc *SubGraph, count uint64, dst outputNode) {
if pc.Params.Normalize && pc.Params.Alias == "" {
return
}
c := types.ValueForType(types.IntID)
c.Value = int64(count)
fieldName := pc.Params.Alias
if fieldName == "" {
fieldName = fmt.Sprintf("count(%s)", pc.Attr)
}
dst.AddValue(fieldName, c)
}
func aggWithVarFieldName(pc *SubGraph) string {
if pc.Params.Alias != "" {
return pc.Params.Alias
}
fieldName := fmt.Sprintf("val(%v)", pc.Params.Var)
if len(pc.Params.NeedsVar) > 0 {
fieldName = fmt.Sprintf("val(%v)", pc.Params.NeedsVar[0].Name)
if pc.SrcFunc != nil {
fieldName = fmt.Sprintf("%s(%v)", pc.SrcFunc.Name, fieldName)
}
}
return fieldName
}
func addInternalNode(pc *SubGraph, uid uint64, dst outputNode) error {
if len(pc.Params.uidToVal) == 0 {
return x.Errorf("Wrong use of var() with %v.", pc.Params.NeedsVar)
}
sv, ok := pc.Params.uidToVal[uid]
if !ok || sv.Value == nil {
return nil
}
fieldName := aggWithVarFieldName(pc)
dst.AddValue(fieldName, sv)
return nil
}
func addCheckPwd(pc *SubGraph, vals []*pb.TaskValue, dst outputNode) {
c := types.ValueForType(types.BoolID)
if len(vals) == 0 {
c.Value = false
} else {
c.Value = task.ToBool(vals[0])
}
fieldName := pc.Params.Alias
if fieldName == "" {
fieldName = fmt.Sprintf("checkpwd(%s)", pc.Attr)
}
dst.AddValue(fieldName, c)
}
func alreadySeen(parentIds []uint64, uid uint64) bool {
for _, id := range parentIds {
if id == uid {
return true
}
}
return false
}
func facetName(fieldName string, f *api.Facet) string {
if f.Alias != "" {
return f.Alias
}
return fieldName + FacetDelimeter + f.Key
}
// This method gets the values and children for a subprotos.
func (sg *SubGraph) preTraverse(uid uint64, dst outputNode) error {
if sg.Params.IgnoreReflex {
if alreadySeen(sg.Params.parentIds, uid) {
// A node can't have itself as the child at any level.
return nil
}
// Push myself to stack before sending this to children.
sg.Params.parentIds = append(sg.Params.parentIds, uid)
}
var invalidUids map[uint64]bool
// We go through all predicate children of the subprotos.
for _, pc := range sg.Children {
if pc.Params.ignoreResult {
continue
}
if pc.IsInternal() {
if pc.Params.Expand != "" {
continue
}
if pc.Params.Normalize && pc.Params.Alias == "" {
continue
}
if err := addInternalNode(pc, uid, dst); err != nil {
return err
}
continue
}
if len(pc.uidMatrix) == 0 {
// Can happen in recurse query.
continue
}
if len(pc.facetsMatrix) > 0 && len(pc.facetsMatrix) != len(pc.uidMatrix) {
return x.Errorf("Length of facetsMatrix and uidMatrix mismatch: %d vs %d",
len(pc.facetsMatrix), len(pc.uidMatrix))
}
idx := algo.IndexOf(pc.SrcUIDs, uid)
if idx < 0 {
continue
}
if pc.Params.isGroupBy {
if len(pc.GroupbyRes) <= idx {
return x.Errorf("Unexpected length while adding Groupby. Idx: [%v], len: [%v]",
idx, len(pc.GroupbyRes))
}
dst.addGroupby(pc, pc.GroupbyRes[idx], pc.fieldName())
continue
}
fieldName := pc.fieldName()
if len(pc.counts) > 0 {
addCount(pc, uint64(pc.counts[idx]), dst)
} else if pc.SrcFunc != nil && pc.SrcFunc.Name == "checkpwd" {
addCheckPwd(pc, pc.valueMatrix[idx].Values, dst)
} else if idx < len(pc.uidMatrix) && len(pc.uidMatrix[idx].Uids) > 0 {
var fcsList []*pb.Facets
if pc.Params.Facet != nil {
fcsList = pc.facetsMatrix[idx].FacetsList
}
if sg.Params.IgnoreReflex {
pc.Params.parentIds = sg.Params.parentIds
}
// We create as many predicate entity children as the length of uids for
// this predicate.
ul := pc.uidMatrix[idx]
for childIdx, childUID := range ul.Uids {
if fieldName == "" || (invalidUids != nil && invalidUids[childUID]) {
continue
}
uc := dst.New(fieldName)
if rerr := pc.preTraverse(childUID, uc); rerr != nil {
if rerr.Error() == "_INV_" {
if invalidUids == nil {
invalidUids = make(map[uint64]bool)
}
invalidUids[childUID] = true
continue // next UID.
}
// Some other error.
glog.Errorf("Error while traversal: %v", rerr)
return rerr
}
if pc.Params.Facet != nil && len(fcsList) > childIdx {
fs := fcsList[childIdx]
for _, f := range fs.Facets {
fVal, err := facets.ValFor(f)
if err != nil {
return err
}
uc.AddValue(facetName(fieldName, f), fVal)
}
}
if !uc.IsEmpty() {
if sg.Params.GetUid {
uc.SetUID(childUID, "uid")
}
if pc.List {
dst.AddListChild(fieldName, uc)
} else {
dst.AddMapChild(fieldName, uc, false)
}
}
}
if pc.Params.uidCount && !(pc.Params.uidCountAlias == "" && pc.Params.Normalize) {
uc := dst.New(fieldName)
c := types.ValueForType(types.IntID)
c.Value = int64(len(ul.Uids))
alias := pc.Params.uidCountAlias
if alias == "" {
alias = "count"
}
uc.AddValue(alias, c)
dst.AddListChild(fieldName, uc)
}
} else {
if pc.Params.Alias == "" && len(pc.Params.Langs) > 0 {
fieldName += "@"
fieldName += strings.Join(pc.Params.Langs, ":")
}
if pc.Attr == "uid" {
dst.SetUID(uid, pc.fieldName())
continue
}
if len(pc.facetsMatrix) > idx && len(pc.facetsMatrix[idx].FacetsList) > 0 {
// in case of Value we have only one Facets
for _, f := range pc.facetsMatrix[idx].FacetsList[0].Facets {
fVal, err := facets.ValFor(f)
if err != nil {
return err
}
dst.AddValue(facetName(fieldName, f), fVal)
}
}
if len(pc.valueMatrix) <= idx {
continue
}
for i, tv := range pc.valueMatrix[idx].Values {
// if conversion not possible, we ignore it in the result.
sv, convErr := convertWithBestEffort(tv, pc.Attr)
if convErr != nil {
return convErr
}
if pc.Params.expandAll && len(pc.LangTags[idx].Lang) != 0 {
if i >= len(pc.LangTags[idx].Lang) {
return x.Errorf(
"pb.error: all lang tags should be either present or absent")
}
fieldNameWithTag := fieldName
lang := pc.LangTags[idx].Lang[i]
if lang != "" {
fieldNameWithTag += "@" + lang
}
encodeAsList := pc.List && len(lang) == 0
dst.AddListValue(fieldNameWithTag, sv, encodeAsList)
continue
}
encodeAsList := pc.List && len(pc.Params.Langs) == 0
if !pc.Params.Normalize {
dst.AddListValue(fieldName, sv, encodeAsList)
continue
}
// If the query had the normalize directive, then we only add nodes
// with an Alias.
if pc.Params.Alias != "" {
dst.AddListValue(fieldName, sv, encodeAsList)
}
}
}
}
if sg.Params.IgnoreReflex && len(sg.Params.parentIds) > 0 {
// Lets pop the stack.
sg.Params.parentIds = (sg.Params.parentIds)[:len(sg.Params.parentIds)-1]
}
// Only for shortest path query we wan't to return uid always if there is
// nothing else at that level.
if (sg.Params.GetUid && !dst.IsEmpty()) || sg.Params.shortest {
dst.SetUID(uid, "uid")
}
if sg.pathMeta != nil {
totalWeight := types.Val{
Tid: types.FloatID,
Value: sg.pathMeta.weight,
}
dst.AddValue("_weight_", totalWeight)
}
return nil
}
// convert from task.Val to types.Value, based on schema appropriate type
// is already set in api.Value
func convertWithBestEffort(tv *pb.TaskValue, attr string) (types.Val, error) {
// value would be in binary format with appropriate type
v, _ := getValue(tv)
if !v.Tid.IsScalar() {
return v, x.Errorf("Leaf predicate:'%v' must be a scalar.", attr)
}
// creates appropriate type from binary format
sv, err := types.Convert(v, v.Tid)
x.Checkf(err, "Error while interpreting appropriate type from binary")
return sv, nil
}
func mathCopy(dst *mathTree, src *gql.MathTree) error {
// Either we'll have an operation specified, or the function specified.
dst.Const = src.Const
dst.Fn = src.Fn
dst.Val = src.Val
dst.Var = src.Var
for _, mc := range src.Child {
child := &mathTree{}
if err := mathCopy(child, mc); err != nil {
return err
}
dst.Child = append(dst.Child, child)
}
return nil
}
func filterCopy(sg *SubGraph, ft *gql.FilterTree) error {
// Either we'll have an operation specified, or the function specified.
if len(ft.Op) > 0 {
sg.FilterOp = ft.Op
} else {
sg.Attr = ft.Func.Attr
if !isValidFuncName(ft.Func.Name) {
return x.Errorf("Invalid function name : %s", ft.Func.Name)
}
if isUidFnWithoutVar(ft.Func) {
sg.SrcFunc = &Function{Name: ft.Func.Name}
if err := sg.populate(ft.Func.UID); err != nil {
return err
}
} else {
sg.createSrcFunction(ft.Func)
sg.Params.NeedsVar = append(sg.Params.NeedsVar, ft.Func.NeedsVar...)
}
}
for _, ftc := range ft.Child {
child := &SubGraph{}
if err := filterCopy(child, ftc); err != nil {
return err
}
sg.Filters = append(sg.Filters, child)
}
return nil
}
func uniqueKey(gchild *gql.GraphQuery) string {
key := gchild.Attr
if gchild.Func != nil {
key += fmt.Sprintf("%v", gchild.Func)
}
// This is the case when we ask for a variable.
if gchild.Attr == "val" {
// E.g. a as age, result is returned as var(a)
if gchild.Var != "" && gchild.Var != "val" {
key = fmt.Sprintf("val(%v)", gchild.Var)
} else if len(gchild.NeedsVar) > 0 {
// For var(s)
key = fmt.Sprintf("val(%v)", gchild.NeedsVar[0].Name)
}
// Could be min(var(x)) && max(var(x))
if gchild.Func != nil {
key += gchild.Func.Name
}
}
if gchild.IsCount { // ignore count subgraphs..
key += "count"
}
if len(gchild.Langs) > 0 {
key += fmt.Sprintf("%v", gchild.Langs)
}
if gchild.MathExp != nil {
// We would only be here if Alias is empty, so Var would be non
// empty because MathExp should have atleast one of them.
key = fmt.Sprintf("val(%+v)", gchild.Var)
}
if gchild.IsGroupby {
key += "groupby"
}
return key
}
func treeCopy(gq *gql.GraphQuery, sg *SubGraph) error {
// Typically you act on the current node, and leave recursion to deal with
// children. But, in this case, we don't want to muck with the current
// node, because of the way we're dealing with the root node.
// So, we work on the children, and then recurse for grand children.
attrsSeen := make(map[string]struct{})
for _, gchild := range gq.Children {
if sg.Params.Alias == "shortest" && gchild.Expand != "" {
return x.Errorf("expand() not allowed inside shortest")
}
key := ""
if gchild.Alias != "" {
key = gchild.Alias
} else {
key = uniqueKey(gchild)
}
if _, ok := attrsSeen[key]; ok {
return x.Errorf("%s not allowed multiple times in same sub-query.",
key)
}
attrsSeen[key] = struct{}{}
args := params{
Alias: gchild.Alias,
Cascade: sg.Params.Cascade,
Expand: gchild.Expand,
Facet: gchild.Facets,
FacetOrder: gchild.FacetOrder,
FacetOrderDesc: gchild.FacetDesc,
FacetVar: gchild.FacetVar,
GetUid: sg.Params.GetUid,
IgnoreReflex: sg.Params.IgnoreReflex,
Langs: gchild.Langs,
NeedsVar: append(gchild.NeedsVar[:0:0], gchild.NeedsVar...),
Normalize: sg.Params.Normalize,
Order: gchild.Order,
Var: gchild.Var,
groupbyAttrs: gchild.GroupbyAttrs,
isGroupBy: gchild.IsGroupby,
isInternal: gchild.IsInternal,
uidCount: gchild.UidCount,
uidCountAlias: gchild.UidCountAlias,
}
if gchild.IsCount {
if len(gchild.Children) != 0 {
return errors.New("Node with count cannot have child attributes")
}
args.DoCount = true
}
for argk := range gchild.Args {
if !isValidArg(argk) {
return x.Errorf("Invalid argument : %s", argk)
}
}
if err := args.fill(gchild); err != nil {
return err
}
if len(args.Order) != 0 && len(args.FacetOrder) != 0 {
return x.Errorf("Cannot specify order at both args and facets")
}
dst := &SubGraph{
Attr: gchild.Attr,
Params: args,
}
if gchild.MathExp != nil {
mathExp := &mathTree{}
if err := mathCopy(mathExp, gchild.MathExp); err != nil {
return err
}
dst.MathExp = mathExp
}
if gchild.Func != nil &&
(gchild.Func.IsAggregator() || gchild.Func.IsPasswordVerifier()) {
if len(gchild.Children) != 0 {
return x.Errorf("Node with %q cant have child attr", gchild.Func.Name)
}
// embedded filter will cause ambiguous output like following,
// director.film @filter(gt(initial_release_date, "2016")) {
// min(initial_release_date @filter(gt(initial_release_date, "1986"))
// }
if gchild.Filter != nil {
return x.Errorf(
"Node with %q cant have filter, please place the filter on the upper level",
gchild.Func.Name)
}
dst.createSrcFunction(gchild.Func)
}
if gchild.Filter != nil {
dstf := &SubGraph{}
if err := filterCopy(dstf, gchild.Filter); err != nil {
return err
}
dst.Filters = append(dst.Filters, dstf)
}
if gchild.FacetsFilter != nil {
facetsFilter, err := toFacetsFilter(gchild.FacetsFilter)
if err != nil {
return err
}
dst.facetsFilter = facetsFilter
}
sg.Children = append(sg.Children, dst)
if err := treeCopy(gchild, dst); err != nil {
return err
}
}
return nil
}
func (args *params) fill(gq *gql.GraphQuery) error {
if v, ok := gq.Args["offset"]; ok {
offset, err := strconv.ParseInt(v, 0, 32)
if err != nil {
return err
}
args.Offset = int(offset)
}
if v, ok := gq.Args["after"]; ok {
after, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return err
}
args.AfterUID = uint64(after)
}
if args.Alias == "shortest" {
if v, ok := gq.Args["depth"]; ok {
depth, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return err
}
args.ExploreDepth = depth
}
if v, ok := gq.Args["numpaths"]; ok {
numPaths, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return err
}
args.numPaths = int(numPaths)
}
if v, ok := gq.Args["from"]; ok {
from, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return err
}
args.From = uint64(from)
}
if v, ok := gq.Args["to"]; ok {
to, err := strconv.ParseUint(v, 0, 64)
if err != nil {
return err
}
args.To = uint64(to)
}
if v, ok := gq.Args["maxweight"]; ok {
maxWeight, err := strconv.ParseFloat(v, 64)
if err != nil {
return err
}
args.MaxWeight = maxWeight
} else if !ok {
args.MaxWeight = math.MaxFloat64
}
if v, ok := gq.Args["minweight"]; ok {
minWeight, err := strconv.ParseFloat(v, 64)
if err != nil {
return err
}
args.MinWeight = minWeight
} else if !ok {
args.MinWeight = -math.MaxFloat64
}
}
if v, ok := gq.Args["first"]; ok {
first, err := strconv.ParseInt(v, 0, 32)
if err != nil {
return err
}
args.Count = int(first)
}
return nil
}
// ToSubGraph converts the GraphQuery into the pb.SubGraph instance type.
func ToSubGraph(ctx context.Context, gq *gql.GraphQuery) (*SubGraph, error) {
sg, err := newGraph(ctx, gq)
if err != nil {
return nil, err
}
err = treeCopy(gq, sg)
if err != nil {
return nil, err
}
return sg, err
}
// ContextKey is used to set options in the context object.
type ContextKey int
const (
// DebugKey is the key used to toggle debug mode.
DebugKey ContextKey = iota
)
func isDebug(ctx context.Context) bool {
var debug bool
// gRPC client passes information about debug as metadata.
if md, ok := metadata.FromIncomingContext(ctx); ok {
// md is a map[string][]string
debug = len(md["debug"]) > 0 && md["debug"][0] == "true"
}
// HTTP passes information about debug as query parameter which is attached to context.
return debug || ctx.Value(DebugKey) == "true"
}
func (sg *SubGraph) populate(uids []uint64) error {
// Put sorted entries in matrix.
sort.Slice(uids, func(i, j int) bool { return uids[i] < uids[j] })
sg.uidMatrix = []*pb.List{{Uids: uids}}
// User specified list may not be sorted.
sg.SrcUIDs = &pb.List{Uids: uids}
return nil
}
// newGraph returns the SubGraph and its task query.
func newGraph(ctx context.Context, gq *gql.GraphQuery) (*SubGraph, error) {
// This would set the Result field in SubGraph,
// and populate the children for attributes.
// For the root, the name to be used in result is stored in Alias, not Attr.
// The attr at root (if present) would stand for the source functions attr.
args := params{
Alias: gq.Alias,
Cascade: gq.Cascade,
GetUid: isDebug(ctx),
IgnoreReflex: gq.IgnoreReflex,
IsEmpty: gq.IsEmpty,
Langs: gq.Langs,
NeedsVar: append(gq.NeedsVar[:0:0], gq.NeedsVar...),
Normalize: gq.Normalize,
Order: gq.Order,
ParentVars: make(map[string]varValue),
Recurse: gq.Recurse,
RecurseArgs: gq.RecurseArgs,
Var: gq.Var,
groupbyAttrs: gq.GroupbyAttrs,
isGroupBy: gq.IsGroupby,
uidCount: gq.UidCount,
uidCountAlias: gq.UidCountAlias,
}
for argk := range gq.Args {
if !isValidArg(argk) {
return nil, x.Errorf("Invalid argument : %s", argk)
}
}
if err := args.fill(gq); err != nil {
return nil, err
}
sg := &SubGraph{Params: args}
if gq.Func != nil {
// Uid function doesnt have Attr. It just has a list of ids
if gq.Func.Attr != "uid" {
sg.Attr = gq.Func.Attr
}
if !isValidFuncName(gq.Func.Name) {
return nil, x.Errorf("Invalid function name : %s", gq.Func.Name)
}
sg.createSrcFunction(gq.Func)
}
if isUidFnWithoutVar(gq.Func) && len(gq.UID) > 0 {
if err := sg.populate(gq.UID); err != nil {
return nil, err
}
}
// Copy roots filter.
if gq.Filter != nil {
sgf := &SubGraph{}
if err := filterCopy(sgf, gq.Filter); err != nil {
return nil, err
}
sg.Filters = append(sg.Filters, sgf)
}
if gq.FacetsFilter != nil {
facetsFilter, err := toFacetsFilter(gq.FacetsFilter)
if err != nil {
return nil, err