-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
relational.go
2271 lines (1978 loc) · 68.1 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/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"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/opt/xform"
"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/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"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.NodeColumnOrdinal. 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,
}
}
// getNodeColumnOrdinal 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) getNodeColumnOrdinal(col opt.ColumnID) exec.NodeColumnOrdinal {
ord, ok := ep.outputCols.Get(int(col))
if !ok {
panic(errors.AssertionFailedf("column %d not in input", log.Safe(col)))
}
return exec.NodeColumnOrdinal(ord)
}
func (ep *execPlan) getNodeColumnOrdinalSet(cols opt.ColSet) exec.NodeColumnOrdinalSet {
var res exec.NodeColumnOrdinalSet
cols.ForEach(func(colID opt.ColumnID) {
res.Add(int(ep.getNodeColumnOrdinal(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) colinfo.ColumnOrdering {
if ordering.Empty() {
return nil
}
colOrder := make(colinfo.ColumnOrdering, len(ordering))
for i := range ordering {
colOrder[i].ColIdx = int(ep.getNodeColumnOrdinal(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
if opt.IsDDLOp(e) {
// 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(b.evalCtx.Codec.ForSystemTenant()); 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.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.EnsureDistinctOnExpr, *memo.UpsertDistinctOnExpr,
*memo.EnsureUpsertDistinctOnExpr:
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.InvertedJoinExpr:
ep, err = b.buildInvertedJoin(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.InvertedFilterExpr:
ep, err = b.buildInvertedFilter(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.ControlSchedulesExpr:
ep, err = b.buildControlSchedules(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 we are building against an ExplainFactory, annotate the nodes with more
// information.
if ef, ok := b.factory.(exec.ExplainFactory); ok {
stats := &e.Relational().Stats
ef.AnnotateNode(ep.root, exec.EstimatedStatsID, &exec.EstimatedStats{
TableStatsAvailable: stats.Available,
RowCount: stats.RowCount,
Cost: float64(e.Cost()),
})
}
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.Presentation)
}
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(colinfo.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 0).
func (b *Builder) getColumns(
cols opt.ColSet, tableID opt.TableID,
) (exec.TableColumnOrdinalSet, opt.ColMap) {
var needed exec.TableColumnOrdinalSet
var output opt.ColMap
columnCount := b.mem.Metadata().Table(tableID).ColumnCount()
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;
// if successful (ok=true), the scan is guaranteed never to return more results
// than maxRows.
func (b *Builder) indexConstraintMaxResults(scan *memo.ScanExpr) (maxRows uint64, ok bool) {
c := scan.Constraint
if c == nil || c.IsContradiction() || c.IsUnconstrained() {
return 0, false
}
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, false
}
return c.CalculateMaxResults(b.evalCtx, indexCols, rel.NotNullCols)
}
func (b *Builder) scanParams(
tab cat.Table, scan *memo.ScanExpr,
) (exec.ScanParams, opt.ColMap, error) {
// 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)
isInverted := idx.IsInverted()
_, isPartial := idx.Predicate()
var err error
switch {
case isInverted && isPartial:
err = fmt.Errorf(
"index \"%s\" is a partial inverted index and cannot be used for this query",
idx.Name(),
)
case isInverted:
err = fmt.Errorf(
"index \"%s\" is inverted and cannot be used for this query",
idx.Name(),
)
case isPartial:
err = fmt.Errorf(
"index \"%s\" is a partial index that does not contain all the rows needed to execute this query",
idx.Name(),
)
default:
// This should never happen.
err = fmt.Errorf("index \"%s\" cannot be used for this query", idx.Name())
}
return exec.ScanParams{}, opt.ColMap{}, err
}
locking := scan.Locking
if b.forceForUpdateLocking {
locking = forUpdateLocking
}
// Raise error if row-level locking is part of a read-only transaction.
if locking != nil && locking.Strength > tree.ForNone && b.evalCtx.TxnReadOnly {
return exec.ScanParams{}, opt.ColMap{}, pgerror.Newf(pgcode.ReadOnlySQLTransaction,
"cannot execute %s in a read-only transaction", locking.Strength.String())
}
needed, outputMap := b.getColumns(scan.Cols, scan.Table)
// 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()
parallelize := false
if hardLimit == 0 && softLimit == 0 {
maxResults, ok := b.indexConstraintMaxResults(scan)
if ok && maxResults < ParallelScanResultThreshold {
// Don't set the flag when we have a single span which returns a single
// row: it does nothing in this case except litter EXPLAINs.
// There are still cases where the flag doesn't do anything when the spans
// cover a single range, but there is nothing we can do about that.
if !(maxResults == 1 && scan.Constraint.Spans.Count() == 1) {
parallelize = true
}
}
}
return exec.ScanParams{
NeededCols: needed,
IndexConstraint: scan.Constraint,
InvertedConstraint: scan.InvertedConstraint,
HardLimit: hardLimit,
SoftLimit: softLimit,
// HardLimit.Reverse() is taken into account by ScanIsReverse.
Reverse: ordering.ScanIsReverse(scan, &scan.RequiredPhysical().Ordering),
Parallelize: parallelize,
Locking: locking,
EstimatedRowCount: rowCount,
}, outputMap, nil
}
func (b *Builder) buildScan(scan *memo.ScanExpr) (execPlan, error) {
md := b.mem.Metadata()
tab := md.Table(scan.Table)
if !b.disableTelemetry && scan.UsesPartialIndex(md) {
telemetry.Inc(sqltelemetry.PartialIndexScanUseCounter)
}
params, outputCols, err := b.scanParams(tab, scan)
if err != nil {
return execPlan{}, err
}
res := execPlan{outputCols: outputCols}
root, err := b.factory.ConstructScan(
tab,
tab.Index(scan.Index),
params,
res.reqOrdering(scan),
)
if err != nil {
return execPlan{}, err
}
// Save if we planned a full table/index scan on the builder so that the
// planner can be made aware later. We only do this for non-virtual tables.
if !tab.IsVirtualTable() && scan.Constraint == nil && scan.InvertedConstraint == nil {
if scan.Index == cat.PrimaryIndex {
b.ContainsFullTableScan = true
} else {
b.ContainsFullIndexScan = true
}
}
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
}
filter, err := b.buildScalarWithMap(input.outputCols, &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
}
func (b *Builder) buildInvertedFilter(invFilter *memo.InvertedFilterExpr) (execPlan, error) {
input, err := b.buildRelational(invFilter.Input)
if err != nil {
return execPlan{}, err
}
// A filtering node does not modify the schema.
res := execPlan{outputCols: input.outputCols}
invertedCol := input.getNodeColumnOrdinal(invFilter.InvertedColumn)
var typedPreFilterExpr tree.TypedExpr
var typ *types.T
if invFilter.PreFiltererState != nil && invFilter.PreFiltererState.Expr != nil {
// The expression has a single variable, corresponding to the indexed
// column. We assign it an ordinal of 0.
var colMap opt.ColMap
colMap.Set(int(invFilter.PreFiltererState.Col), 0)
ctx := buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, colMap.Len()),
ivarMap: colMap,
}
typedPreFilterExpr, err = b.buildScalar(&ctx, invFilter.PreFiltererState.Expr)
if err != nil {
return execPlan{}, err
}
typ = invFilter.PreFiltererState.Typ
}
res.root, err = b.factory.ConstructInvertedFilter(
input.root, invFilter.InvertedExpression, typedPreFilterExpr, typ, invertedCol)
if err != nil {
return execPlan{}, err
}
// Apply a post-projection to remove the inverted column.
//
// TODO(rytaft): the invertedFilter used to do this post-projection, but we
// had difficulty integrating that behavior. Investigate and restore that
// original behavior.
return b.applySimpleProject(
res, invFilter.Relational().OutputCols, invFilter.ProvidedPhysical().Ordering,
)
}
// 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.NodeColumnOrdinal, 0, cols.Len())
var res execPlan
cols.ForEach(func(i opt.ColumnID) {
res.outputCols.Set(int(i), len(colList))
colList = append(colList, input.getNodeColumnOrdinal(i))
})
var err error
res.root, err = b.factory.ConstructSimpleProject(
input.root, colList, 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())
cols := make(colinfo.ResultColumns, 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)
cols = append(cols, colinfo.ResultColumn{
Name: md.ColumnMeta(item.Col).Alias,
Typ: item.Typ,
})
}
prj.Passthrough.ForEach(func(colID opt.ColumnID) {
res.outputCols.Set(int(colID), len(exprs))
indexedVar := b.indexedVar(&ctx, md, colID)
exprs = append(exprs, indexedVar)
meta := md.ColumnMeta(colID)
cols = append(cols, colinfo.ResultColumn{
Name: meta.Alias,
Typ: meta.Type,
})
})
reqOrdering := res.reqOrdering(prj)
res.root, err = b.factory.ConstructRender(input.root, cols, exprs, reqOrdering)
if err != nil {
return execPlan{}, err
}
return res, nil
}
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)
leftProps := leftExpr.Relational()
rightExpr := join.Child(1).(memo.RelExpr)
rightProps := rightExpr.Relational()
filters := join.Child(2).(*memo.FiltersExpr)
if len(memo.WithUses(rightExpr)) != 0 {
return execPlan{}, fmt.Errorf("references to WITH expressions from correlated subqueries are unsupported")
}
leftPlan, err := b.buildRelational(leftExpr)
if err != nil {
return execPlan{}, err
}
// Make a copy of the required props for the right side.
rightRequiredProps := *rightExpr.RequiredPhysical()
// The right-hand side will produce the output columns in order.
rightRequiredProps.Presentation = b.makePresentation(rightProps.OutputCols)
// leftBoundCols is the set of columns that this apply join binds.
leftBoundCols := leftProps.OutputCols.Intersection(rightProps.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 col, ok := leftBoundCols.Next(0); ok; col, ok = leftBoundCols.Next(col + 1) {
v, ok := leftPlan.outputCols.Get(int(col))
if !ok {
return execPlan{}, fmt.Errorf("couldn't find binding column %d in left output columns", col)
}
leftBoundColMap.Set(int(col), v)
}
// Now, the cool part! We set up an ApplyJoinPlanRightSideFn which plans the
// right side given a particular left side row. We do this planning in a
// separate memo, but we use the same exec.Factory.
//
// Note: we put o outside of the function so we allocate it only once.
var o xform.Optimizer
planRightSideFn := func(ef exec.Factory, leftRow tree.Datums) (exec.Plan, error) {
o.Init(b.evalCtx, b.catalog)
f := o.Factory()
// Copy the right expression into a new memo, replacing each bound column
// with the corresponding value from the left row.
var replaceFn norm.ReplaceFunc
replaceFn = func(e opt.Expr) opt.Expr {
switch t := e.(type) {
case *memo.VariableExpr:
if leftOrd, ok := leftBoundColMap.Get(int(t.Col)); ok {
return f.ConstructConstVal(leftRow[leftOrd], t.Typ)
}
}
return f.CopyAndReplaceDefault(e, replaceFn)
}
f.CopyAndReplace(rightExpr, &rightRequiredProps, replaceFn)
newRightSide, err := o.Optimize()
if err != nil {
return nil, err
}
eb := New(ef, f.Memo(), b.catalog, newRightSide, b.evalCtx, false /* allowAutoCommit */)
eb.disableTelemetry = true
plan, err := eb.Build()
if err != nil {
if errors.IsAssertionFailure(err) {
// Enhance the error with the EXPLAIN (OPT, VERBOSE) of the inner
// expression.
fmtFlags := memo.ExprFmtHideQualifications | memo.ExprFmtHideScalars | memo.ExprFmtHideTypes
explainOpt := o.FormatExpr(newRightSide, fmtFlags)
err = errors.WithDetailf(err, "newRightSide:\n%s", explainOpt)
}
return nil, err
}
return plan, nil
}
// The right plan will always produce the columns in the presentation, in
// the same order.
var rightOutputCols opt.ColMap
for i := range rightRequiredProps.Presentation {
rightOutputCols.Set(int(rightRequiredProps.Presentation[i].ID), i)
}
allCols := joinOutputMap(leftPlan.outputCols, rightOutputCols)
var onExpr tree.TypedExpr
if len(*filters) != 0 {
scalarCtx := buildScalarCtx{
ivh: tree.MakeIndexedVarHelper(nil /* container */, numOutputColsInMap(allCols)),
ivarMap: allCols,
}
onExpr, err = b.buildScalar(&scalarCtx, filters)
if err != nil {
return execPlan{}, err
}
}
var outputCols opt.ColMap
if joinType == descpb.LeftSemiJoin || joinType == descpb.LeftAntiJoin {
// For semi and anti join, only the left columns are output.
outputCols = leftPlan.outputCols
} else {
outputCols = allCols
}
ep := execPlan{outputCols: outputCols}
ep.root, err = b.factory.ConstructApplyJoin(
joinType,
leftPlan.root,
b.presentationToResultColumns(rightRequiredProps.Presentation),
onExpr,
planRightSideFn,
)
if err != nil {
return execPlan{}, err
}
return ep, nil
}
// makePresentation creates a Presentation that contains the given columns, in
// order of their IDs.
func (b *Builder) makePresentation(cols opt.ColSet) physical.Presentation {
md := b.mem.Metadata()
result := make(physical.Presentation, 0, cols.Len())
cols.ForEach(func(col opt.ColumnID) {
result = append(result, opt.AliasedColumn{
Alias: md.ColumnMeta(col).Alias,
ID: col,
})
})
return result
}
// presentationToResultColumns returns ResultColumns corresponding to the
// columns in a presentation.
func (b *Builder) presentationToResultColumns(pres physical.Presentation) colinfo.ResultColumns {
md := b.mem.Metadata()
result := make(colinfo.ResultColumns, len(pres))
for i := range pres {
result[i] = colinfo.ResultColumn{
Name: pres[i].Alias,
Typ: md.ColumnMeta(pres[i].ID).Type,
}
}
return result
}
func (b *Builder) buildHashJoin(join memo.RelExpr) (execPlan, error) {
if f := join.Private().(*memo.JoinPrivate).Flags; f.Has(memo.DisallowHashJoinStoreRight) {
// We need to do a bit of reverse engineering here to determine what the
// hint was.
hint := tree.AstLookup
if !f.Has(memo.DisallowMergeJoin) {
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,
)
if !b.disableTelemetry {
if len(leftEq) > 0 {
telemetry.Inc(sqltelemetry.JoinAlgoHashUseCounter)
} else {
telemetry.Inc(sqltelemetry.JoinAlgoCrossUseCounter)
}
telemetry.Inc(opt.JoinTypeToUseCounter(join.Op()))
}
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.NodeColumnOrdinal, 2*len(leftEq))
leftEqOrdinals := eqColsBuf[:len(leftEq):len(leftEq)]
rightEqOrdinals := eqColsBuf[len(leftEq):]
for i := range leftEq {
leftEqOrdinals[i] = left.getNodeColumnOrdinal(leftEq[i])
rightEqOrdinals[i] = right.getNodeColumnOrdinal(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) {
if !b.disableTelemetry {
telemetry.Inc(sqltelemetry.JoinAlgoMergeUseCounter)
telemetry.Inc(opt.JoinTypeToUseCounter(join.JoinType))
}
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 descpb.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
}