-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
query.go
2735 lines (2489 loc) · 78.6 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"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/glog"
"github.com/pkg/errors"
otrace "go.opencensus.io/trace"
"google.golang.org/grpc/metadata"
"github.com/dgraph-io/dgo/v2/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/schema"
"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"
)
/*
* 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"`
AssignTimestamp time.Duration `json:"assign_timestamp"`
Processing time.Duration `json:"processing"`
Json time.Duration `json:"json_conversion"`
}
// params contains the list of parameters required to execute a SubGraph.
type params struct {
// Alias is the value of the predicate's alias, if any.
Alias string
// Count is the value of "first" parameter in the query.
Count int
// Offset is the value of the "offset" parameter.
Offset int
// AfterUID is the value of the "after" parameter.
AfterUID uint64
// DoCount is true if the count of the predicate is requested instead of its value.
DoCount bool
// GetUid is true if the uid should be returned. Used for debug requests.
GetUid bool
// Order is the list of predicates to sort by and their sort order.
Order []*pb.Order
// Langs is the list of languages and their preferred order for looking up a predicate value.
Langs []string
// Facet tells us about the requested facets and their aliases.
Facet *pb.FacetParams
// FacetOrder has the name of the facet by which the results should be sorted.
FacetOrder string
// FacetOrderDesc is true if the facets should be order in descending order. If it's
// false, the facets will be ordered in ascending order.
FacetOrderDesc bool
// Var is the name of the variable defined in this SubGraph
// (e.g. in "x as name", this would be x).
Var string
// FacetVar is a map of predicate to the facet variable alias
// for e.g. @facets(L1 as weight) the map would be { "weight": "L1" }
FacetVar map[string]string
// NeedsVar is the list of variables required by this SubGraph along with their type.
NeedsVar []gql.VarContext
// ParentVars is a map of variables passed down recursively to children of a SubGraph in a query
// block. These are used to filter uids defined in a parent using a variable.
// TODO (pawan) - This can potentially be simplified to a map[string]*pb.List since we don't
// support reading from value variables defined in the parent and other fields that are part
// of varValue.
ParentVars map[string]varValue
// UidToVal is the mapping of uid to values. This is populated into a SubGraph from a value
// variable that is part of req.Vars. This value variable would have been defined
// in some other query.
UidToVal map[uint64]types.Val
// Normalize is true if the @normalize directive is specified.
Normalize bool
// Recurse is true if the @recurse directive is specified.
Recurse bool
// RecurseArgs stores the arguments passed to the @recurse directive.
RecurseArgs gql.RecurseArgs
// Cascade is true if the @cascade directive is specified.
Cascade bool
// IgnoreReflex is true if the @ignorereflex directive is specified.
IgnoreReflex bool
// ShortestPathArgs contains the from and to functions to execute a shortest path query.
ShortestPathArgs gql.ShortestPathArgs
// From is the node from which to run the shortest path algorithm.
From uint64
// To is the destination node of the shortest path algorithm
To uint64
// NumPaths is used for k-shortest path query to specify number of paths to return.
NumPaths int
// MaxWeight is the max weight allowed in a path returned by the shortest path algorithm.
MaxWeight float64
// MinWeight is the min weight allowed in a path returned by the shortest path algorithm.
MinWeight float64
// ExploreDepth is used by recurse and shortest path queries to specify the maximum graph
// depth to explore.
ExploreDepth uint64
// IsInternal determines if processTask has to be called or not.
IsInternal bool
// IgnoreResult is true if the node results are to be ignored.
IgnoreResult bool
// Expand holds the argument passed to the expand function.
Expand string
// IsGroupBy is true if @groupby is specified.
IsGroupBy bool // True if @groupby is specified.
// GroupbyAttrs holds the list of attributes to group by.
GroupbyAttrs []gql.GroupByAttr
// ParentIds is a stack that is maintained and passed down to children.
ParentIds []uint64
// IsEmpty is true if the subgraph doesn't have any SrcUids or DestUids.
// Only used to get aggregated vars
IsEmpty bool
// ExpandAll is true if all the language values should be expanded.
ExpandAll bool
// Shortest is true when the subgraph holds the results of a shortest paths query.
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)
IsLenVar bool // eq(len(s), 10)
}
// SubGraph is the way to represent data. It contains both the request parameters and the response.
// Once generated, this can then be encoded to other client convenient formats, like GraphQL / JSON.
type SubGraph struct {
ReadTs uint64
Cache int
Attr string
UnknownAttr bool
// read only parameters which are populated before the execution of the query and are used to
// execute this query.
Params params
// count stores the count of an edge (predicate). There would be one value corresponding to each
// uid in SrcUIDs.
counts []uint32
// valueMatrix is a slice of ValueList. If this SubGraph is for a scalar predicate type, then
// there would be one list for each uid in SrcUIDs storing the value of the predicate.
// The individual elements of the slice are a ValueList because we support scalar predicates
// of list type. For non-list type scalar predicates, there would be only one value in every
// ValueList.
valueMatrix []*pb.ValueList
// uidMatrix is a slice of List. There would be one List corresponding to each uid in SrcUIDs.
// In graph terms, a list is a slice of outgoing edges from a node.
uidMatrix []*pb.List
// facetsMatrix contains the facet values. There would a list corresponding to each uid in
// uidMatrix.
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 specified using func. Should only be non-nil at root. At other levels,
// filters are used.
SrcFunc *Function
FilterOp string
Filters []*SubGraph // List of filters specified at the current node.
facetsFilter *pb.FilterTree
MathExp *mathTree
Children []*SubGraph // children of the current node, should be empty for leaf nodes.
// 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)
}
}
// IsGroupBy returns whether this subgraph is part of a groupBy query.
func (sg *SubGraph) IsGroupBy() bool {
return sg.Params.IsGroupBy
}
// IsInternal returns whether this subgraph is marked as internal.
func (sg *SubGraph) IsInternal() bool {
return sg.Params.IsInternal
}
func (sg *SubGraph) createSrcFunction(gf *gql.Function) {
if gf == nil {
return
}
sg.SrcFunc = &Function{
Name: gf.Name,
Args: append(gf.Args[:0:0], gf.Args...),
IsCount: gf.IsCount,
IsValueVar: gf.IsValueVar,
IsLenVar: gf.IsLenVar,
}
// type function is just an alias for eq(type, "dgraph.type").
if gf.Name == "type" {
sg.Attr = "dgraph.type"
sg.SrcFunc.Name = "eq"
sg.SrcFunc.IsCount = false
sg.SrcFunc.IsValueVar = false
sg.SrcFunc.IsLenVar = false
return
}
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 is returned when a value is empty.
ErrEmptyVal = errors.New("Query: harmless error, e.g. task.Val is nil")
// ErrWrongAgg is returned when value aggregation is attempted in the root level of a query.
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 isEmptyIneqFnWithVar(sg *SubGraph) bool {
return sg.SrcFunc != nil && isInequalityFn(sg.SrcFunc.Name) && len(sg.SrcFunc.Args) == 0 &&
len(sg.Params.NeedsVar) > 0
}
// 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, errors.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 errors.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 {
if ft.Func.Attr == "uid" {
return errors.Errorf(`Argument cannot be "uid"`)
}
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 errors.Errorf("expand() not allowed inside shortest")
}
key := ""
if gchild.Alias != "" {
key = gchild.Alias
} else {
key = uniqueKey(gchild)
}
if _, ok := attrsSeen[key]; ok {
return errors.Errorf("%s not allowed multiple times in same sub-query.",
key)
}
attrsSeen[key] = struct{}{}
args := params{
Alias: gchild.Alias,
Cascade: gchild.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: gchild.Normalize || sg.Params.Normalize,
Order: gchild.Order,
Var: gchild.Var,
GroupbyAttrs: gchild.GroupbyAttrs,
IsGroupBy: gchild.IsGroupby,
IsInternal: gchild.IsInternal,
}
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 errors.Errorf("Invalid argument: %s", argk)
}
}
if err := args.fill(gchild); err != nil {
return err
}
if len(args.Order) != 0 && len(args.FacetOrder) != 0 {
return errors.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 errors.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 errors.Errorf(
"Node with %q cant have filter, please place the filter on the upper level",
gchild.Func.Name)
}
if gchild.Func.Attr == "uid" {
return errors.Errorf(`Argument cannot be "uid"`)
}
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 = 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["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 gq.ShortestPathArgs.From == nil || gq.ShortestPathArgs.To == nil {
return errors.Errorf("from/to can't be nil for shortest path")
}
if len(gq.ShortestPathArgs.From.UID) > 0 {
args.From = gq.ShortestPathArgs.From.UID[0]
}
if len(gq.ShortestPathArgs.To.UID) > 0 {
args.To = gq.ShortestPathArgs.To.UID[0]
}
}
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
if len(md["debug"]) > 0 {
// We ignore the error here, because in error case,
// debug would be false which is what we want.
debug, _ = strconv.ParseBool(md["debug"][0])
}
}
// HTTP passes information about debug as query parameter which is attached to context.
d, _ := ctx.Value(DebugKey).(bool)
return debug || d
}
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,
ShortestPathArgs: gq.ShortestPathArgs,
Var: gq.Var,
GroupbyAttrs: gq.GroupbyAttrs,
IsGroupBy: gq.IsGroupby,
}
for argk := range gq.Args {
if !isValidArg(argk) {
return nil, errors.Errorf("Invalid argument: %s", argk)
}
}
if err := args.fill(gq); err != nil {
return nil, errors.Wrapf(err, "while filling args")
}
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
} else {
// Disallow uid as attribute - issue#3110
if len(gq.Func.UID) == 0 {
return nil, errors.Errorf(`Argument cannot be "uid"`)
}
}
if !isValidFuncName(gq.Func.Name) {
return nil, errors.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, errors.Wrapf(err, "while populating UIDs")
}
}
// Copy roots filter.
if gq.Filter != nil {
sgf := &SubGraph{}
if err := filterCopy(sgf, gq.Filter); err != nil {
return nil, errors.Wrapf(err, "while copying filter")
}
sg.Filters = append(sg.Filters, sgf)
}
if gq.FacetsFilter != nil {
facetsFilter, err := toFacetsFilter(gq.FacetsFilter)
if err != nil {
return nil, errors.Wrapf(err, "while converting to facets filter")
}
sg.facetsFilter = facetsFilter
}
return sg, nil
}
func toFacetsFilter(gft *gql.FilterTree) (*pb.FilterTree, error) {
if gft == nil {
return nil, nil
}
if gft.Func != nil && len(gft.Func.NeedsVar) != 0 {
return nil, errors.Errorf("Variables not supported in pb.FilterTree")
}
ftree := &pb.FilterTree{Op: gft.Op}
for _, gftc := range gft.Child {
ftc, err := toFacetsFilter(gftc)
if err != nil {
return nil, err
}
ftree.Children = append(ftree.Children, ftc)
}
if gft.Func != nil {
ftree.Func = &pb.Function{
Key: gft.Func.Attr,
Name: gft.Func.Name,
}
// TODO(Janardhan): Handle variable in facets later.
for _, arg := range gft.Func.Args {
ftree.Func.Args = append(ftree.Func.Args, arg.Value)
}
}
return ftree, nil
}
// createTaskQuery generates the query buffer.
func createTaskQuery(sg *SubGraph) (*pb.Query, error) {
attr := sg.Attr
// Might be safer than just checking first byte due to i18n
reverse := strings.HasPrefix(attr, "~")
if reverse {
attr = strings.TrimPrefix(attr, "~")
}
var srcFunc *pb.SrcFunction
if sg.SrcFunc != nil {
srcFunc = &pb.SrcFunction{}
srcFunc.Name = sg.SrcFunc.Name
srcFunc.IsCount = sg.SrcFunc.IsCount
for _, arg := range sg.SrcFunc.Args {
srcFunc.Args = append(srcFunc.Args, arg.Value)
if arg.IsValueVar {
return nil, errors.Errorf("Unsupported use of value var")
}
}
}
// If the lang is set to *, query all the languages.
if len(sg.Params.Langs) == 1 && sg.Params.Langs[0] == "*" {
sg.Params.ExpandAll = true
sg.Params.Langs = nil
}
// count is to limit how many results we want.
first := calculateFirstN(sg)
out := &pb.Query{
ReadTs: sg.ReadTs,
Cache: int32(sg.Cache),
Attr: attr,
Langs: sg.Params.Langs,
Reverse: reverse,
SrcFunc: srcFunc,
AfterUid: sg.Params.AfterUID,
DoCount: len(sg.Filters) == 0 && sg.Params.DoCount,
FacetParam: sg.Params.Facet,
FacetsFilter: sg.facetsFilter,
ExpandAll: sg.Params.ExpandAll,
First: first,
}
if sg.SrcUIDs != nil {
out.UidList = sg.SrcUIDs
}
return out, nil
}
// calculateFirstN returns the count of result we need to proceed query further down.
func calculateFirstN(sg *SubGraph) int32 {
// by default count is zero. (zero will retrive all the results)
count := math.MaxInt32
// In order to limit we have to make sure that the this level met the following conditions
// - No Filter (We can't filter until we have all the uids)
// {
// q(func: has(name), first:1)@filter(eq(father, "schoolboy")) {
// name
// father
// }
// }
// - No Ordering (We need all the results to do the sorting)
// {
// q(func: has(name), first:1, orderasc: name) {
// name
// }
// }
// - should be has function (Right now, I'm doing it for has, later it can be extended)
// {
// q(func: has(name), first:1) {
// name
// }
// }
isSupportedFunction := sg.SrcFunc != nil && sg.SrcFunc.Name == "has"
if len(sg.Filters) == 0 && len(sg.Params.Order) == 0 &&
isSupportedFunction {
// Offset also added because, we need n results to trim the offset.
if sg.Params.Count != 0 {
count = sg.Params.Count + sg.Params.Offset
}
}
return int32(count)
}
// varValue is a generic representation of a variable and holds multiple things.
// TODO(pawan) - Come back to this and document what do individual fields mean and when are they
// populated.
type varValue struct {
Uids *pb.List // list of uids if this denotes a uid variable.
Vals map[uint64]types.Val
path []*SubGraph // This stores the subgraph path from root to var definition.
// strList stores the valueMatrix corresponding to a predicate and is later used in
// expand(val(x)) query.
strList []*pb.ValueList
}
func evalLevelAgg(
doneVars map[string]varValue,
sg, parent *SubGraph) (map[uint64]types.Val, error) {
var mp map[uint64]types.Val
if parent == nil {
return nil, ErrWrongAgg
}
needsVar := sg.Params.NeedsVar[0].Name
if parent.Params.IsEmpty {
// The aggregated value doesn't really belong to a uid, we put it in UidToVal map
// corresponding to uid 0 to avoid defining another field in SubGraph.
vals := doneVars[needsVar].Vals
if len(vals) == 0 {
mp = make(map[uint64]types.Val)
mp[0] = types.Val{Tid: types.FloatID, Value: 0.0}
return mp, nil
}
ag := aggregator{
name: sg.SrcFunc.Name,
}
for _, val := range vals {
ag.Apply(val)
}
v, err := ag.Value()
if err != nil && err != ErrEmptyVal {
return nil, err
}
if v.Value != nil {
mp = make(map[uint64]types.Val)
mp[0] = v
}
return mp, nil
}
var relSG *SubGraph
for _, ch := range parent.Children {
if sg == ch {
continue
}
for _, v := range ch.Params.FacetVar {
if v == needsVar {
relSG = ch
}
}
for _, cch := range ch.Children {
// Find the sibling node whose child has the required variable.
if cch.Params.Var == needsVar {
relSG = ch
}
}
}
if relSG == nil {
return nil, errors.Errorf("Invalid variable aggregation. Check the levels.")
}
vals := doneVars[needsVar].Vals
mp = make(map[uint64]types.Val)
// Go over the sibling node and aggregate.
for i, list := range relSG.uidMatrix {
ag := aggregator{
name: sg.SrcFunc.Name,
}
for _, uid := range list.Uids {
if val, ok := vals[uid]; ok {
ag.Apply(val)