-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
relational.go
2048 lines (1779 loc) · 60.6 KB
/
relational.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 execbuilder
import (
"bytes"
"context"
"fmt"
"math"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/norm"
"github.com/cockroachdb/cockroach/pkg/sql/opt/ordering"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
type execPlan struct {
root exec.Node
// outputCols is a map from opt.ColumnID to exec.ColumnOrdinal. It maps
// columns in the output set of a relational expression to indices in the
// result columns of the exec.Node.
//
// The reason we need to keep track of this (instead of using just the
// relational properties) is that the relational properties don't force a
// single "schema": any ordering of the output columns is possible. We choose
// the schema that is most convenient: for scans, we use the table's column
// ordering. Consider:
// SELECT a, b FROM t WHERE a = b
// and the following two cases:
// 1. The table is defined as (k INT PRIMARY KEY, a INT, b INT). The scan will
// return (k, a, b).
// 2. The table is defined as (k INT PRIMARY KEY, b INT, a INT). The scan will
// return (k, b, a).
// In these two cases, the relational properties are effectively the same.
//
// An alternative to this would be to always use a "canonical" schema, for
// example the output columns in increasing index order. However, this would
// require a lot of otherwise unnecessary projections.
//
// Note: conceptually, this could be a ColList; however, the map is more
// convenient when converting VariableOps to IndexedVars.
outputCols opt.ColMap
}
// numOutputCols returns the number of columns emitted by the execPlan's Node.
// This will typically be equal to ep.outputCols.Len(), but might be different
// if the node outputs the same optimizer ColumnID multiple times.
// TODO(justin): we should keep track of this instead of computing it each time.
func (ep *execPlan) numOutputCols() int {
return numOutputColsInMap(ep.outputCols)
}
// numOutputColsInMap returns the number of slots required to fill in all of
// the columns referred to by this ColMap.
func numOutputColsInMap(m opt.ColMap) int {
max, ok := m.MaxValue()
if !ok {
return 0
}
return max + 1
}
// makeBuildScalarCtx returns a buildScalarCtx that can be used with expressions
// that refer the output columns of this plan.
func (ep *execPlan) makeBuildScalarCtx() buildScalarCtx {
return buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, ep.numOutputCols()),
ivarMap: ep.outputCols,
}
}
// getColumnOrdinal takes a column that is known to be produced by the execPlan
// and returns the ordinal index of that column in the result columns of the
// node.
func (ep *execPlan) getColumnOrdinal(col opt.ColumnID) exec.ColumnOrdinal {
ord, ok := ep.outputCols.Get(int(col))
if !ok {
panic(errors.AssertionFailedf("column %d not in input", log.Safe(col)))
}
return exec.ColumnOrdinal(ord)
}
func (ep *execPlan) getColumnOrdinalSet(cols opt.ColSet) exec.ColumnOrdinalSet {
var res exec.ColumnOrdinalSet
cols.ForEach(func(colID opt.ColumnID) {
res.Add(int(ep.getColumnOrdinal(colID)))
})
return res
}
// reqOrdering converts the provided ordering of a relational expression to an
// OutputOrdering (according to the outputCols map).
func (ep *execPlan) reqOrdering(expr memo.RelExpr) exec.OutputOrdering {
return exec.OutputOrdering(ep.sqlOrdering(expr.ProvidedPhysical().Ordering))
}
// sqlOrdering converts an Ordering to a ColumnOrdering (according to the
// outputCols map).
func (ep *execPlan) sqlOrdering(ordering opt.Ordering) sqlbase.ColumnOrdering {
if ordering.Empty() {
return nil
}
colOrder := make(sqlbase.ColumnOrdering, len(ordering))
for i := range ordering {
colOrder[i].ColIdx = int(ep.getColumnOrdinal(ordering[i].ID()))
if ordering[i].Descending() {
colOrder[i].Direction = encoding.Descending
} else {
colOrder[i].Direction = encoding.Ascending
}
}
return colOrder
}
func (b *Builder) buildRelational(e memo.RelExpr) (execPlan, error) {
var ep execPlan
var err error
isDDL := opt.IsDDLOp(e)
if isDDL {
// Mark the statement as containing DDL for use
// in the SQL executor.
b.IsDDL = true
// This will set the system DB trigger for transactions containing
// schema-modifying statements that have no effect, such as
// `BEGIN; INSERT INTO ...; CREATE TABLE IF NOT EXISTS ...; COMMIT;`
// where the table already exists. This will generate some false schema
// cache refreshes, but that's expected to be quite rare in practice.
if err := b.evalCtx.Txn.SetSystemConfigTrigger(); err != nil {
return execPlan{}, errors.WithSecondaryError(
unimplemented.NewWithIssuef(26508,
"schema change statement cannot follow a statement that has written in the same transaction"),
err)
}
}
// Raise error if mutation op is part of a read-only transaction.
if opt.IsMutationOp(e) && b.evalCtx.TxnReadOnly {
return execPlan{}, pgerror.Newf(pgcode.ReadOnlySQLTransaction,
"cannot execute %s in a read-only transaction", b.statementTag(e))
}
// Collect usage telemetry for relational node, if appropriate.
if !b.disableTelemetry {
if c := opt.OpTelemetryCounters[e.Op()]; c != nil {
telemetry.Inc(c)
}
}
var saveTableName string
if b.nameGen != nil {
// Don't save tables for operators that don't produce any columns (most
// importantly, for SET which is used to disable saving of tables).
if !e.Relational().OutputCols.Empty() {
// This function must be called in a pre-order traversal of the tree.
saveTableName = b.nameGen.GenerateName(e.Op())
}
}
switch t := e.(type) {
case *memo.ValuesExpr:
ep, err = b.buildValues(t)
case *memo.ScanExpr:
ep, err = b.buildScan(t)
case *memo.VirtualScanExpr:
ep, err = b.buildVirtualScan(t)
case *memo.SelectExpr:
ep, err = b.buildSelect(t)
case *memo.ProjectExpr:
ep, err = b.buildProject(t)
case *memo.GroupByExpr, *memo.ScalarGroupByExpr:
ep, err = b.buildGroupBy(e)
case *memo.DistinctOnExpr, *memo.UpsertDistinctOnExpr:
ep, err = b.buildDistinct(t)
case *memo.LimitExpr, *memo.OffsetExpr:
ep, err = b.buildLimitOffset(e)
case *memo.SortExpr:
ep, err = b.buildSort(t)
case *memo.IndexJoinExpr:
ep, err = b.buildIndexJoin(t)
case *memo.LookupJoinExpr:
ep, err = b.buildLookupJoin(t)
case *memo.ZigzagJoinExpr:
ep, err = b.buildZigzagJoin(t)
case *memo.OrdinalityExpr:
ep, err = b.buildOrdinality(t)
case *memo.MergeJoinExpr:
ep, err = b.buildMergeJoin(t)
case *memo.Max1RowExpr:
ep, err = b.buildMax1Row(t)
case *memo.ProjectSetExpr:
ep, err = b.buildProjectSet(t)
case *memo.WindowExpr:
ep, err = b.buildWindow(t)
case *memo.SequenceSelectExpr:
ep, err = b.buildSequenceSelect(t)
case *memo.InsertExpr:
ep, err = b.buildInsert(t)
case *memo.UpdateExpr:
ep, err = b.buildUpdate(t)
case *memo.UpsertExpr:
ep, err = b.buildUpsert(t)
case *memo.DeleteExpr:
ep, err = b.buildDelete(t)
case *memo.CreateTableExpr:
ep, err = b.buildCreateTable(t)
case *memo.CreateViewExpr:
ep, err = b.buildCreateView(t)
case *memo.WithExpr:
ep, err = b.buildWith(t)
case *memo.WithScanExpr:
ep, err = b.buildWithScan(t)
case *memo.RecursiveCTEExpr:
ep, err = b.buildRecursiveCTE(t)
case *memo.ExplainExpr:
ep, err = b.buildExplain(t)
case *memo.ShowTraceForSessionExpr:
ep, err = b.buildShowTrace(t)
case *memo.OpaqueRelExpr, *memo.OpaqueMutationExpr, *memo.OpaqueDDLExpr:
ep, err = b.buildOpaque(t.Private().(*memo.OpaqueRelPrivate))
case *memo.AlterTableSplitExpr:
ep, err = b.buildAlterTableSplit(t)
case *memo.AlterTableUnsplitExpr:
ep, err = b.buildAlterTableUnsplit(t)
case *memo.AlterTableUnsplitAllExpr:
ep, err = b.buildAlterTableUnsplitAll(t)
case *memo.AlterTableRelocateExpr:
ep, err = b.buildAlterTableRelocate(t)
case *memo.ControlJobsExpr:
ep, err = b.buildControlJobs(t)
case *memo.CancelQueriesExpr:
ep, err = b.buildCancelQueries(t)
case *memo.CancelSessionsExpr:
ep, err = b.buildCancelSessions(t)
case *memo.ExportExpr:
ep, err = b.buildExport(t)
default:
switch {
case opt.IsSetOp(e):
ep, err = b.buildSetOp(e)
case opt.IsJoinNonApplyOp(e):
ep, err = b.buildHashJoin(e)
case opt.IsJoinApplyOp(e):
ep, err = b.buildApplyJoin(e)
default:
err = errors.AssertionFailedf("no execbuild for %T", t)
}
}
if err != nil {
return execPlan{}, err
}
// In race builds, assert that the exec plan output columns match the opt
// plan output columns.
if util.RaceEnabled {
optCols := e.Relational().OutputCols
var execCols opt.ColSet
ep.outputCols.ForEach(func(key, val int) {
execCols.Add(opt.ColumnID(key))
})
if !execCols.Equals(optCols) {
return execPlan{}, errors.AssertionFailedf(
"exec columns do not match opt columns: expected %v, got %v", optCols, execCols)
}
}
if saveTableName != "" {
ep, err = b.applySaveTable(ep, e, saveTableName)
if err != nil {
return execPlan{}, err
}
}
// Wrap the expression in a render expression if presentation requires it.
if p := e.RequiredPhysical(); !p.Presentation.Any() {
ep, err = b.applyPresentation(ep, p)
}
return ep, err
}
func (b *Builder) buildValues(values *memo.ValuesExpr) (execPlan, error) {
rows, err := b.buildValuesRows(values)
if err != nil {
return execPlan{}, err
}
return b.constructValues(rows, values.Cols)
}
func (b *Builder) buildValuesRows(values *memo.ValuesExpr) ([][]tree.TypedExpr, error) {
numCols := len(values.Cols)
rows := make([][]tree.TypedExpr, len(values.Rows))
rowBuf := make([]tree.TypedExpr, len(rows)*numCols)
scalarCtx := buildScalarCtx{}
for i := range rows {
tup := values.Rows[i].(*memo.TupleExpr)
if len(tup.Elems) != numCols {
return nil, fmt.Errorf("inconsistent row length %d vs %d", len(tup.Elems), numCols)
}
// Chop off prefix of rowBuf and limit its capacity.
rows[i] = rowBuf[:numCols:numCols]
rowBuf = rowBuf[numCols:]
var err error
for j := 0; j < numCols; j++ {
rows[i][j], err = b.buildScalar(&scalarCtx, tup.Elems[j])
if err != nil {
return nil, err
}
}
}
return rows, nil
}
func (b *Builder) constructValues(rows [][]tree.TypedExpr, cols opt.ColList) (execPlan, error) {
md := b.mem.Metadata()
resultCols := make(sqlbase.ResultColumns, len(cols))
for i, col := range cols {
colMeta := md.ColumnMeta(col)
resultCols[i].Name = colMeta.Alias
resultCols[i].Typ = colMeta.Type
}
node, err := b.factory.ConstructValues(rows, resultCols)
if err != nil {
return execPlan{}, err
}
ep := execPlan{root: node}
for i, col := range cols {
ep.outputCols.Set(int(col), i)
}
return ep, nil
}
// getColumns returns the set of column ordinals in the table for the set of
// column IDs, along with a mapping from the column IDs to output ordinals
// (starting with outputOrdinalStart).
func (b *Builder) getColumns(
cols opt.ColSet, tableID opt.TableID,
) (exec.ColumnOrdinalSet, opt.ColMap) {
needed := exec.ColumnOrdinalSet{}
output := opt.ColMap{}
columnCount := b.mem.Metadata().Table(tableID).DeletableColumnCount()
n := 0
for i := 0; i < columnCount; i++ {
colID := tableID.ColumnID(i)
if cols.Contains(colID) {
needed.Add(i)
output.Set(int(colID), n)
n++
}
}
return needed, output
}
// indexConstraintMaxResults returns the maximum number of results for a scan;
// the scan is guaranteed never to return more results than this. Iff this hint
// is invalid, 0 is returned.
func (b *Builder) indexConstraintMaxResults(scan *memo.ScanExpr) uint64 {
c := scan.Constraint
if c == nil || c.IsContradiction() || c.IsUnconstrained() {
return 0
}
numCols := c.Columns.Count()
var indexCols opt.ColSet
for i := 0; i < numCols; i++ {
indexCols.Add(c.Columns.Get(i).ID())
}
rel := scan.Relational()
if !rel.FuncDeps.ColsAreLaxKey(indexCols) {
return 0
}
return c.CalculateMaxResults(b.evalCtx, indexCols, rel.NotNullCols)
}
func (b *Builder) buildScan(scan *memo.ScanExpr) (execPlan, error) {
md := b.mem.Metadata()
tab := md.Table(scan.Table)
// Check if we tried to force a specific index but there was no Scan with that
// index in the memo.
if scan.Flags.ForceIndex && scan.Flags.Index != scan.Index {
idx := tab.Index(scan.Flags.Index)
var err error
if idx.IsInverted() {
err = fmt.Errorf("index \"%s\" is inverted and cannot be used for this query", idx.Name())
} else {
// This should never happen.
err = fmt.Errorf("index \"%s\" cannot be used for this query", idx.Name())
}
return execPlan{}, err
}
needed, output := b.getColumns(scan.Cols, scan.Table)
res := execPlan{outputCols: output}
// Get the estimated row count from the statistics.
// Note: if this memo was originally created as part of a PREPARE
// statement or was stored in the query cache, the column stats would have
// been removed by DetachMemo. Update that function if the column stats are
// needed here in the future.
rowCount := scan.Relational().Stats.RowCount
if !scan.Relational().Stats.Available {
// When there are no statistics available, we construct a scan node with
// the estimated row count of zero rows.
rowCount = 0
}
if scan.PartitionConstrainedScan {
sqltelemetry.IncrementPartitioningCounter(sqltelemetry.PartitionConstrainedScan)
}
softLimit := int64(math.Ceil(scan.RequiredPhysical().LimitHint))
hardLimit := scan.HardLimit.RowCount()
// At most one of hardLimit and softLimit may be defined at the same time.
//
// TODO(celine): Determine the more optimal course of action if there are
// competing hard and soft limits. It is currently unclear what course to
// take in the case of, for example, a small soft limit and a large hard
// limit, but always taking the soft limit is almost certainly suboptimal.
if softLimit != 0 {
hardLimit = 0
}
locking := scan.Locking
if b.forceForUpdateLocking {
locking = forUpdateLocking
}
root, err := b.factory.ConstructScan(
tab,
tab.Index(scan.Index),
needed,
scan.Constraint,
hardLimit,
softLimit,
// HardLimit.Reverse() is taken into account by ScanIsReverse.
ordering.ScanIsReverse(scan, &scan.RequiredPhysical().Ordering),
b.indexConstraintMaxResults(scan),
res.reqOrdering(scan),
rowCount,
locking,
)
if err != nil {
return execPlan{}, err
}
res.root = root
return res, nil
}
func (b *Builder) buildVirtualScan(scan *memo.VirtualScanExpr) (execPlan, error) {
md := b.mem.Metadata()
tab := md.Table(scan.Table)
_, output := b.getColumns(scan.Cols, scan.Table)
res := execPlan{outputCols: output}
root, err := b.factory.ConstructVirtualScan(tab)
if err != nil {
return execPlan{}, err
}
res.root = root
return res, nil
}
func (b *Builder) buildSelect(sel *memo.SelectExpr) (execPlan, error) {
input, err := b.buildRelational(sel.Input)
if err != nil {
return execPlan{}, err
}
ctx := input.makeBuildScalarCtx()
filter, err := b.buildScalar(&ctx, &sel.Filters)
if err != nil {
return execPlan{}, err
}
// A filtering node does not modify the schema.
res := execPlan{outputCols: input.outputCols}
reqOrder := res.reqOrdering(sel)
res.root, err = b.factory.ConstructFilter(input.root, filter, reqOrder)
if err != nil {
return execPlan{}, err
}
return res, nil
}
// applySimpleProject adds a simple projection on top of an existing plan.
func (b *Builder) applySimpleProject(
input execPlan, cols opt.ColSet, providedOrd opt.Ordering,
) (execPlan, error) {
// We have only pass-through columns.
colList := make([]exec.ColumnOrdinal, 0, cols.Len())
var res execPlan
cols.ForEach(func(i opt.ColumnID) {
res.outputCols.Set(int(i), len(colList))
colList = append(colList, input.getColumnOrdinal(i))
})
var err error
res.root, err = b.factory.ConstructSimpleProject(
input.root, colList, nil /* colNames */, exec.OutputOrdering(res.sqlOrdering(providedOrd)),
)
if err != nil {
return execPlan{}, err
}
return res, nil
}
func (b *Builder) buildProject(prj *memo.ProjectExpr) (execPlan, error) {
md := b.mem.Metadata()
input, err := b.buildRelational(prj.Input)
if err != nil {
return execPlan{}, err
}
projections := prj.Projections
if len(projections) == 0 {
// We have only pass-through columns.
return b.applySimpleProject(input, prj.Passthrough, prj.ProvidedPhysical().Ordering)
}
var res execPlan
exprs := make(tree.TypedExprs, 0, len(projections)+prj.Passthrough.Len())
colNames := make([]string, 0, len(exprs))
ctx := input.makeBuildScalarCtx()
for i := range projections {
item := &projections[i]
expr, err := b.buildScalar(&ctx, item.Element)
if err != nil {
return execPlan{}, err
}
res.outputCols.Set(int(item.Col), i)
exprs = append(exprs, expr)
colNames = append(colNames, md.ColumnMeta(item.Col).Alias)
}
prj.Passthrough.ForEach(func(colID opt.ColumnID) {
res.outputCols.Set(int(colID), len(exprs))
exprs = append(exprs, b.indexedVar(&ctx, md, colID))
colNames = append(colNames, md.ColumnMeta(colID).Alias)
})
reqOrdering := res.reqOrdering(prj)
res.root, err = b.factory.ConstructRender(input.root, exprs, colNames, reqOrdering)
if err != nil {
return execPlan{}, err
}
return res, nil
}
// ReplaceVars replaces the VariableExprs within a RelExpr with constant Datums
// provided by the vars map, which maps opt column id for each VariableExpr to
// replace to the Datum that should replace it. The memo within the input
// norm.Factory will be replaced with the result.
// requiredPhysical is the set of physical properties that are required of the
// root of the new expression.
func ReplaceVars(
f *norm.Factory,
applyInput memo.RelExpr,
requiredPhysical *physical.Required,
vars map[opt.ColumnID]tree.Datum,
) {
var replaceFn norm.ReplaceFunc
replaceFn = func(e opt.Expr) opt.Expr {
switch t := e.(type) {
case *memo.VariableExpr:
if d, ok := vars[t.Col]; ok {
return f.ConstructConstVal(d, t.Typ)
}
}
return f.CopyAndReplaceDefault(e, replaceFn)
}
f.CopyAndReplace(applyInput, requiredPhysical, replaceFn)
}
func (b *Builder) buildApplyJoin(join memo.RelExpr) (execPlan, error) {
switch join.Op() {
case opt.InnerJoinApplyOp, opt.LeftJoinApplyOp, opt.SemiJoinApplyOp, opt.AntiJoinApplyOp:
default:
return execPlan{}, fmt.Errorf("couldn't execute correlated subquery with op %s", join.Op())
}
joinType := joinOpToJoinType(join.Op())
leftExpr := join.Child(0).(memo.RelExpr)
rightExpr := join.Child(1).(memo.RelExpr)
filters := join.Child(2).(*memo.FiltersExpr)
// Create a fake version of the right-side plan that contains NULL for all
// outer columns, so that we can figure out the output columns and various
// other attributes.
var f norm.Factory
f.Init(b.evalCtx, b.catalog)
fakeBindings := make(map[opt.ColumnID]tree.Datum)
rightExpr.Relational().OuterCols.ForEach(func(k opt.ColumnID) {
fakeBindings[k] = tree.DNull
})
ReplaceVars(&f, rightExpr, rightExpr.RequiredPhysical(), fakeBindings)
// We increment nullifyMissingVarExprs here to instruct the scalar builder to
// replace the outer column VariableExprs with null for the current scope.
b.nullifyMissingVarExprs++
fakeRight, err := b.buildRelational(rightExpr)
b.nullifyMissingVarExprs--
if err != nil {
return execPlan{}, err
}
// Make a copy of the required props.
requiredProps := *rightExpr.RequiredPhysical()
requiredProps.Presentation = make(physical.Presentation, fakeRight.outputCols.Len())
fakeRight.outputCols.ForEach(func(k, v int) {
requiredProps.Presentation[opt.ColumnID(v)] = opt.AliasedColumn{
ID: opt.ColumnID(k),
Alias: join.Memo().Metadata().ColumnMeta(opt.ColumnID(k)).Alias,
}
})
left, err := b.buildRelational(leftExpr)
if err != nil {
return execPlan{}, err
}
// leftBoundCols is the set of columns that this apply join binds.
leftBoundCols := leftExpr.Relational().OutputCols.Intersection(rightExpr.Relational().OuterCols)
// leftBoundColMap is a map from opt.ColumnID to opt.ColumnOrdinal that maps
// a column bound by the left side of this apply join to the column ordinal
// in the left side that contains the binding.
var leftBoundColMap opt.ColMap
for k, ok := leftBoundCols.Next(0); ok; k, ok = leftBoundCols.Next(k + 1) {
v, ok := left.outputCols.Get(int(k))
if !ok {
return execPlan{}, fmt.Errorf("couldn't find binding column %d in output columns", k)
}
leftBoundColMap.Set(int(k), v)
}
allCols := joinOutputMap(left.outputCols, fakeRight.outputCols)
ctx := buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, numOutputColsInMap(allCols)),
ivarMap: allCols,
}
var onExpr tree.TypedExpr
if len(*filters) != 0 {
onExpr, err = b.buildScalar(&ctx, filters)
if err != nil {
return execPlan{}, err
}
}
var outputCols opt.ColMap
if joinType == sqlbase.LeftSemiJoin || joinType == sqlbase.LeftAntiJoin {
// For semi and anti join, only the left columns are output.
outputCols = left.outputCols
} else {
outputCols = allCols
}
ep := execPlan{outputCols: outputCols}
ep.root, err = b.factory.ConstructApplyJoin(
joinType,
left.root,
leftBoundColMap,
b.mem,
&requiredProps,
fakeRight.root,
rightExpr,
onExpr,
)
if err != nil {
return execPlan{}, err
}
return ep, nil
}
func (b *Builder) buildHashJoin(join memo.RelExpr) (execPlan, error) {
if f := join.Private().(*memo.JoinPrivate).Flags; !f.Has(memo.AllowHashJoinStoreRight) {
// We need to do a bit of reverse engineering here to determine what the
// hint was.
hint := tree.AstLookup
if f.Has(memo.AllowMergeJoin) {
hint = tree.AstMerge
}
return execPlan{}, errors.Errorf(
"could not produce a query plan conforming to the %s JOIN hint", hint,
)
}
joinType := joinOpToJoinType(join.Op())
leftExpr := join.Child(0).(memo.RelExpr)
rightExpr := join.Child(1).(memo.RelExpr)
filters := join.Child(2).(*memo.FiltersExpr)
leftEq, rightEq := memo.ExtractJoinEqualityColumns(
leftExpr.Relational().OutputCols,
rightExpr.Relational().OutputCols,
*filters,
)
left, right, onExpr, outputCols, err := b.initJoinBuild(
leftExpr,
rightExpr,
memo.ExtractRemainingJoinFilters(*filters, leftEq, rightEq),
joinType,
)
if err != nil {
return execPlan{}, err
}
ep := execPlan{outputCols: outputCols}
// Convert leftEq/rightEq to ordinals.
eqColsBuf := make([]exec.ColumnOrdinal, 2*len(leftEq))
leftEqOrdinals := eqColsBuf[:len(leftEq):len(leftEq)]
rightEqOrdinals := eqColsBuf[len(leftEq):]
for i := range leftEq {
leftEqOrdinals[i] = left.getColumnOrdinal(leftEq[i])
rightEqOrdinals[i] = right.getColumnOrdinal(rightEq[i])
}
leftEqColsAreKey := leftExpr.Relational().FuncDeps.ColsAreStrictKey(leftEq.ToSet())
rightEqColsAreKey := rightExpr.Relational().FuncDeps.ColsAreStrictKey(rightEq.ToSet())
ep.root, err = b.factory.ConstructHashJoin(
joinType,
left.root, right.root,
leftEqOrdinals, rightEqOrdinals,
leftEqColsAreKey, rightEqColsAreKey,
onExpr,
)
if err != nil {
return execPlan{}, err
}
return ep, nil
}
func (b *Builder) buildMergeJoin(join *memo.MergeJoinExpr) (execPlan, error) {
joinType := joinOpToJoinType(join.JoinType)
left, right, onExpr, outputCols, err := b.initJoinBuild(
join.Left, join.Right, join.On, joinType,
)
if err != nil {
return execPlan{}, err
}
leftOrd := left.sqlOrdering(join.LeftEq)
rightOrd := right.sqlOrdering(join.RightEq)
ep := execPlan{outputCols: outputCols}
reqOrd := ep.reqOrdering(join)
leftEqColsAreKey := join.Left.Relational().FuncDeps.ColsAreStrictKey(join.LeftEq.ColSet())
rightEqColsAreKey := join.Right.Relational().FuncDeps.ColsAreStrictKey(join.RightEq.ColSet())
ep.root, err = b.factory.ConstructMergeJoin(
joinType,
left.root, right.root,
onExpr,
leftOrd, rightOrd, reqOrd,
leftEqColsAreKey, rightEqColsAreKey,
)
if err != nil {
return execPlan{}, err
}
return ep, nil
}
// initJoinBuild builds the inputs to the join as well as the ON expression.
func (b *Builder) initJoinBuild(
leftChild memo.RelExpr,
rightChild memo.RelExpr,
filters memo.FiltersExpr,
joinType sqlbase.JoinType,
) (leftPlan, rightPlan execPlan, onExpr tree.TypedExpr, outputCols opt.ColMap, _ error) {
leftPlan, err := b.buildRelational(leftChild)
if err != nil {
return execPlan{}, execPlan{}, nil, opt.ColMap{}, err
}
rightPlan, err = b.buildRelational(rightChild)
if err != nil {
return execPlan{}, execPlan{}, nil, opt.ColMap{}, err
}
allCols := joinOutputMap(leftPlan.outputCols, rightPlan.outputCols)
ctx := buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, numOutputColsInMap(allCols)),
ivarMap: allCols,
}
if len(filters) != 0 {
onExpr, err = b.buildScalar(&ctx, &filters)
if err != nil {
return execPlan{}, execPlan{}, nil, opt.ColMap{}, err
}
}
if joinType == sqlbase.LeftSemiJoin || joinType == sqlbase.LeftAntiJoin {
// For semi and anti join, only the left columns are output.
return leftPlan, rightPlan, onExpr, leftPlan.outputCols, nil
}
return leftPlan, rightPlan, onExpr, allCols, nil
}
// joinOutputMap determines the outputCols map for a (non-semi/anti) join, given
// the outputCols maps for its inputs.
func joinOutputMap(left, right opt.ColMap) opt.ColMap {
numLeftCols := numOutputColsInMap(left)
res := left.Copy()
right.ForEach(func(colIdx, rightIdx int) {
res.Set(colIdx, rightIdx+numLeftCols)
})
return res
}
func joinOpToJoinType(op opt.Operator) sqlbase.JoinType {
switch op {
case opt.InnerJoinOp, opt.InnerJoinApplyOp:
return sqlbase.InnerJoin
case opt.LeftJoinOp, opt.LeftJoinApplyOp:
return sqlbase.LeftOuterJoin
case opt.RightJoinOp:
return sqlbase.RightOuterJoin
case opt.FullJoinOp:
return sqlbase.FullOuterJoin
case opt.SemiJoinOp, opt.SemiJoinApplyOp:
return sqlbase.LeftSemiJoin
case opt.AntiJoinOp, opt.AntiJoinApplyOp:
return sqlbase.LeftAntiJoin
default:
panic(errors.AssertionFailedf("not a join op %s", log.Safe(op)))
}
}
func (b *Builder) buildGroupBy(groupBy memo.RelExpr) (execPlan, error) {
input, err := b.buildGroupByInput(groupBy)
if err != nil {
return execPlan{}, err
}
var ep execPlan
groupingCols := groupBy.Private().(*memo.GroupingPrivate).GroupingCols
groupingColIdx := make([]exec.ColumnOrdinal, 0, groupingCols.Len())
for i, ok := groupingCols.Next(0); ok; i, ok = groupingCols.Next(i + 1) {
ep.outputCols.Set(int(i), len(groupingColIdx))
groupingColIdx = append(groupingColIdx, input.getColumnOrdinal(i))
}
aggregations := *groupBy.Child(1).(*memo.AggregationsExpr)
aggInfos := make([]exec.AggInfo, len(aggregations))
for i := range aggregations {
item := &aggregations[i]
agg := item.Agg
var filterOrd exec.ColumnOrdinal = -1
if aggFilter, ok := agg.(*memo.AggFilterExpr); ok {
filter, ok := aggFilter.Filter.(*memo.VariableExpr)
if !ok {
return execPlan{}, errors.AssertionFailedf("only VariableOp args supported")
}
filterOrd = input.getColumnOrdinal(filter.Col)
agg = aggFilter.Input
}
distinct := false
if aggDistinct, ok := agg.(*memo.AggDistinctExpr); ok {
distinct = true
agg = aggDistinct.Input
}
name, overload := memo.FindAggregateOverload(agg)
// Accumulate variable arguments in argCols and constant arguments in
// constArgs. Constant arguments must follow variable arguments.
var argCols []exec.ColumnOrdinal
var constArgs tree.Datums
for j, n := 0, agg.ChildCount(); j < n; j++ {
child := agg.Child(j)
if variable, ok := child.(*memo.VariableExpr); ok {
if len(constArgs) != 0 {
return execPlan{}, errors.Errorf("constant args must come after variable args")
}
argCols = append(argCols, input.getColumnOrdinal(variable.Col))
} else {
if len(argCols) == 0 {
return execPlan{}, errors.Errorf("a constant arg requires at least one variable arg")
}
constArgs = append(constArgs, memo.ExtractConstDatum(child))
}
}
aggInfos[i] = exec.AggInfo{
FuncName: name,
Builtin: overload,
Distinct: distinct,
ResultType: item.Agg.DataType(),
ArgCols: argCols,
ConstArgs: constArgs,
Filter: filterOrd,
}
ep.outputCols.Set(int(item.Col), len(groupingColIdx)+i)
}
if groupBy.Op() == opt.ScalarGroupByOp {
ep.root, err = b.factory.ConstructScalarGroupBy(input.root, aggInfos)
} else {
groupBy := groupBy.(*memo.GroupByExpr)
groupingColOrder := input.sqlOrdering(ordering.StreamingGroupingColOrdering(
&groupBy.GroupingPrivate, &groupBy.RequiredPhysical().Ordering,
))
reqOrdering := ep.reqOrdering(groupBy)
ep.root, err = b.factory.ConstructGroupBy(
input.root, groupingColIdx, groupingColOrder, aggInfos, reqOrdering,
)
}
if err != nil {
return execPlan{}, err
}
return ep, nil
}
func (b *Builder) buildDistinct(distinct memo.RelExpr) (execPlan, error) {
private := distinct.Private().(*memo.GroupingPrivate)
if private.GroupingCols.Empty() {
// A DistinctOn with no grouping columns should have been converted to a
// LIMIT 1 or Max1Row by normalization rules.
return execPlan{}, fmt.Errorf("cannot execute distinct on no columns")