-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
opt_exec_factory.go
2245 lines (2029 loc) · 67.2 KB
/
opt_exec_factory.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 sql
import (
"bytes"
"compress/zlib"
"context"
"encoding/base64"
"fmt"
"net/url"
"strings"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/inverted"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/constraint"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec/explain"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treewindow"
"github.com/cockroachdb/cockroach/pkg/sql/span"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/intsets"
"github.com/cockroachdb/errors"
)
type execFactory struct {
ctx context.Context
planner *planner
// alloc is allocated lazily the first time it is needed and shared among
// all mutation planNodes created by the factory. It should not be accessed
// directly - use getDatumAlloc() instead.
alloc *tree.DatumAlloc
// isExplain is true if this factory is used to build a statement inside
// EXPLAIN or EXPLAIN ANALYZE.
isExplain bool
}
var _ exec.Factory = &execFactory{}
func newExecFactory(ctx context.Context, p *planner) *execFactory {
return &execFactory{
ctx: ctx,
planner: p,
}
}
// Ctx implements the Factory interface.
func (ef *execFactory) Ctx() context.Context {
return ef.ctx
}
func (ef *execFactory) getDatumAlloc() *tree.DatumAlloc {
if ef.alloc == nil {
ef.alloc = &tree.DatumAlloc{}
}
return ef.alloc
}
// ConstructValues is part of the exec.Factory interface.
func (ef *execFactory) ConstructValues(
rows [][]tree.TypedExpr, cols colinfo.ResultColumns,
) (exec.Node, error) {
if len(cols) == 0 && len(rows) == 1 {
return &unaryNode{}, nil
}
if len(rows) == 0 {
return &zeroNode{columns: cols}, nil
}
return &valuesNode{
columns: cols,
tuples: rows,
specifiedInQuery: true,
}, nil
}
// ConstructLiteralValues is part of the exec.Factory interface.
func (ef *execFactory) ConstructLiteralValues(
rows tree.ExprContainer, cols colinfo.ResultColumns,
) (exec.Node, error) {
if len(cols) == 0 && rows.NumRows() == 1 {
return &unaryNode{}, nil
}
if rows.NumRows() == 0 {
return &zeroNode{columns: cols}, nil
}
switch t := rows.(type) {
case *rowcontainer.RowContainer:
return &valuesNode{
columns: cols,
specifiedInQuery: true,
externallyOwnedContainer: true,
valuesRun: valuesRun{rows: t},
}, nil
case *tree.VectorRows:
return &valuesNode{
columns: cols,
specifiedInQuery: true,
externallyOwnedContainer: true,
coldataBatch: t.Batch,
}, nil
default:
return nil, errors.AssertionFailedf("unexpected rows type %T in ConstructLiteralValues", rows)
}
}
// ConstructScan is part of the exec.Factory interface.
func (ef *execFactory) ConstructScan(
table cat.Table, index cat.Index, params exec.ScanParams, reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
if table.IsVirtualTable() {
return ef.constructVirtualScan(table, index, params, reqOrdering)
}
tabDesc := table.(*optTable).desc
idx := index.(*optIndex).idx
// Create a scanNode.
scan := ef.planner.Scan()
colCfg := makeScanColumnsConfig(table, params.NeededCols)
if err := scan.initTable(ef.ctx, ef.planner, tabDesc, colCfg); err != nil {
return nil, err
}
if params.IndexConstraint != nil && params.IndexConstraint.IsContradiction() {
return newZeroNode(scan.resultColumns), nil
}
scan.index = idx
scan.hardLimit = params.HardLimit
scan.softLimit = params.SoftLimit
scan.reverse = params.Reverse
scan.parallelize = params.Parallelize
var err error
scan.spans, err = generateScanSpans(ef.planner.EvalContext(), ef.planner.ExecCfg().Codec, tabDesc, idx, params)
if err != nil {
return nil, err
}
scan.isFull = len(scan.spans) == 1 && scan.spans[0].EqualValue(
scan.desc.IndexSpan(ef.planner.ExecCfg().Codec, scan.index.GetID()),
)
if err = colCfg.assertValidReqOrdering(reqOrdering); err != nil {
return nil, err
}
scan.reqOrdering = ReqOrdering(reqOrdering)
scan.estimatedRowCount = uint64(params.EstimatedRowCount)
scan.lockingStrength = descpb.ToScanLockingStrength(params.Locking.Strength)
scan.lockingWaitPolicy = descpb.ToScanLockingWaitPolicy(params.Locking.WaitPolicy)
scan.localityOptimized = params.LocalityOptimized
if !ef.isExplain && !(ef.planner.isInternalPlanner || ef.planner.SessionData().Internal) {
idxUsageKey := roachpb.IndexUsageKey{
TableID: roachpb.TableID(tabDesc.GetID()),
IndexID: roachpb.IndexID(idx.GetID()),
}
ef.planner.extendedEvalCtx.indexUsageStats.RecordRead(idxUsageKey)
}
return scan, nil
}
func generateScanSpans(
evalCtx *eval.Context,
codec keys.SQLCodec,
tabDesc catalog.TableDescriptor,
index catalog.Index,
params exec.ScanParams,
) (roachpb.Spans, error) {
var sb span.Builder
sb.Init(evalCtx, codec, tabDesc, index)
if params.InvertedConstraint != nil {
return sb.SpansFromInvertedSpans(params.InvertedConstraint, params.IndexConstraint, nil /* scratch */)
}
splitter := span.MakeSplitter(tabDesc, index, params.NeededCols)
return sb.SpansFromConstraint(params.IndexConstraint, splitter)
}
func (ef *execFactory) constructVirtualScan(
table cat.Table, index cat.Index, params exec.ScanParams, reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
return constructVirtualScan(
ef, ef.planner, table, index, params, reqOrdering,
func(d *delayedNode) (exec.Node, error) { return d, nil },
)
}
func asDataSource(n exec.Node) planDataSource {
plan := n.(planNode)
return planDataSource{
columns: planColumns(plan),
plan: plan,
}
}
// ConstructFilter is part of the exec.Factory interface.
func (ef *execFactory) ConstructFilter(
n exec.Node, filter tree.TypedExpr, reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
// Create a filterNode.
src := asDataSource(n)
f := &filterNode{
source: src,
}
f.ivarHelper = tree.MakeIndexedVarHelper(f, len(src.columns))
f.filter = f.ivarHelper.Rebind(filter)
if f.filter == nil {
// Filter statically evaluates to true. Just return the input plan.
return n, nil
}
f.reqOrdering = ReqOrdering(reqOrdering)
// If there's a spool, pull it up.
if spool, ok := f.source.plan.(*spoolNode); ok {
f.source.plan = spool.source
spool.source = f
return spool, nil
}
return f, nil
}
// ConstructInvertedFilter is part of the exec.Factory interface.
func (ef *execFactory) ConstructInvertedFilter(
n exec.Node,
invFilter *inverted.SpanExpression,
preFiltererExpr tree.TypedExpr,
preFiltererType *types.T,
invColumn exec.NodeColumnOrdinal,
) (exec.Node, error) {
inputCols := planColumns(n.(planNode))
columns := make(colinfo.ResultColumns, len(inputCols))
copy(columns, inputCols)
n = &invertedFilterNode{
input: n.(planNode),
expression: invFilter,
preFiltererExpr: preFiltererExpr,
preFiltererType: preFiltererType,
invColumn: int(invColumn),
resultColumns: columns,
}
return n, nil
}
// ConstructSimpleProject is part of the exec.Factory interface.
func (ef *execFactory) ConstructSimpleProject(
n exec.Node, cols []exec.NodeColumnOrdinal, reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
return constructSimpleProjectForPlanNode(n.(planNode), cols, nil /* colNames */, reqOrdering)
}
func constructSimpleProjectForPlanNode(
n planNode, cols []exec.NodeColumnOrdinal, colNames []string, reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
// If the top node is already a renderNode, just rearrange the columns. But
// we don't want to duplicate a rendering expression (in case it is expensive
// to compute or has side-effects); so if we have duplicates we avoid this
// optimization (and add a new renderNode).
if r, ok := n.(*renderNode); ok && !hasDuplicates(cols) {
oldCols, oldRenders := r.columns, r.render
r.columns = make(colinfo.ResultColumns, len(cols))
r.render = make([]tree.TypedExpr, len(cols))
for i, ord := range cols {
r.columns[i] = oldCols[ord]
if colNames != nil {
r.columns[i].Name = colNames[i]
}
r.render[i] = oldRenders[ord]
}
r.reqOrdering = ReqOrdering(reqOrdering)
return r, nil
}
inputCols := planColumns(n)
var rb renderBuilder
rb.init(n, reqOrdering)
exprs := make(tree.TypedExprs, len(cols))
for i, col := range cols {
exprs[i] = rb.r.ivarHelper.IndexedVar(int(col))
}
var resultTypes []*types.T
if colNames != nil {
// We will need updated result types.
resultTypes = make([]*types.T, len(cols))
for i := range exprs {
resultTypes[i] = exprs[i].ResolvedType()
}
}
resultCols := getResultColumnsForSimpleProject(cols, colNames, resultTypes, inputCols)
rb.setOutput(exprs, resultCols)
return rb.res, nil
}
func hasDuplicates(cols []exec.NodeColumnOrdinal) bool {
var set intsets.Fast
for _, c := range cols {
if set.Contains(int(c)) {
return true
}
set.Add(int(c))
}
return false
}
// ConstructSerializingProject is part of the exec.Factory interface.
func (ef *execFactory) ConstructSerializingProject(
n exec.Node, cols []exec.NodeColumnOrdinal, colNames []string,
) (exec.Node, error) {
node := n.(planNode)
// If we are just renaming columns, we can do that in place.
if len(cols) == len(planColumns(node)) {
identity := true
for i := range cols {
if cols[i] != exec.NodeColumnOrdinal(i) {
identity = false
break
}
}
if identity {
inputCols := planMutableColumns(node)
for i := range inputCols {
inputCols[i].Name = colNames[i]
}
// TODO(yuzefovich): if n is not a renderNode, we won't serialize
// it, but this is breaking the contract of
// ConstructSerializingProject. We should clean this up, but in the
// mean time it seems acceptable given that the method is called
// only for the root node.
if r, ok := n.(*renderNode); ok {
r.serialize = true
}
return n, nil
}
}
res, err := constructSimpleProjectForPlanNode(node, cols, colNames, nil /* reqOrdering */)
if err != nil {
return nil, err
}
switch r := res.(type) {
case *renderNode:
r.serialize = true
case *spoolNode:
// If we pulled up a spoolNode, we don't need to materialize the
// ordering (because all mutations are currently not distributed).
// TODO(yuzefovich): evaluate whether we still need to push renderings
// through the spoolNode.
default:
return nil, errors.AssertionFailedf("unexpected planNode type %T in ConstructSerializingProject", res)
}
return res, nil
}
// ConstructRender is part of the exec.Factory interface.
// N.B.: The input exprs will be modified.
func (ef *execFactory) ConstructRender(
n exec.Node,
columns colinfo.ResultColumns,
exprs tree.TypedExprs,
reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
var rb renderBuilder
rb.init(n, reqOrdering)
for i, expr := range exprs {
exprs[i] = rb.r.ivarHelper.Rebind(expr)
}
rb.setOutput(exprs, columns)
return rb.res, nil
}
// ConstructHashJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructHashJoin(
joinType descpb.JoinType,
left, right exec.Node,
leftEqCols, rightEqCols []exec.NodeColumnOrdinal,
leftEqColsAreKey, rightEqColsAreKey bool,
extraOnCond tree.TypedExpr,
) (exec.Node, error) {
p := ef.planner
leftSrc := asDataSource(left)
rightSrc := asDataSource(right)
pred := makePredicate(joinType, leftSrc.columns, rightSrc.columns)
numEqCols := len(leftEqCols)
pred.leftEqualityIndices = leftEqCols
pred.rightEqualityIndices = rightEqCols
nameBuf := make(tree.NameList, 2*numEqCols)
pred.leftColNames = nameBuf[:numEqCols:numEqCols]
pred.rightColNames = nameBuf[numEqCols:]
for i := range leftEqCols {
pred.leftColNames[i] = tree.Name(leftSrc.columns[leftEqCols[i]].Name)
pred.rightColNames[i] = tree.Name(rightSrc.columns[rightEqCols[i]].Name)
}
pred.leftEqKey = leftEqColsAreKey
pred.rightEqKey = rightEqColsAreKey
pred.onCond = pred.iVarHelper.Rebind(extraOnCond)
return p.makeJoinNode(leftSrc, rightSrc, pred), nil
}
// ConstructApplyJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructApplyJoin(
joinType descpb.JoinType,
left exec.Node,
rightColumns colinfo.ResultColumns,
onCond tree.TypedExpr,
planRightSideFn exec.ApplyJoinPlanRightSideFn,
) (exec.Node, error) {
leftSrc := asDataSource(left)
pred := makePredicate(joinType, leftSrc.columns, rightColumns)
pred.onCond = pred.iVarHelper.Rebind(onCond)
return newApplyJoinNode(joinType, leftSrc, rightColumns, pred, planRightSideFn)
}
// ConstructMergeJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructMergeJoin(
joinType descpb.JoinType,
left, right exec.Node,
onCond tree.TypedExpr,
leftOrdering, rightOrdering colinfo.ColumnOrdering,
reqOrdering exec.OutputOrdering,
leftEqColsAreKey, rightEqColsAreKey bool,
) (exec.Node, error) {
var err error
p := ef.planner
leftSrc := asDataSource(left)
rightSrc := asDataSource(right)
pred := makePredicate(joinType, leftSrc.columns, rightSrc.columns)
pred.onCond = pred.iVarHelper.Rebind(onCond)
node := p.makeJoinNode(leftSrc, rightSrc, pred)
pred.leftEqKey = leftEqColsAreKey
pred.rightEqKey = rightEqColsAreKey
pred.leftEqualityIndices, pred.rightEqualityIndices, node.mergeJoinOrdering, err = getEqualityIndicesAndMergeJoinOrdering(leftOrdering, rightOrdering)
if err != nil {
return nil, err
}
n := len(leftOrdering)
pred.leftColNames = make(tree.NameList, n)
pred.rightColNames = make(tree.NameList, n)
for i := 0; i < n; i++ {
leftColIdx, rightColIdx := leftOrdering[i].ColIdx, rightOrdering[i].ColIdx
pred.leftColNames[i] = tree.Name(leftSrc.columns[leftColIdx].Name)
pred.rightColNames[i] = tree.Name(rightSrc.columns[rightColIdx].Name)
}
// Set up node.props, which tells the distsql planner to maintain the
// resulting ordering (if needed).
node.reqOrdering = ReqOrdering(reqOrdering)
return node, nil
}
// ConstructScalarGroupBy is part of the exec.Factory interface.
func (ef *execFactory) ConstructScalarGroupBy(
input exec.Node, aggregations []exec.AggInfo,
) (exec.Node, error) {
// There are no grouping columns with scalar GroupBy, so we create empty
// arguments upfront to be passed into getResultColumnsForGroupBy call
// below.
var inputCols colinfo.ResultColumns
var groupCols []exec.NodeColumnOrdinal
n := &groupNode{
plan: input.(planNode),
funcs: make([]*aggregateFuncHolder, 0, len(aggregations)),
columns: getResultColumnsForGroupBy(inputCols, groupCols, aggregations),
isScalar: true,
}
if err := ef.addAggregations(n, aggregations); err != nil {
return nil, err
}
return n, nil
}
// ConstructGroupBy is part of the exec.Factory interface.
func (ef *execFactory) ConstructGroupBy(
input exec.Node,
groupCols []exec.NodeColumnOrdinal,
groupColOrdering colinfo.ColumnOrdering,
aggregations []exec.AggInfo,
reqOrdering exec.OutputOrdering,
groupingOrderType exec.GroupingOrderType,
) (exec.Node, error) {
inputPlan := input.(planNode)
inputCols := planColumns(inputPlan)
// TODO(harding): Use groupingOrder to determine when to use a hash
// aggregator.
n := &groupNode{
plan: inputPlan,
funcs: make([]*aggregateFuncHolder, 0, len(groupCols)+len(aggregations)),
columns: getResultColumnsForGroupBy(inputCols, groupCols, aggregations),
groupCols: convertNodeOrdinalsToInts(groupCols),
groupColOrdering: groupColOrdering,
isScalar: false,
reqOrdering: ReqOrdering(reqOrdering),
}
for _, col := range n.groupCols {
// TODO(radu): only generate the grouping columns we actually need.
f := newAggregateFuncHolder(
builtins.AnyNotNull,
[]int{col},
nil, /* arguments */
false, /* isDistinct */
)
n.funcs = append(n.funcs, f)
}
if err := ef.addAggregations(n, aggregations); err != nil {
return nil, err
}
return n, nil
}
func (ef *execFactory) addAggregations(n *groupNode, aggregations []exec.AggInfo) error {
for i := range aggregations {
agg := &aggregations[i]
renderIdxs := convertNodeOrdinalsToInts(agg.ArgCols)
f := newAggregateFuncHolder(
agg.FuncName,
renderIdxs,
agg.ConstArgs,
agg.Distinct,
)
f.filterRenderIdx = int(agg.Filter)
n.funcs = append(n.funcs, f)
}
return nil
}
// ConstructDistinct is part of the exec.Factory interface.
func (ef *execFactory) ConstructDistinct(
input exec.Node,
distinctCols, orderedCols exec.NodeColumnOrdinalSet,
reqOrdering exec.OutputOrdering,
nullsAreDistinct bool,
errorOnDup string,
) (exec.Node, error) {
return &distinctNode{
plan: input.(planNode),
distinctOnColIdxs: distinctCols,
columnsInOrder: orderedCols,
reqOrdering: ReqOrdering(reqOrdering),
nullsAreDistinct: nullsAreDistinct,
errorOnDup: errorOnDup,
}, nil
}
// ConstructHashSetOp is part of the exec.Factory interface.
func (ef *execFactory) ConstructHashSetOp(
typ tree.UnionType, all bool, left, right exec.Node,
) (exec.Node, error) {
return ef.planner.newUnionNode(
typ, all, left.(planNode), right.(planNode), nil, nil, 0, /* hardLimit */
false, /* enforceHomeRegion */
)
}
// ConstructStreamingSetOp is part of the exec.Factory interface.
func (ef *execFactory) ConstructStreamingSetOp(
typ tree.UnionType,
all bool,
left, right exec.Node,
streamingOrdering colinfo.ColumnOrdering,
reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
return ef.planner.newUnionNode(
typ,
all,
left.(planNode),
right.(planNode),
streamingOrdering,
ReqOrdering(reqOrdering),
0, /* hardLimit */
false, /* enforceHomeRegion */
)
}
// ConstructUnionAll is part of the exec.Factory interface.
func (ef *execFactory) ConstructUnionAll(
left, right exec.Node, reqOrdering exec.OutputOrdering, hardLimit uint64, enforceHomeRegion bool,
) (exec.Node, error) {
return ef.planner.newUnionNode(
tree.UnionOp,
true, /* all */
left.(planNode),
right.(planNode),
colinfo.ColumnOrdering(reqOrdering),
ReqOrdering(reqOrdering),
hardLimit,
enforceHomeRegion,
)
}
// ConstructSort is part of the exec.Factory interface.
func (ef *execFactory) ConstructSort(
input exec.Node, ordering exec.OutputOrdering, alreadyOrderedPrefix int,
) (exec.Node, error) {
return &sortNode{
plan: input.(planNode),
ordering: colinfo.ColumnOrdering(ordering),
alreadyOrderedPrefix: alreadyOrderedPrefix,
}, nil
}
// ConstructOrdinality is part of the exec.Factory interface.
func (ef *execFactory) ConstructOrdinality(input exec.Node, colName string) (exec.Node, error) {
plan := input.(planNode)
inputColumns := planColumns(plan)
cols := make(colinfo.ResultColumns, len(inputColumns)+1)
copy(cols, inputColumns)
cols[len(cols)-1] = colinfo.ResultColumn{
Name: colName,
Typ: types.Int,
}
return &ordinalityNode{
source: plan,
columns: cols,
}, nil
}
// ConstructIndexJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructIndexJoin(
input exec.Node,
table cat.Table,
keyCols []exec.NodeColumnOrdinal,
tableCols exec.TableColumnOrdinalSet,
reqOrdering exec.OutputOrdering,
locking opt.Locking,
limitHint int64,
) (exec.Node, error) {
tabDesc := table.(*optTable).desc
colCfg := makeScanColumnsConfig(table, tableCols)
cols := makeColList(table, tableCols)
tableScan := ef.planner.Scan()
if err := tableScan.initTable(ef.ctx, ef.planner, tabDesc, colCfg); err != nil {
return nil, err
}
idx := tabDesc.GetPrimaryIndex()
tableScan.index = idx
tableScan.disableBatchLimit()
tableScan.lockingStrength = descpb.ToScanLockingStrength(locking.Strength)
tableScan.lockingWaitPolicy = descpb.ToScanLockingWaitPolicy(locking.WaitPolicy)
if !ef.isExplain && !(ef.planner.isInternalPlanner || ef.planner.SessionData().Internal) {
idxUsageKey := roachpb.IndexUsageKey{
TableID: roachpb.TableID(tabDesc.GetID()),
IndexID: roachpb.IndexID(idx.GetID()),
}
ef.planner.extendedEvalCtx.indexUsageStats.RecordRead(idxUsageKey)
}
n := &indexJoinNode{
input: input.(planNode),
table: tableScan,
cols: cols,
resultColumns: colinfo.ResultColumnsFromColumns(tabDesc.GetID(), cols),
reqOrdering: ReqOrdering(reqOrdering),
limitHint: limitHint,
}
n.keyCols = make([]int, len(keyCols))
for i, c := range keyCols {
n.keyCols[i] = int(c)
}
return n, nil
}
// ConstructLookupJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructLookupJoin(
joinType descpb.JoinType,
input exec.Node,
table cat.Table,
index cat.Index,
eqCols []exec.NodeColumnOrdinal,
eqColsAreKey bool,
lookupExpr tree.TypedExpr,
remoteLookupExpr tree.TypedExpr,
lookupCols exec.TableColumnOrdinalSet,
onCond tree.TypedExpr,
isFirstJoinInPairedJoiner bool,
isSecondJoinInPairedJoiner bool,
reqOrdering exec.OutputOrdering,
locking opt.Locking,
limitHint int64,
remoteOnlyLookups bool,
) (exec.Node, error) {
if table.IsVirtualTable() {
return ef.constructVirtualTableLookupJoin(joinType, input, table, index, eqCols, lookupCols, onCond)
}
tabDesc := table.(*optTable).desc
idx := index.(*optIndex).idx
colCfg := makeScanColumnsConfig(table, lookupCols)
tableScan := ef.planner.Scan()
if err := tableScan.initTable(ef.ctx, ef.planner, tabDesc, colCfg); err != nil {
return nil, err
}
tableScan.index = idx
tableScan.lockingStrength = descpb.ToScanLockingStrength(locking.Strength)
tableScan.lockingWaitPolicy = descpb.ToScanLockingWaitPolicy(locking.WaitPolicy)
if !ef.isExplain && !(ef.planner.isInternalPlanner || ef.planner.SessionData().Internal) {
idxUsageKey := roachpb.IndexUsageKey{
TableID: roachpb.TableID(tabDesc.GetID()),
IndexID: roachpb.IndexID(idx.GetID()),
}
ef.planner.extendedEvalCtx.indexUsageStats.RecordRead(idxUsageKey)
}
n := &lookupJoinNode{
input: input.(planNode),
table: tableScan,
joinType: joinType,
eqColsAreKey: eqColsAreKey,
isFirstJoinInPairedJoiner: isFirstJoinInPairedJoiner,
isSecondJoinInPairedJoiner: isSecondJoinInPairedJoiner,
reqOrdering: ReqOrdering(reqOrdering),
limitHint: limitHint,
remoteOnlyLookups: remoteOnlyLookups,
}
n.eqCols = make([]int, len(eqCols))
for i, c := range eqCols {
n.eqCols[i] = int(c)
}
pred := makePredicate(joinType, planColumns(input.(planNode)), planColumns(tableScan))
if lookupExpr != nil {
n.lookupExpr = pred.iVarHelper.Rebind(lookupExpr)
}
if remoteLookupExpr != nil {
n.remoteLookupExpr = pred.iVarHelper.Rebind(remoteLookupExpr)
}
if onCond != nil && onCond != tree.DBoolTrue {
n.onCond = pred.iVarHelper.Rebind(onCond)
}
n.columns = pred.cols
if isFirstJoinInPairedJoiner {
n.columns = append(n.columns, colinfo.ResultColumn{Name: "cont", Typ: types.Bool})
}
return n, nil
}
func (ef *execFactory) constructVirtualTableLookupJoin(
joinType descpb.JoinType,
input exec.Node,
table cat.Table,
index cat.Index,
eqCols []exec.NodeColumnOrdinal,
lookupCols exec.TableColumnOrdinalSet,
onCond tree.TypedExpr,
) (exec.Node, error) {
tn := &table.(*optVirtualTable).name
virtual, err := ef.planner.getVirtualTabler().getVirtualTableEntry(tn, ef.planner)
if err != nil {
return nil, err
}
if !canQueryVirtualTable(ef.planner.EvalContext(), virtual) {
return nil, newUnimplementedVirtualTableError(tn.Schema(), tn.Table())
}
if len(eqCols) > 1 {
return nil, errors.AssertionFailedf("vtable indexes with more than one column aren't supported yet")
}
// Check for explicit use of the dummy column.
if lookupCols.Contains(0) {
return nil, errors.Errorf("use of %s column not allowed.", table.Column(0).ColName())
}
idx := index.(*optVirtualIndex).idx
tableDesc := table.(*optVirtualTable).desc
// Build the result columns.
inputCols := planColumns(input.(planNode))
if onCond == tree.DBoolTrue {
onCond = nil
}
var tableScan scanNode
// Set up a scanNode that we won't actually use, just to get the needed
// column analysis.
colCfg := makeScanColumnsConfig(table, lookupCols)
if err := tableScan.initTable(ef.ctx, ef.planner, tableDesc, colCfg); err != nil {
return nil, err
}
tableScan.index = idx
vtableCols := colinfo.ResultColumnsFromColumns(tableDesc.GetID(), tableDesc.PublicColumns())
projectedVtableCols := planColumns(&tableScan)
var outputCols colinfo.ResultColumns
switch joinType {
case descpb.InnerJoin, descpb.LeftOuterJoin:
outputCols = make(colinfo.ResultColumns, 0, len(inputCols)+len(projectedVtableCols))
outputCols = append(outputCols, inputCols...)
outputCols = append(outputCols, projectedVtableCols...)
case descpb.LeftSemiJoin, descpb.LeftAntiJoin:
outputCols = make(colinfo.ResultColumns, 0, len(inputCols))
outputCols = append(outputCols, inputCols...)
default:
return nil, errors.AssertionFailedf("unexpected join type for virtual lookup join: %s", joinType.String())
}
pred := makePredicate(joinType, inputCols, projectedVtableCols)
pred.onCond = pred.iVarHelper.Rebind(onCond)
n := &vTableLookupJoinNode{
input: input.(planNode),
joinType: joinType,
virtualTableEntry: virtual,
dbName: tn.Catalog(),
table: tableDesc,
index: idx,
eqCol: int(eqCols[0]),
inputCols: inputCols,
vtableCols: vtableCols,
lookupCols: lookupCols,
columns: outputCols,
pred: pred,
}
return n, nil
}
func (ef *execFactory) ConstructInvertedJoin(
joinType descpb.JoinType,
invertedExpr tree.TypedExpr,
input exec.Node,
table cat.Table,
index cat.Index,
prefixEqCols []exec.NodeColumnOrdinal,
lookupCols exec.TableColumnOrdinalSet,
onCond tree.TypedExpr,
isFirstJoinInPairedJoiner bool,
reqOrdering exec.OutputOrdering,
locking opt.Locking,
) (exec.Node, error) {
tabDesc := table.(*optTable).desc
idx := index.(*optIndex).idx
colCfg := makeScanColumnsConfig(table, lookupCols)
tableScan := ef.planner.Scan()
if err := tableScan.initTable(ef.ctx, ef.planner, tabDesc, colCfg); err != nil {
return nil, err
}
tableScan.index = idx
tableScan.lockingStrength = descpb.ToScanLockingStrength(locking.Strength)
tableScan.lockingWaitPolicy = descpb.ToScanLockingWaitPolicy(locking.WaitPolicy)
if !ef.isExplain && !(ef.planner.isInternalPlanner || ef.planner.SessionData().Internal) {
idxUsageKey := roachpb.IndexUsageKey{
TableID: roachpb.TableID(tabDesc.GetID()),
IndexID: roachpb.IndexID(idx.GetID()),
}
ef.planner.extendedEvalCtx.indexUsageStats.RecordRead(idxUsageKey)
}
n := &invertedJoinNode{
input: input.(planNode),
table: tableScan,
joinType: joinType,
invertedExpr: invertedExpr,
isFirstJoinInPairedJoiner: isFirstJoinInPairedJoiner,
reqOrdering: ReqOrdering(reqOrdering),
}
if len(prefixEqCols) > 0 {
n.prefixEqCols = make([]int, len(prefixEqCols))
for i, c := range prefixEqCols {
n.prefixEqCols[i] = int(c)
}
}
if onCond != nil && onCond != tree.DBoolTrue {
n.onExpr = onCond
}
// Build the result columns.
inputCols := planColumns(input.(planNode))
var scanCols colinfo.ResultColumns
if joinType.ShouldIncludeRightColsInOutput() {
scanCols = planColumns(tableScan)
}
numCols := len(inputCols) + len(scanCols)
if isFirstJoinInPairedJoiner {
numCols++
}
n.columns = make(colinfo.ResultColumns, 0, numCols)
n.columns = append(n.columns, inputCols...)
n.columns = append(n.columns, scanCols...)
if isFirstJoinInPairedJoiner {
n.columns = append(n.columns, colinfo.ResultColumn{Name: "cont", Typ: types.Bool})
}
return n, nil
}
// Helper function to create a scanNode from just a table / index descriptor
// and requested cols.
func (ef *execFactory) constructScanForZigzag(
table cat.Table,
index cat.Index,
cols exec.TableColumnOrdinalSet,
eqCols []exec.TableColumnOrdinal,
locking opt.Locking,
) (_ *scanNode, eqColOrdinals []int, _ error) {
colCfg := makeScanColumnsConfig(table, cols)
var err error
eqColOrdinals, err = tableToScanOrdinals(cols, eqCols)
if err != nil {
return nil, nil, err
}
tableDesc := table.(*optTable).desc
idxDesc := index.(*optIndex).idx
scan := ef.planner.Scan()
if err := scan.initTable(ef.ctx, ef.planner, tableDesc, colCfg); err != nil {
return nil, nil, err
}
if !ef.isExplain && !(ef.planner.isInternalPlanner || ef.planner.SessionData().Internal) {
idxUsageKey := roachpb.IndexUsageKey{
TableID: roachpb.TableID(tableDesc.GetID()),
IndexID: roachpb.IndexID(idxDesc.GetID()),
}
ef.planner.extendedEvalCtx.indexUsageStats.RecordRead(idxUsageKey)
}
scan.index = idxDesc
scan.lockingStrength = descpb.ToScanLockingStrength(locking.Strength)
scan.lockingWaitPolicy = descpb.ToScanLockingWaitPolicy(locking.WaitPolicy)
return scan, eqColOrdinals, nil
}
// ConstructZigzagJoin is part of the exec.Factory interface.
func (ef *execFactory) ConstructZigzagJoin(
leftTable cat.Table,
leftIndex cat.Index,
leftCols exec.TableColumnOrdinalSet,
leftFixedVals []tree.TypedExpr,
leftEqCols []exec.TableColumnOrdinal,
leftLocking opt.Locking,
rightTable cat.Table,
rightIndex cat.Index,
rightCols exec.TableColumnOrdinalSet,
rightFixedVals []tree.TypedExpr,
rightEqCols []exec.TableColumnOrdinal,
rightLocking opt.Locking,
onCond tree.TypedExpr,
reqOrdering exec.OutputOrdering,
) (exec.Node, error) {
if len(leftEqCols) != len(rightEqCols) {
return nil, errors.AssertionFailedf("creating zigzag join with unequal number of equated cols")
}
n := &zigzagJoinNode{
sides: make([]zigzagJoinSide, 2),
reqOrdering: ReqOrdering(reqOrdering),
}
var err error
n.sides[0].scan, n.sides[0].eqCols, err = ef.constructScanForZigzag(leftTable, leftIndex, leftCols, leftEqCols, leftLocking)
if err != nil {
return nil, err
}
n.sides[1].scan, n.sides[1].eqCols, err = ef.constructScanForZigzag(rightTable, rightIndex, rightCols, rightEqCols, rightLocking)
if err != nil {
return nil, err
}
if onCond != nil && onCond != tree.DBoolTrue {
n.onCond = onCond
}
// The resultant columns are identical to those from individual index scans; so
// reuse the resultColumns generated in the scanNodes.
n.columns = make(
colinfo.ResultColumns,
0,
len(n.sides[0].scan.resultColumns)+len(n.sides[1].scan.resultColumns),
)
n.columns = append(n.columns, n.sides[0].scan.resultColumns...)
n.columns = append(n.columns, n.sides[1].scan.resultColumns...)