-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
column_exec_setup.go
1950 lines (1832 loc) · 71.2 KB
/
column_exec_setup.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 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package distsqlrun
import (
"context"
"fmt"
"math"
"reflect"
"strings"
"sync"
"sync/atomic"
"github.com/cockroachdb/cockroach/pkg/col/coltypes"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/sql/distsqlpb"
"github.com/cockroachdb/cockroach/pkg/sql/exec"
"github.com/cockroachdb/cockroach/pkg/sql/exec/colrpc"
"github.com/cockroachdb/cockroach/pkg/sql/exec/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/exec/vecbuiltins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/opentracing/opentracing-go"
)
func checkNumIn(inputs []exec.Operator, numIn int) error {
if len(inputs) != numIn {
return errors.Errorf("expected %d input(s), got %d", numIn, len(inputs))
}
return nil
}
// wrapRowSource, given an input exec.Operator, integrates toWrap into a
// columnar execution flow and returns toWrap's output as an exec.Operator.
func wrapRowSource(
ctx context.Context,
flowCtx *FlowCtx,
input exec.Operator,
inputTypes []types.T,
newToWrap func(RowSource) (RowSource, error),
) (*columnarizer, error) {
var (
toWrapInput RowSource
// TODO(asubiotto): Plumb proper processorIDs once we have stats.
processorID int32
)
// Optimization: if the input is a columnarizer, its input is necessarily a
// RowSource, so remove the unnecessary conversion.
if c, ok := input.(*columnarizer); ok {
// TODO(asubiotto): We might need to do some extra work to remove references
// to this operator (e.g. streamIDToOp).
toWrapInput = c.input
} else {
var err error
toWrapInput, err = newMaterializer(
flowCtx,
processorID,
input,
inputTypes,
&distsqlpb.PostProcessSpec{},
nil, /* output */
nil, /* metadataSourcesQueue */
nil, /* outputStatsToTrace */
nil, /* cancelFlow */
)
if err != nil {
return nil, err
}
}
toWrap, err := newToWrap(toWrapInput)
if err != nil {
return nil, err
}
return newColumnarizer(ctx, flowCtx, processorID, toWrap)
}
type newColOperatorResult struct {
op exec.Operator
columnTypes []types.T
memUsage int
metadataSources []distsqlpb.MetadataSource
isStreaming bool
}
// newColOperator creates a new columnar operator according to the given spec.
func newColOperator(
ctx context.Context, flowCtx *FlowCtx, spec *distsqlpb.ProcessorSpec, inputs []exec.Operator,
) (result newColOperatorResult, err error) {
log.VEventf(ctx, 2, "planning col operator for spec %q", spec)
core := &spec.Core
post := &spec.Post
// By default, we safely assume that an operator is not streaming. Note that
// projections, renders, filters, limits, offsets as well as all internal
// operators (like stats collectors and cancel checkers) are streaming, so in
// order to determine whether the resulting chain of operators is streaming,
// it is sufficient to look only at the "core" operator.
result.isStreaming = false
switch {
case core.Noop != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
result.op, result.isStreaming = exec.NewNoop(inputs[0]), true
result.columnTypes = spec.Input[0].ColumnTypes
case core.TableReader != nil:
if err := checkNumIn(inputs, 0); err != nil {
return result, err
}
if core.TableReader.IsCheck {
return result, errors.Newf("scrub table reader is unsupported in vectorized")
}
var scanOp *colBatchScan
scanOp, err = newColBatchScan(flowCtx, core.TableReader, post)
if err != nil {
return result, err
}
result.op, result.isStreaming = scanOp, true
result.metadataSources = append(result.metadataSources, scanOp)
// colBatchScan is wrapped with a cancel checker below, so we need to
// account for its static memory usage here. We also need to log its
// creation separately.
result.memUsage += scanOp.EstimateStaticMemoryUsage()
log.VEventf(ctx, 1, "made op %T\n", result.op)
// We want to check for cancellation once per input batch, and wrapping
// only colBatchScan with an exec.CancelChecker allows us to do just that.
// It's sufficient for most of the operators since they are extremely fast.
// However, some of the long-running operators (for example, sorter) are
// still responsible for doing the cancellation check on their own while
// performing long operations.
result.op = exec.NewCancelChecker(result.op)
returnMutations := core.TableReader.Visibility == distsqlpb.ScanVisibility_PUBLIC_AND_NOT_PUBLIC
result.columnTypes = core.TableReader.Table.ColumnTypesWithMutations(returnMutations)
case core.Aggregator != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
aggSpec := core.Aggregator
if len(aggSpec.Aggregations) == 0 {
// We can get an aggregator when no aggregate functions are present if
// HAVING clause is present, for example, with a query as follows:
// SELECT 1 FROM t HAVING true. In this case, we plan a special operator
// that outputs a batch of length 1 without actual columns once and then
// zero-length batches. The actual "data" will be added by projections
// below.
// TODO(solon): The distsql plan for this case includes a TableReader, so
// we end up creating an orphaned colBatchScan. We should avoid that.
// Ideally the optimizer would not plan a scan in this unusual case.
result.op, result.isStreaming, err = exec.NewSingleTupleNoInputOp(), true, nil
// We make columnTypes non-nil so that sanity check doesn't panic.
result.columnTypes = make([]types.T, 0)
break
}
if len(aggSpec.GroupCols) == 0 &&
len(aggSpec.Aggregations) == 1 &&
aggSpec.Aggregations[0].FilterColIdx == nil &&
aggSpec.Aggregations[0].Func == distsqlpb.AggregatorSpec_COUNT_ROWS &&
!aggSpec.Aggregations[0].Distinct {
result.op, result.isStreaming, err = exec.NewCountOp(inputs[0]), true, nil
result.columnTypes = []types.T{*types.Int}
break
}
var groupCols, orderedCols util.FastIntSet
for _, col := range aggSpec.OrderedGroupCols {
orderedCols.Add(int(col))
}
needHash := false
for _, col := range aggSpec.GroupCols {
if !orderedCols.Contains(int(col)) {
needHash = true
}
groupCols.Add(int(col))
}
if !orderedCols.SubsetOf(groupCols) {
return result, errors.AssertionFailedf("ordered cols must be a subset of grouping cols")
}
aggTyps := make([][]types.T, len(aggSpec.Aggregations))
aggCols := make([][]uint32, len(aggSpec.Aggregations))
aggFns := make([]distsqlpb.AggregatorSpec_Func, len(aggSpec.Aggregations))
result.columnTypes = make([]types.T, len(aggSpec.Aggregations))
for i, agg := range aggSpec.Aggregations {
if agg.Distinct {
return result, errors.Newf("distinct aggregation not supported")
}
if agg.FilterColIdx != nil {
return result, errors.Newf("filtering aggregation not supported")
}
if len(agg.Arguments) > 0 {
return result, errors.Newf("aggregates with arguments not supported")
}
aggTyps[i] = make([]types.T, len(agg.ColIdx))
for j, colIdx := range agg.ColIdx {
aggTyps[i][j] = spec.Input[0].ColumnTypes[colIdx]
}
aggCols[i] = agg.ColIdx
aggFns[i] = agg.Func
switch agg.Func {
case distsqlpb.AggregatorSpec_SUM:
switch aggTyps[i][0].Family() {
case types.IntFamily:
// TODO(alfonso): plan ordinary SUM on integer types by casting to DECIMAL
// at the end, mod issues with overflow. Perhaps to avoid the overflow
// issues, at first, we could plan SUM for all types besides Int64.
return result, errors.Newf("sum on int cols not supported (use sum_int)")
}
case distsqlpb.AggregatorSpec_SUM_INT:
// TODO(yuzefovich): support this case through vectorize.
if aggTyps[i][0].Width() != 64 {
return result, errors.Newf("sum_int is only supported on Int64 through vectorized")
}
}
_, retType, err := GetAggregateInfo(agg.Func, aggTyps[i]...)
if err != nil {
return result, err
}
result.columnTypes[i] = *retType
}
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
if needHash {
result.op, err = exec.NewHashAggregator(
inputs[0], typs, aggFns, aggSpec.GroupCols, aggCols, isScalarAggregate(aggSpec),
)
} else {
result.op, err = exec.NewOrderedAggregator(
inputs[0], typs, aggFns, aggSpec.GroupCols, aggCols, isScalarAggregate(aggSpec),
)
result.isStreaming = true
}
case core.Distinct != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
var distinctCols, orderedCols util.FastIntSet
for _, col := range core.Distinct.OrderedColumns {
orderedCols.Add(int(col))
}
for _, col := range core.Distinct.DistinctColumns {
if !orderedCols.Contains(int(col)) {
return result, errors.Newf("unsorted distinct not supported")
}
distinctCols.Add(int(col))
}
if !orderedCols.SubsetOf(distinctCols) {
return result, errors.AssertionFailedf("ordered cols must be a subset of distinct cols")
}
result.columnTypes = spec.Input[0].ColumnTypes
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(result.columnTypes)
if err != nil {
return result, err
}
result.op, err = exec.NewOrderedDistinct(inputs[0], core.Distinct.OrderedColumns, typs)
result.isStreaming = true
case core.Ordinality != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
result.columnTypes = append(spec.Input[0].ColumnTypes, *types.Int)
result.op, result.isStreaming = exec.NewOrdinalityOp(inputs[0]), true
case core.HashJoiner != nil:
if err := checkNumIn(inputs, 2); err != nil {
return result, err
}
var leftTypes, rightTypes []coltypes.T
leftTypes, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
rightTypes, err = typeconv.FromColumnTypes(spec.Input[1].ColumnTypes)
if err != nil {
return result, err
}
nLeftCols := uint32(len(leftTypes))
nRightCols := uint32(len(rightTypes))
leftOutCols := make([]uint32, 0)
rightOutCols := make([]uint32, 0)
// Note that we do not need a special treatment in case of LEFT SEMI and
// LEFT ANTI joins when setting up outCols because in such cases there will
// be a projection with post.OutputColumns already projecting out the right
// side.
if post.Projection {
for _, col := range post.OutputColumns {
if col < nLeftCols {
leftOutCols = append(leftOutCols, col)
} else {
rightOutCols = append(rightOutCols, col-nLeftCols)
}
}
} else {
for i := uint32(0); i < nLeftCols; i++ {
leftOutCols = append(leftOutCols, i)
}
for i := uint32(0); i < nRightCols; i++ {
rightOutCols = append(rightOutCols, i)
}
}
var (
onExpr *distsqlpb.Expression
filterPlanning *filterPlanningState
)
if !core.HashJoiner.OnExpr.Empty() {
if core.HashJoiner.Type != sqlbase.JoinType_INNER {
return result, errors.Newf("can't plan non-inner hash join with on expressions")
}
onExpr = &core.HashJoiner.OnExpr
filterPlanning = newFilterPlanningState(len(leftTypes), len(rightTypes))
leftOutCols, rightOutCols = filterPlanning.renderAllNeededCols(
*onExpr, leftOutCols, rightOutCols,
)
}
result.op, err = exec.NewEqHashJoinerOp(
inputs[0],
inputs[1],
core.HashJoiner.LeftEqColumns,
core.HashJoiner.RightEqColumns,
leftOutCols,
rightOutCols,
leftTypes,
rightTypes,
core.HashJoiner.RightEqColumnsAreKey,
core.HashJoiner.LeftEqColumnsAreKey || core.HashJoiner.RightEqColumnsAreKey,
core.HashJoiner.Type,
)
if err != nil {
return result, err
}
result.columnTypes = make([]types.T, nLeftCols+nRightCols)
copy(result.columnTypes, spec.Input[0].ColumnTypes)
if core.HashJoiner.Type != sqlbase.JoinType_LEFT_SEMI {
// TODO(yuzefovich): update this conditional once LEFT ANTI is supported.
copy(result.columnTypes[nLeftCols:], spec.Input[1].ColumnTypes)
} else {
result.columnTypes = result.columnTypes[:nLeftCols]
}
if onExpr != nil {
filterPlanning.remapIVars(onExpr)
err = result.planFilterExpr(flowCtx.NewEvalCtx(), *onExpr)
filterPlanning.projectOutExtraCols(&result, leftOutCols, rightOutCols)
}
case core.MergeJoiner != nil:
if err := checkNumIn(inputs, 2); err != nil {
return result, err
}
if core.MergeJoiner.Type.IsSetOpJoin() {
return result, errors.AssertionFailedf("unexpectedly %s merge join was planned", core.MergeJoiner.Type.String())
}
// Merge joiner is a streaming operator when equality columns form a key
// for both of the inputs.
result.isStreaming = core.MergeJoiner.LeftEqColumnsAreKey && core.MergeJoiner.RightEqColumnsAreKey
var leftTypes, rightTypes []coltypes.T
leftTypes, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
rightTypes, err = typeconv.FromColumnTypes(spec.Input[1].ColumnTypes)
if err != nil {
return result, err
}
nLeftCols := uint32(len(leftTypes))
nRightCols := uint32(len(rightTypes))
leftOutCols := make([]uint32, 0, nLeftCols)
rightOutCols := make([]uint32, 0, nRightCols)
// Note that we do not need a special treatment in case of LEFT SEMI and
// LEFT ANTI joins when setting up outCols because in such cases there will
// be a projection with post.OutputColumns already projecting out the right
// side.
if post.Projection {
for _, col := range post.OutputColumns {
if col < nLeftCols {
leftOutCols = append(leftOutCols, col)
} else {
rightOutCols = append(rightOutCols, col-nLeftCols)
}
}
} else {
for i := uint32(0); i < nLeftCols; i++ {
leftOutCols = append(leftOutCols, i)
}
for i := uint32(0); i < nRightCols; i++ {
rightOutCols = append(rightOutCols, i)
}
}
var (
onExpr *distsqlpb.Expression
filterPlanning *filterPlanningState
filterOnlyOnLeft bool
filterConstructor func(exec.Operator) (exec.Operator, error)
)
if !core.MergeJoiner.OnExpr.Empty() {
// At the moment, we want to be on the conservative side and not run
// queries with ON expressions when vectorize=auto, so we say that the
// merge join is not streaming which will reject running such a query
// through vectorized engine with 'auto' setting.
// TODO(yuzefovich): remove this when we're confident in ON expression
// support.
result.isStreaming = false
onExpr = &core.MergeJoiner.OnExpr
filterPlanning = newFilterPlanningState(len(leftTypes), len(rightTypes))
switch core.MergeJoiner.Type {
case sqlbase.JoinType_INNER:
leftOutCols, rightOutCols = filterPlanning.renderAllNeededCols(
*onExpr, leftOutCols, rightOutCols,
)
case sqlbase.JoinType_LEFT_SEMI, sqlbase.JoinType_LEFT_ANTI:
filterOnlyOnLeft = filterPlanning.isFilterOnlyOnLeft(*onExpr)
filterConstructor = func(op exec.Operator) (exec.Operator, error) {
r := newColOperatorResult{
op: op,
columnTypes: append(spec.Input[0].ColumnTypes, spec.Input[1].ColumnTypes...),
}
// We don't need to remap the indexed vars in onExpr because the
// filter will be run alongside the merge joiner, and it will have
// access to all of the columns from both sides.
err := r.planFilterExpr(flowCtx.NewEvalCtx(), *onExpr)
return r.op, err
}
default:
return result, errors.Errorf("can only plan INNER, LEFT SEMI, and LEFT ANTI merge joins with ON expressions")
}
}
result.op, err = exec.NewMergeJoinOp(
core.MergeJoiner.Type,
inputs[0],
inputs[1],
leftOutCols,
rightOutCols,
leftTypes,
rightTypes,
core.MergeJoiner.LeftOrdering.Columns,
core.MergeJoiner.RightOrdering.Columns,
filterConstructor,
filterOnlyOnLeft,
)
if err != nil {
return result, err
}
result.columnTypes = make([]types.T, nLeftCols+nRightCols)
copy(result.columnTypes, spec.Input[0].ColumnTypes)
if core.MergeJoiner.Type != sqlbase.JoinType_LEFT_SEMI &&
core.MergeJoiner.Type != sqlbase.JoinType_LEFT_ANTI {
copy(result.columnTypes[nLeftCols:], spec.Input[1].ColumnTypes)
} else {
result.columnTypes = result.columnTypes[:nLeftCols]
}
if onExpr != nil && core.MergeJoiner.Type == sqlbase.JoinType_INNER {
filterPlanning.remapIVars(onExpr)
err = result.planFilterExpr(flowCtx.NewEvalCtx(), *onExpr)
filterPlanning.projectOutExtraCols(&result, leftOutCols, rightOutCols)
}
case core.JoinReader != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
var c *columnarizer
c, err = wrapRowSource(ctx, flowCtx, inputs[0], spec.Input[0].ColumnTypes, func(input RowSource) (RowSource, error) {
var (
jr RowSource
err error
)
// The lookup and index joiners need to be passed the post-process specs,
// since they inspect them to figure out information about needed columns.
// This means that we'll let those processors do any renders or filters,
// which isn't ideal. We could improve this.
if len(core.JoinReader.LookupColumns) == 0 {
jr, err = newIndexJoiner(
flowCtx, spec.ProcessorID, core.JoinReader, input, post, nil, /* output */
)
} else {
jr, err = newJoinReader(
flowCtx, spec.ProcessorID, core.JoinReader, input, post, nil, /* output */
)
}
post = &distsqlpb.PostProcessSpec{}
if err != nil {
return nil, err
}
result.columnTypes = jr.OutputTypes()
return jr, nil
})
result.op, result.isStreaming = c, true
result.metadataSources = append(result.metadataSources, c)
case core.Sorter != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
input := inputs[0]
var inputTypes []coltypes.T
inputTypes, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
orderingCols := core.Sorter.OutputOrdering.Columns
matchLen := core.Sorter.OrderingMatchLen
if matchLen > 0 {
// The input is already partially ordered. Use a chunks sorter to avoid
// loading all the rows into memory.
result.op, err = exec.NewSortChunks(input, inputTypes, orderingCols, int(matchLen))
} else if post.Limit != 0 && post.Filter.Empty() && post.Limit+post.Offset < math.MaxUint16 {
// There is a limit specified with no post-process filter, so we know
// exactly how many rows the sorter should output. Choose a top K sorter,
// which uses a heap to avoid storing more rows than necessary.
k := uint16(post.Limit + post.Offset)
result.op, result.isStreaming = exec.NewTopKSorter(input, inputTypes, orderingCols, k), true
} else {
// No optimizations possible. Default to the standard sort operator.
result.op, err = exec.NewSorter(input, inputTypes, orderingCols)
}
result.columnTypes = spec.Input[0].ColumnTypes
case core.Windower != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
if len(core.Windower.WindowFns) != 1 {
return result, errors.Newf("only a single window function is currently supported")
}
wf := core.Windower.WindowFns[0]
if wf.Frame != nil &&
(wf.Frame.Mode != distsqlpb.WindowerSpec_Frame_RANGE ||
wf.Frame.Bounds.Start.BoundType != distsqlpb.WindowerSpec_Frame_UNBOUNDED_PRECEDING ||
(wf.Frame.Bounds.End != nil && wf.Frame.Bounds.End.BoundType != distsqlpb.WindowerSpec_Frame_CURRENT_ROW)) {
return result, errors.Newf("window functions with non-default window frames are not supported")
}
if wf.Func.AggregateFunc != nil {
return result, errors.Newf("aggregate functions used as window functions are not supported")
}
input := inputs[0]
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
tempPartitionColOffset, partitionColIdx := 0, -1
if len(core.Windower.PartitionBy) > 0 {
// TODO(yuzefovich): add support for hashing partitioner (probably by
// leveraging hash routers once we can distribute). The decision about
// which kind of partitioner to use should come from the optimizer.
input, err = exec.NewWindowSortingPartitioner(input, typs, core.Windower.PartitionBy, wf.Ordering.Columns, int(wf.OutputColIdx))
tempPartitionColOffset, partitionColIdx = 1, int(wf.OutputColIdx)
} else {
if len(wf.Ordering.Columns) > 0 {
input, err = exec.NewSorter(input, typs, wf.Ordering.Columns)
}
// TODO(yuzefovich): when both PARTITION BY and ORDER BY clauses are
// omitted, the window function operator is actually streaming.
}
if err != nil {
return result, err
}
orderingCols := make([]uint32, len(wf.Ordering.Columns))
for i, col := range wf.Ordering.Columns {
orderingCols[i] = col.ColIdx
}
switch *wf.Func.WindowFunc {
case distsqlpb.WindowerSpec_ROW_NUMBER:
result.op = vecbuiltins.NewRowNumberOperator(input, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
case distsqlpb.WindowerSpec_RANK:
result.op, err = vecbuiltins.NewRankOperator(input, typs, false /* dense */, orderingCols, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
case distsqlpb.WindowerSpec_DENSE_RANK:
result.op, err = vecbuiltins.NewRankOperator(input, typs, true /* dense */, orderingCols, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
default:
return result, errors.Newf("window function %s is not supported", wf.String())
}
if partitionColIdx != -1 {
// Window partitioner will append a temporary column to the batch which
// we want to project out.
projection := make([]uint32, 0, wf.OutputColIdx+1)
for i := uint32(0); i < wf.OutputColIdx; i++ {
projection = append(projection, i)
}
projection = append(projection, wf.OutputColIdx+1)
result.op = exec.NewSimpleProjectOp(result.op, int(wf.OutputColIdx+1), projection)
}
result.columnTypes = append(spec.Input[0].ColumnTypes, *types.Int)
default:
return result, errors.Newf("unsupported processor core %q", core)
}
if err != nil {
return result, err
}
// After constructing the base operator, calculate the memory usage
// of the operator.
if sMemOp, ok := result.op.(exec.StaticMemoryOperator); ok {
result.memUsage += sMemOp.EstimateStaticMemoryUsage()
}
log.VEventf(ctx, 1, "made op %T\n", result.op)
if result.columnTypes == nil {
return result, errors.AssertionFailedf("output columnTypes unset after planning %T", result.op)
}
if !post.Filter.Empty() {
if err = result.planFilterExpr(flowCtx.NewEvalCtx(), post.Filter); err != nil {
return result, err
}
}
if post.Projection {
result.op = exec.NewSimpleProjectOp(result.op, len(result.columnTypes), post.OutputColumns)
// Update output columnTypes.
newTypes := make([]types.T, 0, len(post.OutputColumns))
for _, j := range post.OutputColumns {
newTypes = append(newTypes, result.columnTypes[j])
}
result.columnTypes = newTypes
} else if post.RenderExprs != nil {
log.VEventf(ctx, 2, "planning render expressions %+v", post.RenderExprs)
var renderedCols []uint32
for _, expr := range post.RenderExprs {
var (
helper exprHelper
renderMem int
)
err := helper.init(expr, result.columnTypes, flowCtx.EvalCtx)
if err != nil {
return result, err
}
var outputIdx int
result.op, outputIdx, result.columnTypes, renderMem, err = planProjectionOperators(
flowCtx.NewEvalCtx(), helper.expr, result.columnTypes, result.op)
if err != nil {
return result, errors.Wrapf(err, "unable to columnarize render expression %q", expr)
}
if outputIdx < 0 {
return result, errors.AssertionFailedf("missing outputIdx")
}
result.memUsage += renderMem
renderedCols = append(renderedCols, uint32(outputIdx))
}
result.op = exec.NewSimpleProjectOp(result.op, len(result.columnTypes), renderedCols)
newTypes := make([]types.T, 0, len(renderedCols))
for _, j := range renderedCols {
newTypes = append(newTypes, result.columnTypes[j])
}
result.columnTypes = newTypes
}
if post.Offset != 0 {
result.op = exec.NewOffsetOp(result.op, post.Offset)
}
if post.Limit != 0 {
result.op = exec.NewLimitOp(result.op, post.Limit)
}
return result, err
}
type filterPlanningState struct {
numLeftInputCols int
numRightInputCols int
// indexVarMap will be populated when rendering all needed columns in case
// when at least one column from either side is used by the filter.
indexVarMap []int
extraLeftOutCols int
extraRightOutCols int
}
func newFilterPlanningState(numLeftInputCols, numRightInputCols int) *filterPlanningState {
return &filterPlanningState{
numLeftInputCols: numLeftInputCols,
numRightInputCols: numRightInputCols,
}
}
// renderAllNeededCols makes sure that all columns used by filter expression
// will be output. It does so by extracting the indices of all indexed vars
// used in the expression and appending those that are missing from *OutCols
// slices to the slices. Additionally, it populates p.indexVarMap to be used
// later to correctly remap the indexed vars and stores information about how
// many extra columns are added so that those extra columns could be projected
// out after the filter has been run.
// It returns updated leftOutCols and rightOutCols.
func (p *filterPlanningState) renderAllNeededCols(
filter distsqlpb.Expression, leftOutCols []uint32, rightOutCols []uint32,
) ([]uint32, []uint32) {
neededColumnsForFilter := findIVarsInRange(
filter,
0, /* start */
p.numLeftInputCols+p.numRightInputCols,
)
if len(neededColumnsForFilter) > 0 {
// At least one column is referenced by the filter expression.
p.indexVarMap = make([]int, p.numLeftInputCols+p.numRightInputCols)
for i := range p.indexVarMap {
p.indexVarMap[i] = -1
}
// First, we process only the left side.
for i, lCol := range leftOutCols {
p.indexVarMap[lCol] = i
}
for _, neededCol := range neededColumnsForFilter {
if int(neededCol) < p.numLeftInputCols {
if p.indexVarMap[neededCol] == -1 {
p.indexVarMap[neededCol] = len(leftOutCols)
leftOutCols = append(leftOutCols, neededCol)
p.extraLeftOutCols++
}
}
}
// Now that we know how many columns from the left will be output, we can
// process the right side.
//
// Here is the explanation of all the indices' dance below:
// suppose we have two inputs with three columns in each, the filter
// expression as @1 = @4 AND @3 = @5, and leftOutCols = {0} and
// rightOutCols = {0} when this method was called. Note that only
// ordinals in the expression are counting from 1, everything else is
// zero-based.
// - After we processed the left side above, we have the following state:
// neededColumnsForFilter = {0, 2, 3, 4}
// leftOutCols = {0, 2}
// p.indexVarMap = {0, -1, 1, -1, -1, -1}
// - We calculate rColOffset = 3 to know which columns for filter are from
// the right side as well as to remap those for rightOutCols (the
// remapping step is needed because rightOutCols "thinks" only in the
// context of the right side).
// - Next, we add already present rightOutCols to the indexed var map:
// rightOutCols = {0}
// p.indexVarMap = {0, -1, 1, 2, -1, -1}
// Note that we needed to remap the column index, and we could do so only
// after the left side has been processed because we need to know how
// many columns will be output from the left.
// - Then, we go through the needed columns for filter slice again, and add
// any that are still missing to rightOutCols:
// rightOutCols = {0, 1}
// p.indexVarMap = {0, -1, 1, 2, 3, -1}
// - We also stored the fact that we appended 1 extra column for both
// inputs, and we will project those out.
rColOffset := uint32(p.numLeftInputCols)
for i, rCol := range rightOutCols {
p.indexVarMap[rCol+rColOffset] = len(leftOutCols) + i
}
for _, neededCol := range neededColumnsForFilter {
if neededCol >= rColOffset {
if p.indexVarMap[neededCol] == -1 {
p.indexVarMap[neededCol] = len(rightOutCols) + len(leftOutCols)
rightOutCols = append(rightOutCols, neededCol-rColOffset)
p.extraRightOutCols++
}
}
}
}
return leftOutCols, rightOutCols
}
// isFilterOnlyOnLeft returns whether the filter expression doesn't use columns
// from the right side.
func (p *filterPlanningState) isFilterOnlyOnLeft(filter distsqlpb.Expression) bool {
// Find all needed columns for filter only from the right side.
neededColumnsForFilter := findIVarsInRange(
filter, p.numLeftInputCols, p.numLeftInputCols+p.numRightInputCols,
)
return len(neededColumnsForFilter) == 0
}
// remapIVars remaps tree.IndexedVars in expr using p.indexVarMap. Note that
// expr is modified in-place.
func (p *filterPlanningState) remapIVars(expr *distsqlpb.Expression) {
if p.indexVarMap == nil {
// If p.indexVarMap is nil, then there is no remapping to do.
return
}
if expr.LocalExpr != nil {
expr.LocalExpr = sqlbase.RemapIVarsInTypedExpr(expr.LocalExpr, p.indexVarMap)
} else {
// We iterate in the reverse order so that the multiple digit numbers are
// handled correctly (consider an expression like @1 AND @11).
for idx := len(p.indexVarMap) - 1; idx >= 0; idx-- {
if p.indexVarMap[idx] != -1 {
// We need +1 below because the ordinals are counting from 1.
expr.Expr = strings.ReplaceAll(
expr.Expr,
fmt.Sprintf("@%d", idx+1),
fmt.Sprintf("@%d", p.indexVarMap[idx]+1),
)
}
}
}
}
// projectOutExtraCols, possibly, adds a projection to remove all the extra
// columns that were needed by the filter expression.
func (p *filterPlanningState) projectOutExtraCols(
result *newColOperatorResult, leftOutCols, rightOutCols []uint32,
) {
if p.extraLeftOutCols+p.extraRightOutCols > 0 {
projection := make([]uint32, 0, len(leftOutCols)+len(rightOutCols)-p.extraLeftOutCols-p.extraRightOutCols)
for i := 0; i < len(leftOutCols)-p.extraLeftOutCols; i++ {
projection = append(projection, uint32(i))
}
for i := 0; i < len(rightOutCols)-p.extraRightOutCols; i++ {
projection = append(projection, uint32(i+len(leftOutCols)))
}
result.op = exec.NewSimpleProjectOp(result.op, len(leftOutCols)+len(rightOutCols), projection)
}
}
func (r *newColOperatorResult) planFilterExpr(
evalCtx *tree.EvalContext, filter distsqlpb.Expression,
) error {
var (
helper exprHelper
selectionMem int
)
err := helper.init(filter, r.columnTypes, evalCtx)
if err != nil {
return err
}
if helper.expr == tree.DNull {
// The filter expression is tree.DNull meaning that it is always false, so
// we put a zero operator.
r.op = exec.NewZeroOp(r.op)
return nil
}
var filterColumnTypes []types.T
r.op, _, filterColumnTypes, selectionMem, err = planSelectionOperators(evalCtx, helper.expr, r.columnTypes, r.op)
if err != nil {
return errors.Wrapf(err, "unable to columnarize filter expression %q", filter.Expr)
}
r.memUsage += selectionMem
if len(filterColumnTypes) > len(r.columnTypes) {
// Additional columns were appended to store projections while evaluating
// the filter. Project them away.
var outputColumns []uint32
for i := range r.columnTypes {
outputColumns = append(outputColumns, uint32(i))
}
r.op = exec.NewSimpleProjectOp(r.op, len(filterColumnTypes), outputColumns)
}
return nil
}
func planSelectionOperators(
ctx *tree.EvalContext, expr tree.TypedExpr, columnTypes []types.T, input exec.Operator,
) (op exec.Operator, resultIdx int, ct []types.T, memUsed int, err error) {
switch t := expr.(type) {
case *tree.IndexedVar:
return exec.NewBoolVecToSelOp(input, t.Idx), -1, columnTypes, memUsed, nil
case *tree.AndExpr:
var leftOp, rightOp exec.Operator
var memUsedLeft, memUsedRight int
leftOp, _, ct, memUsedLeft, err = planSelectionOperators(ctx, t.TypedLeft(), columnTypes, input)
if err != nil {
return nil, resultIdx, ct, memUsed, err
}
rightOp, resultIdx, ct, memUsedRight, err = planSelectionOperators(
ctx, t.TypedRight(), ct, leftOp)
return rightOp, resultIdx, ct, memUsedLeft + memUsedRight, err
case *tree.OrExpr:
// OR expressions are handled by converting them to an equivalent CASE
// statement. Since CASE statements don't have a selection form, plan a
// projection and then convert the resulting boolean to a selection vector.
op, resultIdx, ct, memUsed, err = planProjectionOperators(ctx, expr, columnTypes, input)
op = exec.NewBoolVecToSelOp(op, resultIdx)
return op, resultIdx, ct, memUsed, err
case *tree.CaseExpr:
op, resultIdx, ct, memUsed, err = planProjectionOperators(ctx, expr, columnTypes, input)
op = exec.NewBoolVecToSelOp(op, resultIdx)
return op, resultIdx, ct, memUsed, err
case *tree.ComparisonExpr:
cmpOp := t.Operator
leftOp, leftIdx, ct, memUsageLeft, err := planProjectionOperators(ctx, t.TypedLeft(), columnTypes, input)
if err != nil {
return nil, resultIdx, ct, memUsageLeft, err
}
lTyp := &ct[leftIdx]
if constArg, ok := t.Right.(tree.Datum); ok {
if t.Operator == tree.Like || t.Operator == tree.NotLike {
negate := t.Operator == tree.NotLike
op, err := exec.GetLikeOperator(
ctx, leftOp, leftIdx, string(tree.MustBeDString(constArg)), negate)
return op, resultIdx, ct, memUsageLeft, err
}
if t.Operator == tree.In || t.Operator == tree.NotIn {
negate := t.Operator == tree.NotIn
datumTuple, ok := tree.AsDTuple(constArg)
if !ok {
err = errors.Errorf("IN is only supported for constant expressions")
return nil, resultIdx, ct, memUsed, err
}
op, err := exec.GetInOperator(lTyp, leftOp, leftIdx, datumTuple, negate)
return op, resultIdx, ct, memUsageLeft, err
}
op, err := exec.GetSelectionConstOperator(lTyp, t.TypedRight().ResolvedType(), cmpOp, leftOp, leftIdx, constArg)
return op, resultIdx, ct, memUsageLeft, err
}
rightOp, rightIdx, ct, memUsageRight, err := planProjectionOperators(ctx, t.TypedRight(), ct, leftOp)
if err != nil {
return nil, resultIdx, ct, memUsageLeft + memUsageRight, err
}
op, err := exec.GetSelectionOperator(lTyp, &ct[rightIdx], cmpOp, rightOp, leftIdx, rightIdx)
return op, resultIdx, ct, memUsageLeft + memUsageRight, err
default:
return nil, resultIdx, nil, memUsed, errors.Errorf("unhandled selection expression type: %s", reflect.TypeOf(t))
}
}
// planTypedMaybeNullProjectionOperators is used to plan projection operators, but is able to
// plan constNullOperators in the case that we know the "type" of the null. It is currently
// unsafe to plan a constNullOperator when we don't know the type of the null.
func planTypedMaybeNullProjectionOperators(
ctx *tree.EvalContext,
expr tree.TypedExpr,
exprTyp *types.T,
columnTypes []types.T,
input exec.Operator,
) (op exec.Operator, resultIdx int, ct []types.T, memUsed int, err error) {
if expr == tree.DNull {
resultIdx = len(columnTypes)
op = exec.NewConstNullOp(input, resultIdx, typeconv.FromColumnType(exprTyp))
ct = append(columnTypes, *exprTyp)
memUsed = op.(exec.StaticMemoryOperator).EstimateStaticMemoryUsage()
return op, resultIdx, ct, memUsed, nil
}
return planProjectionOperators(ctx, expr, columnTypes, input)
}
// planProjectionOperators plans a chain of operators to execute the provided
// expression. It returns the tail of the chain, as well as the column index
// of the expression's result (if any, otherwise -1) and the column types of the
// resulting batches.
func planProjectionOperators(
ctx *tree.EvalContext, expr tree.TypedExpr, columnTypes []types.T, input exec.Operator,
) (op exec.Operator, resultIdx int, ct []types.T, memUsed int, err error) {
resultIdx = -1
switch t := expr.(type) {
case *tree.IndexedVar:
return input, t.Idx, columnTypes, memUsed, nil
case *tree.ComparisonExpr:
return planProjectionExpr(ctx, t.Operator, t.ResolvedType(), t.TypedLeft(), t.TypedRight(), columnTypes, input)
case *tree.BinaryExpr:
return planProjectionExpr(ctx, t.Operator, t.ResolvedType(), t.TypedLeft(), t.TypedRight(), columnTypes, input)
case *tree.CastExpr:
expr := t.Expr.(tree.TypedExpr)
// If the expression is NULL, we use planTypedMaybeNullProjectionOperators instead of planProjectionOperators
// because we can say that the type of the NULL is the type that we are casting to, rather than unknown.
// We can't use planProjectionOperators because it will reject planning a constNullOp without knowing
// the post typechecking "type" of the NULL.
if expr.ResolvedType() == types.Unknown {