forked from FeatureBaseDB/featurebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
9657 lines (8719 loc) · 269 KB
/
executor.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 2022 Molecula Corp. (DBA FeatureBase).
// SPDX-License-Identifier: Apache-2.0
package pilosa
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math"
"math/bits"
"reflect"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/featurebasedb/featurebase/v3/dax"
"github.com/featurebasedb/featurebase/v3/disco"
"github.com/featurebasedb/featurebase/v3/pql"
"github.com/featurebasedb/featurebase/v3/proto"
"github.com/featurebasedb/featurebase/v3/roaring"
"github.com/featurebasedb/featurebase/v3/shardwidth"
"github.com/featurebasedb/featurebase/v3/task"
"github.com/featurebasedb/featurebase/v3/testhook"
"github.com/featurebasedb/featurebase/v3/tracing"
"github.com/gomem/gomem/pkg/dataframe"
"github.com/lib/pq"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"
)
// defaultField is the field used if one is not specified.
const (
defaultField = "general"
// defaultMinThreshold is the lowest count to use in a Top-N operation when
// looking for additional id/count pairs.
defaultMinThreshold = 1
columnLabel = "col"
rowLabel = "row"
errConnectionRefused = "connect: connection refused"
)
type Executor interface {
Execute(context.Context, dax.TableKeyer, *pql.Query, []uint64, *ExecOptions) (QueryResponse, error)
}
// executor recursively executes calls in a PQL query across all shards.
type executor struct {
Holder *Holder
// Local hostname & cluster configuration.
Node *disco.Node
Cluster *cluster
// Client used for remote requests.
client *InternalClient
// Maximum number of Set() or Clear() commands per request.
MaxWritesPerRequest int
shutdown chan struct{}
workers *task.Pool
workerPoolSize int
work chan job
// track active mapperLocal tasks so we can ensure we don't close
// e.work while they're still waiting to send
activeMappers uint64
// Maximum per-request memory usage (Extract() only)
maxMemory int64
// Temporary flag to be removed when stablized
dataframeEnabled bool
datafameUseParquet bool
}
// executorOption is a functional option type for pilosa.executor
type executorOption func(e *executor) error
func optExecutorInternalQueryClient(c *InternalClient) executorOption {
return func(e *executor) error {
e.client = c
return nil
}
}
func optExecutorWorkerPoolSize(size int) executorOption {
return func(e *executor) error {
e.workerPoolSize = size
return nil
}
}
func optExecutorMaxMemory(v int64) executorOption {
return func(e *executor) error {
e.maxMemory = v
return nil
}
}
func emptyResult(c *pql.Call) interface{} {
switch c.Name {
case "Clear", "ClearRow":
return false
case "Row":
return &Row{Keys: []string{}}
case "Rows":
return RowIdentifiers{Keys: []string{}}
case "IncludesColumn":
return false
}
return nil
}
// newExecutor returns a new instance of executor.
func newExecutor(opts ...executorOption) *executor {
e := &executor{
workerPoolSize: 2,
shutdown: make(chan struct{}),
}
for _, opt := range opts {
err := opt(e)
if err != nil {
panic(err)
}
}
// this channel cap doesn't necessarily have to be the same as
// workerPoolSize... any larger doesn't seem to have an effect in
// the few tests we've done at scale with concurrent query
// workloads. Possible that it could be smaller.
e.work = make(chan job, e.workerPoolSize)
_ = testhook.Opened(NewAuditor(), e, nil)
e.workers = task.NewPool(e.workerPoolSize, e.doOneJob, e)
return e
}
func (e *executor) Close() error {
select {
case <-e.shutdown:
return nil
default:
}
close(e.shutdown)
_ = testhook.Closed(NewAuditor(), e, nil)
// can't close e.work while a mapper is active.
for atomic.LoadUint64(&e.activeMappers) > 0 {
time.Sleep(1 * time.Millisecond)
}
close(e.work)
e.workers.Close()
return nil
}
// PoolSize is exported to let the task pool update us
func (e *executor) PoolSize(n int) {
if e.Holder != nil {
GaugeWorkerTotal.Set(float64(n))
}
}
// InitStats initializes stats counters. Must be called after Holder set.
func (e *executor) InitStats() {
if e.Holder != nil {
CounterJobTotal.Add(0)
l, _, _ := e.workers.Stats()
GaugeWorkerTotal.Set(float64(l))
}
}
// Execute executes a PQL query.
func (e *executor) Execute(ctx context.Context, tableKeyer dax.TableKeyer, q *pql.Query, shards []uint64, opt *ExecOptions) (QueryResponse, error) {
index := string(tableKeyer.Key())
span, ctx := tracing.StartSpanFromContext(ctx, "executor.Execute")
span.LogKV("pql", q.String())
defer span.Finish()
resp := QueryResponse{}
// Check for query cancellation.
if err := validateQueryContext(ctx); err != nil {
return resp, err
}
// Verify that an index is set.
if index == "" {
return resp, ErrIndexRequired
}
idx := e.Holder.Index(index)
if idx == nil {
return resp, newNotFoundError(ErrIndexNotFound, index)
}
needWriteTxn := false
nw := q.WriteCallN()
if nw > 0 {
needWriteTxn = true
}
// Verify that the number of writes do not exceed the maximum.
if e.MaxWritesPerRequest > 0 && nw > e.MaxWritesPerRequest {
return resp, ErrTooManyWrites
}
// Default options.
if opt == nil {
opt = &ExecOptions{}
}
// Default maximum memory, if not passed in.
if opt.MaxMemory == 0 && q.HasCall("Extract") {
opt.MaxMemory = e.maxMemory
}
if opt.Profile {
var prof tracing.ProfiledSpan
prof, ctx = tracing.StartProfiledSpanFromContext(ctx, "Execute")
defer prof.Finish()
var ok bool
resp.Profile, ok = prof.(*tracing.Profile)
if !ok {
return resp, fmt.Errorf("profiling execution failed: %T is not tracing.Profile", prof)
}
}
// Can't do NewTx() this high up, because we need a specific shard.
// So start a qcx with a TxGroup and pass it down.
var qcx *Qcx
if needWriteTxn {
qcx = idx.holder.txf.NewWritableQcx()
} else {
qcx = idx.holder.txf.NewQcx()
}
defer qcx.Abort()
results, err := e.execute(ctx, qcx, index, q, shards, opt)
if err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
resp.Results = results
// Translate response objects from ids to keys, if necessary.
// No need to translate a remote call.
if !opt.Remote {
// only translateResults if this local node is the final destination. only string/column keys.
if err := e.translateResults(ctx, index, idx, q.Calls, results, opt.MaxMemory); err != nil {
if errors.Cause(err) == ErrTranslatingKeyNotFound {
// No error - return empty result
resp.Results = make([]interface{}, len(q.Calls))
for i, c := range q.Calls {
resp.Results[i] = emptyResult(c)
}
return resp, nil
}
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
}
// Must copy out of Tx data before Commiting, because it will become invalid afterwards.
respSafeNoTxData := safeCopy(resp)
// Commit transactions if writing; else let the defer grp.Abort do the rollbacks.
if needWriteTxn {
if err := qcx.Finish(); err != nil {
return respSafeNoTxData, err
}
}
return respSafeNoTxData, nil
}
// safeCopy copies everything in resp that has Bitmap material,
// to avoid anything coming from the mmap-ed Tx storage.
func safeCopy(resp QueryResponse) (out QueryResponse) {
out = QueryResponse{
Err: resp.Err, // error
Profile: resp.Profile, // *tracing.Profile
}
// Results can contain *roaring.Bitmap, so need to copy from Tx mmap-ed memory.
for _, v := range resp.Results {
switch x := v.(type) {
case *Row:
rowSafe := x.Clone()
out.Results = append(out.Results, rowSafe)
case bool:
out.Results = append(out.Results, x)
case nil:
out.Results = append(out.Results, nil)
case uint64:
out.Results = append(out.Results, x) // for counts
case *PairsField:
// no bitmap material, so should be ok to skip Clone()
out.Results = append(out.Results, x)
case PairField: // not PairsField but PairField
// no bitmap material, so should be ok to skip Clone()
out.Results = append(out.Results, x)
case ValCount:
// no bitmap material, so should be ok to skip Clone()
out.Results = append(out.Results, x)
case SignedRow:
// has *Row in it, so has Bitmap material, and very likely needs Clone.
y := x.Clone()
out.Results = append(out.Results, *y)
case GroupCount:
// no bitmap material, so should be ok to skip Clone()
out.Results = append(out.Results, x)
case []GroupCount:
out.Results = append(out.Results, x)
case *GroupCounts:
out.Results = append(out.Results, x)
case ExtractedTable:
out.Results = append(out.Results, x)
case ExtractedIDMatrix:
out.Results = append(out.Results, x)
case RowIdentifiers:
// no bitmap material, so should be ok to skip Clone()
out.Results = append(out.Results, x)
case RowIDs:
// defined as: type RowIDs []uint64
// so does not contain bitmap material, and
// should not need to be cloned.
out.Results = append(out.Results, x)
case []*Row:
safe := make([]*Row, len(x))
for i, v := range x {
safe[i] = v.Clone()
}
out.Results = append(out.Results, safe)
case DistinctTimestamp:
out.Results = append(out.Results, x)
case *SortedRow:
out.Results = append(out.Results, x)
case *dataframe.DataFrame:
// dumpTable(x)
out.Results = append(out.Results, x)
case *BasicTable:
// dumpTable(x)
out.Results = append(out.Results, x)
case ExtractedIDMatrixSorted:
out.Results = append(out.Results, x)
default:
panic(fmt.Sprintf("handle %T here", v))
}
}
return
}
// handlePreCalls traverses the call tree looking for calls that need
// precomputed values (e.g. Distinct, UnionRows, ConstRow...).
func (e *executor) handlePreCalls(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) error {
if c.Name == "Precomputed" {
idx := c.Args["valueidx"].(int64)
if idx >= 0 && idx < int64(len(opt.EmbeddedData)) {
row := opt.EmbeddedData[idx]
c.Precomputed = make(map[uint64]interface{}, len(row.Segments))
for _, segment := range row.Segments {
c.Precomputed[segment.shard] = &Row{Segments: []RowSegment{segment}}
}
} else {
return fmt.Errorf("no precomputed data! index %d, len %d", idx, len(opt.EmbeddedData))
}
return nil
}
newIndex := c.CallIndex()
// A cross-index query is handled by precall. This is inefficient,
// but we have to do it for now because shards might be different and
// we haven't implemented the local precalls that would be enough
// in some cases.
//
// This makes simple cross-index queries noticably inefficient.
//
// If you're here because of that: We should be using PrecallLocal
// in cases where the call isn't already PrecallGlobal, and
// PrecallLocal should wait until we're running on a specific node
// to do the farming-out of just the sub-queries it has to run
// for its local shards.
//
// As is, we have one node querying every node, then sending out
// all the data to every node, including the data that node already
// has. We could reduce the actual copying around dramatically,
// but only in the cases where local is good enough -- not something
// like Distinct, where you can't predict output shard for a result
// from the shard being queried.
if newIndex != "" && newIndex != index {
c.Type = pql.PrecallGlobal
index = newIndex
// we need to recompute shards, then
shards = nil
}
if err := e.handlePreCallChildren(ctx, qcx, index, c, shards, opt); err != nil {
return err
}
// child calls already handled, no precall for this, so we're done
if c.Type == pql.PrecallNone {
return nil
}
// We don't try to handle sub-calls from here. I'm not 100%
// sure that's right, but I think the fact that they're happening
// inside a precomputed call may mean they need different
// handling. In any event, the sub-calls will get handled by
// the executeCall when it gets to them...
// We set c to look like a normal call, and actually execute it:
c.Type = pql.PrecallNone
// possibly override call index.
v, err := e.executeCall(ctx, qcx, index, c, shards, opt)
if err != nil {
return err
}
var row *Row
switch r := v.(type) {
case *Row:
row = r
case SignedRow:
row = r.Pos
default:
return fmt.Errorf("precomputed call %s returned unexpected non-Row data: %T", c.Name, v)
}
if err := ctx.Err(); err != nil {
return err
}
c.Children = []*pql.Call{}
c.Name = "Precomputed"
c.Args = map[string]interface{}{"valueidx": len(opt.EmbeddedData)}
// stash a copy of the full results, which can be forwarded to other
// shards if the query has to go to them
opt.EmbeddedData = append(opt.EmbeddedData, row)
// and stash a copy locally, so local calls can use it
if row != nil {
c.Precomputed = make(map[uint64]interface{}, len(row.Segments))
for _, segment := range row.Segments {
c.Precomputed[segment.shard] = &Row{Segments: []RowSegment{segment}}
}
}
return nil
}
// dumpPrecomputedCalls throws away precomputed call data. this is used so we
// can drop any large data associated with a call once we've processed
// the call.
func (e *executor) dumpPrecomputedCalls(ctx context.Context, c *pql.Call) {
for _, call := range c.Children {
e.dumpPrecomputedCalls(ctx, call)
}
c.Precomputed = nil
}
// handlePreCallChildren handles any pre-calls in the children of a given call.
func (e *executor) handlePreCallChildren(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) error {
for i := range c.Children {
if err := ctx.Err(); err != nil {
return err
}
if err := e.handlePreCalls(ctx, qcx, index, c.Children[i], shards, opt); err != nil {
return err
}
}
for key, val := range c.Args {
// Do not precompute GroupBy aggregates
if key == "aggregate" {
continue
}
// Handle Call() operations which exist inside named arguments, too.
if call, ok := val.(*pql.Call); ok {
if err := ctx.Err(); err != nil {
return err
}
if err := e.handlePreCalls(ctx, qcx, index, call, shards, opt); err != nil {
return err
}
}
}
return nil
}
func (e *executor) execute(ctx context.Context, qcx *Qcx, index string, q *pql.Query, shards []uint64, opt *ExecOptions) ([]interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "executor.execute")
defer span.Finish()
// Apply translations if necessary.
var colTranslations map[string]map[string]uint64 // colID := colTranslations[index][key]
var rowTranslations map[string]map[string]map[string]uint64 // rowID := rowTranslations[index][field][key]
if !opt.Remote {
cols, rows, err := e.preTranslate(ctx, index, q.Calls...)
if err != nil {
return nil, err
}
colTranslations, rowTranslations = cols, rows
}
needShards := false
if len(shards) == 0 {
for _, call := range q.Calls {
if needsShards(call) {
needShards = true
break
}
}
}
if needShards {
// Round up the number of shards.
idx := e.Holder.Index(index)
if idx == nil {
return nil, newNotFoundError(ErrIndexNotFound, index)
}
shards = idx.AvailableShards(includeRemote).Slice()
if len(shards) == 0 {
shards = []uint64{0}
}
}
lastWasWrite := false
// Execute each call serially.
results := make([]interface{}, 0, len(q.Calls))
for i, call := range q.Calls {
if lastWasWrite && needsShards(call) && needShards {
// Round up the number of shards.
idx := e.Holder.Index(index)
if idx == nil {
return nil, newNotFoundError(ErrIndexNotFound, index)
}
shards = idx.AvailableShards(includeRemote).Slice()
if len(shards) == 0 {
shards = []uint64{0}
}
}
lastWasWrite = call.IsWrite()
if err := validateQueryContext(ctx); err != nil {
return nil, err
}
// Apply call translation.
if !opt.Remote && !opt.PreTranslated {
translated, err := e.translateCall(call, index, colTranslations, rowTranslations)
if err != nil {
return nil, errors.Wrap(err, "translating call")
}
if translated == nil {
results = append(results, emptyResult(call))
continue
}
call = translated
}
// If you actually make a top-level Distinct call, you
// want a SignedRow back. Otherwise, it's something else
// that will be using it as a row, and we only care
// about the positive values, because only positive values
// are valid column IDs. So we don't actually eat top-level
// pre calls.
if call.Name == "Count" {
// Handle count specially, skipping the level directly underneath it.
for _, child := range call.Children {
err := e.handlePreCallChildren(ctx, qcx, index, child, shards, opt)
if err != nil {
return nil, err
}
}
} else {
err := e.handlePreCallChildren(ctx, qcx, index, call, shards, opt)
if err != nil {
return nil, err
}
}
var v interface{}
var err error
// Top-level calls don't need to precompute cross-index things,
// because we can just pick whatever index we want, but we
// still need to handle them. Since everything else was
// already precomputed by handlePreCallChildren, though,
// we don't need this logic in executeCall.
newIndex := call.CallIndex()
if newIndex != "" && newIndex != index {
v, err = e.executeCall(ctx, qcx, newIndex, call, nil, opt)
} else {
v, err = e.executeCall(ctx, qcx, index, call, shards, opt)
}
if err != nil {
return nil, err
}
if vc, ok := v.(ValCount); ok {
vc.Cleanup()
v = vc
}
results = append(results, v)
// Some Calls can have significant data associated with them
// that gets generated during processing, such as Precomputed
// values. Dumping the precomputed data, if any, lets the GC
// free the memory before we get there.
e.dumpPrecomputedCalls(ctx, q.Calls[i])
}
return results, nil
}
// cleanup removes the integer value (Val) from the ValCount if one of
// the other fields is in use.
//
// ValCounts are normally holding data which is stored as a BSI
// (integer) under the hood. Sometimes it's convenient to be able to
// compare the underlying integer values rather than their
// interpretation as decimal, timestamp, etc, so the lower level
// functions may return both integer and the interpreted value, but we
// don't want to pass that all the way back to the client, so we
// remove it here.
func (vc *ValCount) Cleanup() {
if vc.Val != 0 && (vc.FloatVal != 0 || !vc.TimestampVal.IsZero() || vc.DecimalVal != nil) {
vc.Val = 0
}
}
// preprocessQuery expands any calls that need preprocessing.
func (e *executor) preprocessQuery(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) (*pql.Call, error) {
switch c.Name {
case "All":
_, hasLimit, err := c.UintArg("limit")
if err != nil {
return nil, err
}
_, hasOffset, err := c.UintArg("offset")
if err != nil {
return nil, err
}
if !hasLimit && !hasOffset {
return c, nil
}
// Rewrite the All() w/ limit to Limit(All()).
c.Children = []*pql.Call{
{
Name: "All",
},
}
c.Name = "Limit"
return c, nil
default:
// Recurse through child calls.
out := make([]*pql.Call, len(c.Children))
var changed bool
for i, child := range c.Children {
res, err := e.preprocessQuery(ctx, qcx, index, child, shards, opt)
if err != nil {
return nil, err
}
if res != child {
changed = true
}
out[i] = res
}
if changed {
c = c.Clone()
c.Children = out
}
return c, nil
}
}
// executeCall executes a call.
func (e *executor) executeCall(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "executor.executeCall")
defer span.Finish()
if err := validateQueryContext(ctx); err != nil {
return nil, err
} else if err := e.validateCallArgs(c); err != nil {
return nil, errors.Wrap(err, "validating args")
}
labels := prometheus.Labels{"index": index}
statFn := func(ctr *prometheus.CounterVec) {
if !opt.Remote {
ctr.With(labels).Inc()
}
}
// Fixes #2009
// See: https://github.com/featurebasedb/featurebase/issues/2009
// TODO: Remove at version 2.0
if e.detectRangeCall(c) {
e.Holder.Logger.Infof("DEPRECATED: Range() is deprecated, please use Row() instead.")
}
// If shards are specified, then use that value for shards. If shards aren't
// specified, then include all of them.
if shards == nil && needsShards(c) {
// Round up the number of shards.
idx := e.Holder.Index(index)
if idx == nil {
return nil, newNotFoundError(ErrIndexNotFound, index)
}
shards = idx.AvailableShards(includeRemote).Slice()
if len(shards) == 0 {
shards = []uint64{0}
}
}
// Preprocess the query.
c, err := e.preprocessQuery(ctx, qcx, index, c, shards, opt)
if err != nil {
return nil, err
}
switch c.Name {
case "Sum":
statFn(CounterQuerySumTotal)
res, err := e.executeSum(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeSum")
case "Min":
statFn(CounterQueryMinTotal)
res, err := e.executeMin(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeMin")
case "Max":
statFn(CounterQueryMaxTotal)
res, err := e.executeMax(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeMax")
case "MinRow":
statFn(CounterQueryMinRowTotal)
res, err := e.executeMinRow(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeMinRow")
case "MaxRow":
statFn(CounterQueryMaxRowTotal)
res, err := e.executeMaxRow(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeMaxRow")
case "Clear":
statFn(CounterQueryClearTotal)
res, err := e.executeClearBit(ctx, qcx, index, c, opt)
return res, errors.Wrap(err, "executeClearBit")
case "ClearRow":
statFn(CounterQueryClearRowTotal)
res, err := e.executeClearRow(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeClearRow")
case "Distinct":
statFn(CounterQueryDistinctTotal)
res, err := e.executeDistinct(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeDistinct")
case "Store":
statFn(CounterQueryStoreTotal)
res, err := e.executeSetRow(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeSetRow")
case "Count":
statFn(CounterQueryCountTotal)
res, err := e.executeCount(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeCount")
case "Set":
statFn(CounterQuerySetTotal)
res, err := e.executeSet(ctx, qcx, index, c, opt)
return res, errors.Wrap(err, "executeSet")
case "TopK":
statFn(CounterQueryTopKTotal)
res, err := e.executeTopK(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeTopK")
case "TopN":
statFn(CounterQueryTopNTotal)
res, err := e.executeTopN(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeTopN")
case "Rows":
statFn(CounterQueryRowsTotal)
res, err := e.executeRows(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeRows")
case "ExternalLookup":
statFn(CounterQueryExternalLookupTotal)
res, err := e.executeExternalLookup(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeExternalLookup")
case "Extract":
statFn(CounterQueryExtractTotal)
res, err := e.executeExtract(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeExtract")
case "GroupBy":
statFn(CounterQueryGroupByTotal)
res, err := e.executeGroupBy(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeGroupBy")
case "Options":
statFn(CounterQueryOptionsTotal)
res, err := e.executeOptionsCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeOptionsCall")
case "IncludesColumn":
statFn(CounterQueryIncludesColumnTotal)
res, err := e.executeIncludesColumnCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeIncludesColumnCall")
case "FieldValue":
statFn(CounterQueryFieldValueTotal)
res, err := e.executeFieldValueCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeFieldValueCall")
case "Precomputed":
statFn(CounterQueryPrecomputedTotal)
res, err := e.executePrecomputedCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executePrecomputedCall")
case "UnionRows":
statFn(CounterQueryUnionRowsTotal)
res, err := e.executeUnionRows(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeUnionRows")
case "ConstRow":
statFn(CounterQueryConstRowTotal)
res, err := e.executeConstRow(ctx, qcx, index, c, opt)
return res, errors.Wrap(err, "executeConstRow")
case "Limit":
statFn(CounterQueryLimitTotal)
res, err := e.executeLimitCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeLimitCall")
case "Percentile":
statFn(CounterQueryPercentileTotal)
res, err := e.executePercentile(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executePercentile")
case "Delete":
statFn(CounterQueryDeleteTotal)
res, err := e.executeDeleteRecords(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeDelete")
case "Sort":
statFn(CounterQuerySortTotal)
res, err := e.executeSort(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeSort")
case "Apply":
statFn(CounterQueryApplyTotal)
res, err := e.executeApply(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeApply")
case "Arrow":
statFn(CounterQueryArrowTotal)
res, err := e.executeArrow(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeArrow")
default: // e.g. "Row", "Union", "Intersect" or anything that returns a bitmap.
res, err := e.executeBitmapCall(ctx, qcx, index, c, shards, opt)
return res, errors.Wrap(err, "executeBitmapCall")
}
}
// validateCallArgs ensures that the value types in call.Args are expected.
func (e *executor) validateCallArgs(c *pql.Call) error {
if _, ok := c.Args["ids"]; ok {
switch v := c.Args["ids"].(type) {
case []int64, []uint64:
// noop
case []interface{}:
b := make([]int64, len(v))
for i := range v {
b[i] = v[i].(int64)
}
c.Args["ids"] = b
default:
return fmt.Errorf("invalid call.Args[ids]: %s", v)
}
}
return nil
}
// if call args include time args ("from"/"to")
// check if field is a time field
func (e *executor) validateTimeCallArgs(c *pql.Call, indexName string) error {
f, err := c.FieldArg()
if err != nil {
return err
}
_, from := c.Args["from"]
_, to := c.Args["to"]
field := e.Holder.Field(indexName, f)
tq := field.TimeQuantum()
if (from || to) && tq == "" {
return fmt.Errorf("field %s is not a time-field, 'from' and 'to' are not valid options for this field type", f)
}
return nil
}
func (e *executor) executeOptionsCall(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "executor.executeOptionsCall")
defer span.Finish()
optCopy := &ExecOptions{}
*optCopy = *opt
if arg, ok := c.Args["shards"]; ok {
if optShards, ok := arg.([]interface{}); ok {
shards = []uint64{}
for _, s := range optShards {
if shard, ok := s.(int64); ok {
shards = append(shards, uint64(shard))
} else {
return nil, errors.New("Query(): shards must be a list of unsigned integers")
}
}
} else {
return nil, errors.New("Query(): shards must be a list of unsigned integers")
}
}
return e.executeCall(ctx, qcx, index, c.Children[0], shards, optCopy)
}
// executeIncludesColumnCall executes an IncludesColumn() call.
func (e *executor) executeIncludesColumnCall(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) (bool, error) {
// Get the shard containing the column, since that's the only
// shard that needs to execute this query.
var shard uint64
col, ok, err := c.UintArg("column")
if err != nil {
return false, errors.Wrap(err, "getting column from args")
} else if !ok {
return false, errors.New("IncludesColumn call must specify a column")
}
shard = col / ShardWidth
// If shard is not in shards, bail early.
if !uint64InSlice(shard, shards) {
return false, nil
}
// Execute calls in bulk on each remote node and merge.
mapFn := func(ctx context.Context, shard uint64, mopt *mapOptions) (_ interface{}, err error) {
return e.executeIncludesColumnCallShard(ctx, qcx, index, c, shard, col)
}
// Merge returned results at coordinating node.
reduceFn := func(ctx context.Context, prev, v interface{}) interface{} {
other, _ := prev.(bool)
return other || v.(bool)
}
result, err := e.mapReduce(ctx, index, []uint64{shard}, c, opt, mapFn, reduceFn)
if err != nil {
return false, err
}
return result.(bool), nil
}
// executeFieldValueCall executes a FieldValue() call.
func (e *executor) executeFieldValueCall(ctx context.Context, qcx *Qcx, index string, c *pql.Call, shards []uint64, opt *ExecOptions) (_ ValCount, err error) {
fieldName, ok := c.Args["field"].(string)
if !ok || fieldName == "" {
return ValCount{}, ErrFieldRequired
}
colKey, ok := c.Args["column"]
if !ok || colKey == "" {
return ValCount{}, ErrColumnRequired
}
// Fetch index.
idx := e.Holder.Index(index)
if idx == nil {
return ValCount{}, newNotFoundError(ErrIndexNotFound, index)
}
// Fetch field.
field := idx.Field(fieldName)
if field == nil {
return ValCount{}, newNotFoundError(ErrFieldNotFound, fieldName)
}
colID, ok, err := c.UintArg("column")
if !ok || err != nil {
return ValCount{}, errors.Wrap(err, "getting column argument")
}
shard := colID / ShardWidth
// Execute calls in bulk on each remote node and merge.
mapFn := func(ctx context.Context, shard uint64, mopt *mapOptions) (_ interface{}, err error) {
return e.executeFieldValueCallShard(ctx, qcx, field, colID, shard)
}
// Select single returned result at coordinating node.
reduceFn := func(ctx context.Context, prev, v interface{}) interface{} {
other, _ := prev.(ValCount)
if other.Count == 1 {
return other
}
return v
}
result, err := e.mapReduce(ctx, index, []uint64{shard}, c, opt, mapFn, reduceFn)
if err != nil {
return ValCount{}, errors.Wrap(err, "map reduce")
}
other, _ := result.(ValCount)
return other, nil
}
func (e *executor) executeFieldValueCallShard(ctx context.Context, qcx *Qcx, field *Field, col uint64, shard uint64) (_ ValCount, err0 error) {
value, exists, err := field.Value(qcx, col)
if err != nil {
return ValCount{}, errors.Wrap(err, "getting field value")
} else if !exists {