-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
relational.go
3055 lines (2711 loc) · 94.3 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"
"strings"
"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/constraint"
"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"
"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/builtinsregistry"
"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/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/buildutil"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
)
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", redact.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
}
if opt.IsMutationOp(e) {
b.ContainsMutation = true
// Raise error if mutation op is part of a read-only transaction.
if b.evalCtx.TxnReadOnly {
return execPlan{}, pgerror.Newf(pgcode.ReadOnlySQLTransaction,
"cannot execute %s in a read-only transaction", b.statementTag(e))
}
}
// Raise error if bounded staleness is used incorrectly.
if b.boundedStaleness() {
if _, ok := boundedStalenessAllowList[e.Op()]; !ok {
return execPlan{}, unimplemented.NewWithIssuef(67562,
"cannot use bounded staleness for %s", 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.LiteralValuesExpr:
ep, err = b.buildLiteralValues(t)
case *memo.ScanExpr:
ep, err = b.buildScan(t)
case *memo.PlaceholderScanExpr:
ep, err = b.buildPlaceholderScan(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.TopKExpr:
ep, err = b.buildTopK(t)
case *memo.LimitExpr, *memo.OffsetExpr:
ep, err = b.buildLimitOffset(e)
case *memo.SortExpr:
ep, err = b.buildSort(t)
case *memo.DistributeExpr:
ep, err = b.buildDistribute(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.CreateFunctionExpr:
ep, err = b.buildCreateFunction(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.AlterRangeRelocateExpr:
ep, err = b.buildAlterRangeRelocate(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.CreateStatisticsExpr:
ep, err = b.buildCreateStatistics(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 test builds, assert that the exec plan output columns match the opt
// plan output columns.
if buildutil.CrdbTestBuild {
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. op: %T", optCols, execCols, e)
}
}
b.maybeAnnotateWithEstimates(ep.root, e)
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
}
// maybeAnnotateWithEstimates checks if we are building against an
// ExplainFactory and annotates the node with more information if so.
func (b *Builder) maybeAnnotateWithEstimates(node exec.Node, e memo.RelExpr) {
if ef, ok := b.factory.(exec.ExplainFactory); ok {
stats := &e.Relational().Stats
val := exec.EstimatedStats{
TableStatsAvailable: stats.Available,
RowCount: stats.RowCount,
Cost: float64(e.Cost()),
}
if scan, ok := e.(*memo.ScanExpr); ok {
tab := b.mem.Metadata().Table(scan.Table)
if tab.StatisticCount() > 0 {
// The first stat is the most recent one.
stat := tab.Statistic(0)
val.TableStatsRowCount = stat.RowCount()
if val.TableStatsRowCount == 0 {
val.TableStatsRowCount = 1
}
val.TableStatsCreatedAt = stat.CreatedAt()
val.LimitHint = scan.RequiredPhysical().LimitHint
val.Forecast = stat.IsForecast()
if val.Forecast {
val.ForecastAt = stat.CreatedAt()
// Find the first non-forecast stat.
for i := 0; i < tab.StatisticCount(); i++ {
nextStat := tab.Statistic(i)
if !nextStat.IsForecast() {
val.TableStatsCreatedAt = nextStat.CreatedAt()
break
}
}
}
}
}
ef.AnnotateNode(node, exec.EstimatedStatsID, &val)
}
}
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 := makeTypedExprMatrix(len(values.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)
}
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
}
// makeTypedExprMatrix allocates a TypedExpr matrix of the given size.
func makeTypedExprMatrix(numRows, numCols int) [][]tree.TypedExpr {
rows := make([][]tree.TypedExpr, numRows)
rowBuf := make([]tree.TypedExpr, numRows*numCols)
for i := range rows {
// Chop off prefix of rowBuf and limit its capacity.
rows[i] = rowBuf[:numCols:numCols]
rowBuf = rowBuf[numCols:]
}
return rows
}
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
}
func (b *Builder) buildLiteralValues(values *memo.LiteralValuesExpr) (execPlan, error) {
md := b.mem.Metadata()
resultCols := make(colinfo.ResultColumns, len(values.ColList()))
for i, col := range values.ColList() {
colMeta := md.ColumnMeta(col)
resultCols[i].Name = colMeta.Alias
resultCols[i].Typ = colMeta.Type
}
node, err := b.factory.ConstructLiteralValues(values.Rows.Rows, resultCols)
if err != nil {
return execPlan{}, err
}
ep := execPlan{root: node}
for i, col := range values.ColList() {
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.ScanPrivate, relProps *props.Relational,
) (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())
}
if !relProps.FuncDeps.ColsAreLaxKey(indexCols) {
return 0, false
}
return c.CalculateMaxResults(b.evalCtx, indexCols, relProps.NotNullCols)
}
// scanParams populates ScanParams and the output column mapping.
func (b *Builder) scanParams(
tab cat.Table, scan *memo.ScanPrivate, relProps *props.Relational, reqProps *physical.Required,
) (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 = pgerror.Newf(pgcode.WrongObjectType,
"index \"%s\" is a partial inverted index and cannot be used for this query",
idx.Name(),
)
case isInverted:
err = pgerror.Newf(pgcode.WrongObjectType,
"index \"%s\" is inverted and cannot be used for this query",
idx.Name(),
)
case isPartial:
err = pgerror.Newf(pgcode.WrongObjectType,
"index \"%s\" is a partial index that does not contain all the rows needed to execute this query",
idx.Name(),
)
default:
err = pgerror.Newf(pgcode.WrongObjectType,
"index \"%s\" cannot be used for this query", idx.Name())
if b.evalCtx.SessionData().DisallowFullTableScans &&
(b.ContainsLargeFullTableScan || b.ContainsLargeFullIndexScan) {
err = errors.WithHint(err,
"try overriding the `disallow_full_table_scans` or increasing the `large_full_scan_rows` cluster/session settings",
)
}
}
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.
// TODO(nvanbenschoten): this check should be shared across all expressions
// that can perform row-level locking.
if locking.IsLocking() && 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. When there are no
// statistics available, we construct a scan node with
// the estimated row count of zero rows.
//
// 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.
var rowCount float64
if relProps.Stats.Available {
rowCount = relProps.Stats.RowCount
}
if scan.PartitionConstrainedScan {
sqltelemetry.IncrementPartitioningCounter(sqltelemetry.PartitionConstrainedScan)
}
softLimit := reqProps.LimitHintInt64()
hardLimit := scan.HardLimit.RowCount()
// If this is a bounded staleness query, check that it touches at most one
// range.
if b.boundedStaleness() {
valid := true
if b.containsBoundedStalenessScan {
// We already planned a scan, perhaps as part of a subquery.
valid = false
} else if hardLimit != 0 {
// If hardLimit is not 0, from KV's perspective, this is a multi-row scan
// with a limit. That means that even if the limit is 1, the scan can span
// multiple ranges if the first range is empty.
valid = false
} else {
maxResults, ok := b.indexConstraintMaxResults(scan, relProps)
valid = ok && maxResults == 1
}
if !valid {
return exec.ScanParams{}, opt.ColMap{}, unimplemented.NewWithIssuef(67562,
"cannot use bounded staleness for queries that may touch more than one range or require an index join",
)
}
b.containsBoundedStalenessScan = true
}
parallelize := false
if hardLimit == 0 && softLimit == 0 {
maxResults, ok := b.indexConstraintMaxResults(scan, relProps)
if ok && maxResults < getParallelScanResultThreshold(b.evalCtx.TestingKnobs.ForceProductionValues) {
// 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
}
}
}
// Figure out if we need to scan in reverse (ScanPrivateCanProvide takes
// HardLimit.Reverse() into account).
ok, reverse := ordering.ScanPrivateCanProvide(
b.mem.Metadata(),
scan,
&reqProps.Ordering,
)
if !ok {
return exec.ScanParams{}, opt.ColMap{}, errors.AssertionFailedf("scan can't provide required ordering")
}
return exec.ScanParams{
NeededCols: needed,
IndexConstraint: scan.Constraint,
InvertedConstraint: scan.InvertedConstraint,
HardLimit: hardLimit,
SoftLimit: softLimit,
Reverse: reverse,
Parallelize: parallelize,
Locking: locking,
EstimatedRowCount: rowCount,
LocalityOptimized: scan.LocalityOptimized,
}, outputMap, nil
}
func (b *Builder) buildScan(scan *memo.ScanExpr) (execPlan, error) {
md := b.mem.Metadata()
tab := md.Table(scan.Table)
if !b.disableTelemetry && scan.PartialIndexPredicate(md) != nil {
telemetry.Inc(sqltelemetry.PartialIndexScanUseCounter)
}
if scan.Flags.ForceZigzag {
return execPlan{}, fmt.Errorf("could not produce a query plan conforming to the FORCE_ZIGZAG hint")
}
isUnfiltered := scan.IsUnfiltered(md)
if scan.Flags.NoFullScan {
// Normally a full scan of a partial index would be allowed with the
// NO_FULL_SCAN hint (isUnfiltered is false for partial indexes), but if the
// user has explicitly forced the partial index *and* used NO_FULL_SCAN, we
// disallow the full index scan.
if isUnfiltered || (scan.Flags.ForceIndex && scan.IsFullIndexScan(md)) {
return execPlan{}, fmt.Errorf("could not produce a query plan conforming to the NO_FULL_SCAN hint")
}
}
// 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.
stats := scan.Relational().Stats
if !tab.IsVirtualTable() && isUnfiltered {
large := !stats.Available || stats.RowCount > b.evalCtx.SessionData().LargeFullScanRows
if scan.Index == cat.PrimaryIndex {
b.ContainsFullTableScan = true
b.ContainsLargeFullTableScan = b.ContainsLargeFullTableScan || large
} else {
b.ContainsFullIndexScan = true
b.ContainsLargeFullIndexScan = b.ContainsLargeFullIndexScan || large
}
if stats.Available && stats.RowCount > b.MaxFullScanRows {
b.MaxFullScanRows = stats.RowCount
}
}
// Save the total estimated number of rows scanned and the time since stats
// were collected.
if stats.Available {
b.TotalScanRows += stats.RowCount
if tab.StatisticCount() > 0 {
// The first stat is the most recent one.
nanosSinceStatsCollected := timeutil.Since(tab.Statistic(0).CreatedAt())
if nanosSinceStatsCollected > b.NanosSinceStatsCollected {
b.NanosSinceStatsCollected = nanosSinceStatsCollected
}
}
}
params, outputCols, err := b.scanParams(tab, &scan.ScanPrivate, scan.Relational(), scan.RequiredPhysical())
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
}
res.root = root
if b.evalCtx.SessionData().EnforceHomeRegion && !b.mem.RootIsExplain() && !b.skipScanExprCollection {
if b.builtScans == nil {
b.builtScans = make([]*memo.ScanExpr, 0, 2)
}
b.builtScans = append(b.builtScans, scan)
}
return res, nil
}
func (b *Builder) buildPlaceholderScan(scan *memo.PlaceholderScanExpr) (execPlan, error) {
if scan.Constraint != nil || scan.InvertedConstraint != nil {
return execPlan{}, errors.AssertionFailedf("PlaceholderScan cannot have constraints")
}
md := b.mem.Metadata()
tab := md.Table(scan.Table)
idx := tab.Index(scan.Index)
// Build the index constraint.
spanColumns := make([]opt.OrderingColumn, len(scan.Span))
for i := range spanColumns {
col := idx.Column(i)
ordinal := col.Ordinal()
colID := scan.Table.ColumnID(ordinal)
spanColumns[i] = opt.MakeOrderingColumn(colID, col.Descending)
}
var columns constraint.Columns
columns.Init(spanColumns)
keyCtx := constraint.MakeKeyContext(&columns, b.evalCtx)
values := make([]tree.Datum, len(scan.Span))
for i, expr := range scan.Span {
// The expression is either a placeholder or a constant.
if p, ok := expr.(*memo.PlaceholderExpr); ok {
val, err := eval.Expr(b.evalCtx, p.Value)
if err != nil {
return execPlan{}, err
}
values[i] = val
} else {
values[i] = memo.ExtractConstDatum(expr)
}
}
key := constraint.MakeCompositeKey(values...)
var span constraint.Span
span.Init(key, constraint.IncludeBoundary, key, constraint.IncludeBoundary)
var spans constraint.Spans
spans.InitSingleSpan(&span)
var c constraint.Constraint
c.Init(&keyCtx, &spans)
private := scan.ScanPrivate
private.SetConstraint(b.evalCtx, &c)
params, outputCols, err := b.scanParams(tab, &private, scan.Relational(), scan.RequiredPhysical())
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
}
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, invFilter.Relational().OutputCols, invFilter.ProvidedPhysical().Ordering)
}
// applySimpleProject adds a simple projection on top of an existing plan.
func (b *Builder) applySimpleProject(
input execPlan, inputExpr memo.RelExpr, cols opt.ColSet, providedOrd opt.Ordering,
) (execPlan, error) {
// Since we are constructing a simple project on top of the main operator,
// we need to explicitly annotate the latter with estimates since the code
// in buildRelational() will attach them to the project.
b.maybeAnnotateWithEstimates(input.root, inputExpr)
// 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.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)
// We will pre-populate the withExprs of the right-hand side execbuilder.
withExprs := make([]builtWithExpr, len(b.withExprs))
copy(withExprs, b.withExprs)
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))