forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_selection.go
1855 lines (1723 loc) · 58.5 KB
/
index_selection.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 2016 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sql
import (
"bytes"
"fmt"
"sort"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/pkg/errors"
)
const nonCoveringIndexPenalty = 10
// analyzeOrderingFn is the interface through which the index selection code
// discovers how useful is the ordering provided by a certain index. The higher
// layer (select) desires a certain ordering on a number of columns; it calls
// into the index selection code with an analyzeOrderingFn that computes how
// many columns of that desired ordering are satisfied by the index ordering.
// Both the number of matching columns and the total columns in the desired
// ordering are returned.
//
// For example, consider the table t {
// a INT,
// b INT,
// c INT,
// INDEX ab (a, b)
// INDEX bac (b, a, c)
// }
//
// For `SELECT * FROM t ORDER BY a, c`, the desired ordering is (a, c);
// totalCols is 2. In this case:
// - the primary index has no ordering on a, b, c; matchingCols is 0.
// - the ab index matches the first column of the desired ordering;
// matchingCols is 1.
// - the bac index doesn't match the desired ordering at all; mathcingCols
// is 0.
//
// For `SELECT * FROM t WHERE b=1 ORDER BY a, c`, the desired ordering is (a, c);
// totalCols is 2. In this case:
// - the primary index has no ordering on a, b, c; matchingCols is 0.
// - the ab index matches the first column of the desired ordering;
// matchingCols is 1.
// - the bac index, along with the fact that b is constrained to a single
// value, matches the desired ordering; matchingCols is 2.
type analyzeOrderingFn func(indexOrdering orderingInfo) (matchingCols, totalCols int)
// selectIndex analyzes the scanNode to determine if there is an index
// available that can fulfill the query with a more restrictive scan.
//
// Analysis currently consists of a simplification of the filter expression,
// replacing expressions which are not usable by indexes by "true". The
// simplified expression is then considered for each index and a set of range
// constraints is created for the index. The candidate indexes are ranked using
// these constraints and the best index is selected. The constraints are then
// transformed into a set of spans to scan within the index.
//
// The analyzeOrdering function is used to determine how useful the ordering of
// an index is. If no particular ordering is desired, it can be nil.
//
// If preferOrderMatching is true, we prefer an index that matches the desired
// ordering completely, even if it is not a covering index.
func (p *planner) selectIndex(
ctx context.Context, s *scanNode, analyzeOrdering analyzeOrderingFn, preferOrderMatching bool,
) (planNode, error) {
if s.desc.IsEmpty() {
// No table.
s.initOrdering(0)
return s, nil
}
if s.filter == nil && analyzeOrdering == nil && s.specifiedIndex == nil {
// No where-clause, no ordering, and no specified index.
s.initOrdering(0)
var err error
s.spans, err = makeSpans(nil, s.desc, s.index)
if err != nil {
return nil, errors.Wrapf(err, "table ID = %d, index ID = %d", s.desc.ID, s.index.ID)
}
return s, nil
}
candidates := make([]*indexInfo, 0, len(s.desc.Indexes)+1)
if s.specifiedIndex != nil {
// An explicit secondary index was requested. Only add it to the candidate
// indexes list.
candidates = append(candidates, &indexInfo{
desc: s.desc,
index: s.specifiedIndex,
})
} else {
candidates = append(candidates, &indexInfo{
desc: s.desc,
index: &s.desc.PrimaryIndex,
})
for i := range s.desc.Indexes {
candidates = append(candidates, &indexInfo{
desc: s.desc,
index: &s.desc.Indexes[i],
})
}
}
for _, c := range candidates {
c.init(s)
}
if s.filter != nil {
// Analyze the filter expression, simplifying it and splitting it up into
// possibly overlapping ranges.
exprs, equivalent := analyzeExpr(&p.evalCtx, s.filter)
if log.V(2) {
log.Infof(ctx, "analyzeExpr: %s -> %s [equivalent=%v]", s.filter, exprs, equivalent)
}
// Check to see if the filter simplified to a constant.
if len(exprs) == 1 && len(exprs[0]) == 1 {
if d, ok := exprs[0][0].(*parser.DBool); ok && bool(!*d) {
// The expression simplified to false.
return &zeroNode{}, nil
}
}
// If the simplified expression is equivalent and there is a single
// disjunction, use it for the filter instead of the original expression.
if equivalent && len(exprs) == 1 {
s.filter = joinAndExprs(exprs[0])
}
// TODO(pmattis): If "len(exprs) > 1" then we have multiple disjunctive
// expressions. For example, "a <= 1 OR a >= 5" will get translated into
// "[[a <= 1], [a >= 5]]".
//
// We currently map all disjunctions onto the same index; this works
// well if we can derive constraints for a set of columns from all
// disjunctions, e.g. `a < 5 OR a > 10`.
//
// However, we can't generate any constraints if the disjunctions refer
// to different columns, e.g. `a > 1 OR b > 1`. We would need to perform
// index selection independently for each of the disjunctive
// expressions, and we would need infrastructure to do a
// multi-index-join. There are complexities: if there are a large
// number of disjunctive expressions we should limit how many indexes we
// use.
for _, c := range candidates {
c.analyzeExprs(exprs)
}
}
if s.noIndexJoin {
// Eliminate non-covering indexes. We do this after the check above for
// constant false filter.
for i := 0; i < len(candidates); {
if !candidates[i].covering {
candidates[i] = candidates[len(candidates)-1]
candidates = candidates[:len(candidates)-1]
} else {
i++
}
}
if len(candidates) == 0 {
// The primary index is always covering. So the only way this can
// happen is if we had a specified index.
if s.specifiedIndex == nil {
panic("no covering indexes")
}
return nil, fmt.Errorf("index \"%s\" is not covering and NO_INDEX_JOIN was specified",
s.specifiedIndex.Name)
}
}
if analyzeOrdering != nil {
for _, c := range candidates {
c.analyzeOrdering(ctx, s, analyzeOrdering, preferOrderMatching)
}
}
indexInfoByCost(candidates).Sort()
if log.V(2) {
for i, c := range candidates {
log.Infof(ctx, "%d: selectIndex(%s): cost=%v constraints=%s reverse=%t",
i, c.index.Name, c.cost, c.constraints, c.reverse)
}
}
// After sorting, candidates[0] contains the best index. Copy its info into
// the scanNode.
c := candidates[0]
s.index = c.index
s.specifiedIndex = nil
s.isSecondaryIndex = (c.index != &s.desc.PrimaryIndex)
var err error
s.spans, err = makeSpans(c.constraints, c.desc, c.index)
if err != nil {
return nil, errors.Wrapf(err, "constraints = %v, table ID = %d, index ID = %d",
c.constraints, s.desc.ID, s.index.ID)
}
if len(s.spans) == 0 {
// There are no spans to scan.
return &zeroNode{}, nil
}
s.filter = applyIndexConstraints(&p.evalCtx, s.filter, c.constraints)
if s.filter != nil {
// Constraint propagation may have produced new constant sub-expressions.
// Propagate them and check if s.filter can be applied prematurely.
var err error
s.filter, err = p.evalCtx.NormalizeExpr(s.filter)
if err != nil {
return nil, err
}
if s.filter == parser.DBoolFalse {
return &zeroNode{}, nil
}
if s.filter == parser.DBoolTrue {
s.filter = nil
}
}
s.filterVars.Rebind(s.filter, true, false)
s.reverse = c.reverse
var plan planNode
if c.covering {
s.initOrdering(c.exactPrefix)
plan = s
} else {
// Note: makeIndexJoin destroys s and returns a new index scan
// node. The filter in that node may be different from the
// original table filter.
plan, s = s.p.makeIndexJoin(s, c.exactPrefix)
}
if log.V(3) {
log.Infof(ctx, "%s: filter=%v", c.index.Name, s.filter)
for i, span := range s.spans {
log.Infof(ctx, "%s/%d: %s", c.index.Name, i, sqlbase.PrettySpan(span, 2))
}
}
return plan, nil
}
type indexConstraint struct {
start *parser.ComparisonExpr
end *parser.ComparisonExpr
// tupleMap is an ordering of the tuples within a tuple comparison such that
// they match the ordering within the index. For example, an index on the
// columns (a, b) and a tuple comparison "(b, a) = (1, 2)" would have a
// tupleMap of {1, 0} indicating that the first column to be encoded is the
// second element of the tuple. The tuple map may be shorter than the length
// of the tuple. For example, if the index was only on (a), then the tupleMap
// would be {1}.
tupleMap []int
}
// numColumns returns the number of columns this constraint applies to. Only
// constraints for expressions with tuple comparisons apply to multiple columns.
func (ic indexConstraint) numColumns() int {
if ic.tupleMap == nil {
return 1
}
return len(ic.tupleMap)
}
func (ic indexConstraint) String() string {
var buf bytes.Buffer
if ic.start != nil {
fmt.Fprintf(&buf, "%s", ic.start)
}
if ic.end != nil && ic.end != ic.start {
if ic.start != nil {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%s", ic.end)
}
return buf.String()
}
// indexConstraints is a set of constraints on a prefix of the columns
// in a single index. The constraints are ordered as the columns in the index.
// A constraint referencing a tuple accounts for several columns (the size of
// its .tupleMap).
type indexConstraints []indexConstraint
func (ic indexConstraints) String() string {
var buf bytes.Buffer
buf.WriteString("[")
for i := range ic {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(ic[i].String())
}
buf.WriteString("]")
return buf.String()
}
// orIndexConstraints stores multiple indexConstraints, one for each top level
// disjunction in our filtering expression. Each indexConstraints element
// generates a set of spans; these sets of spans are merged.
type orIndexConstraints []indexConstraints
func (oic orIndexConstraints) String() string {
var buf bytes.Buffer
for i := range oic {
if i > 0 {
buf.WriteString(" OR ")
}
buf.WriteString(oic[i].String())
}
return buf.String()
}
type indexInfo struct {
desc *sqlbase.TableDescriptor
index *sqlbase.IndexDescriptor
constraints orIndexConstraints
cost float64
covering bool // Does the index cover the required IndexedVars?
reverse bool
exactPrefix int
}
func (v *indexInfo) init(s *scanNode) {
v.covering = v.isCoveringIndex(s)
// The base cost is the number of keys per row.
if v.index == &v.desc.PrimaryIndex {
// The primary index contains 1 key per column plus the sentinel key per
// row.
v.cost = float64(1 + len(v.desc.Columns) - len(v.desc.PrimaryIndex.ColumnIDs))
} else {
v.cost = 1
if !v.covering {
v.cost += float64(1 + len(v.desc.Columns) - len(v.desc.PrimaryIndex.ColumnIDs))
// Non-covering indexes are significantly more expensive than covering
// indexes.
v.cost *= nonCoveringIndexPenalty
}
}
}
// analyzeExprs examines the range map to determine the cost of using the
// index.
func (v *indexInfo) analyzeExprs(exprs []parser.TypedExprs) {
if err := v.makeOrConstraints(exprs); err != nil {
panic(err)
}
// Count the number of elements used to limit the start and end keys. We then
// boost the cost by what fraction of the index keys are being used. The
// higher the fraction, the lower the cost.
if len(v.constraints) == 0 {
// The index isn't being restricted at all, bump the cost significantly to
// make any index which does restrict the keys more desirable.
v.cost *= 1000
} else {
// When we have multiple indexConstraints, each one is for a top-level
// disjunction (OR); together they are no more restrictive than any one of
// them. We thus calculate the cost based on the disjunction which restricts
// the smallest number of columns.
//
// TODO(radu): we need to be more discriminating - constraints such as
// "NOT NULL" are almost as useless as no constraints, whereas "exact value"
// constraints are very restrictive.
minNumCols := len(v.index.ColumnIDs)
for _, cset := range v.constraints {
numCols := 0
for _, c := range cset {
numCols += c.numColumns()
}
if numCols < minNumCols {
minNumCols = numCols
}
}
v.cost *= float64(len(v.index.ColumnIDs)) / float64(minNumCols)
}
}
// analyzeOrdering analyzes the ordering provided by the index and determines
// if it matches the ordering requested by the query. Non-matching orderings
// increase the cost of using the index.
//
// If preferOrderMatching is true, we prefer an index that matches the desired
// ordering completely, even if it is not a covering index.
func (v *indexInfo) analyzeOrdering(
ctx context.Context, scan *scanNode, analyzeOrdering analyzeOrderingFn, preferOrderMatching bool,
) {
// Compute the prefix of the index for which we have exact constraints. This
// prefix is inconsequential for ordering because the values are identical.
v.exactPrefix = v.constraints.exactPrefix(&scan.p.evalCtx)
// Analyze the ordering provided by the index (either forward or reverse).
fwdIndexOrdering := scan.computeOrdering(v.index, v.exactPrefix, false)
revIndexOrdering := scan.computeOrdering(v.index, v.exactPrefix, true)
fwdMatch, fwdOrderCols := analyzeOrdering(fwdIndexOrdering)
revMatch, revOrderCols := analyzeOrdering(revIndexOrdering)
if fwdOrderCols != revOrderCols {
panic(fmt.Sprintf("fwdOrderCols(%d) != revOrderCols(%d)", fwdOrderCols, revOrderCols))
}
orderCols := fwdOrderCols
// Weigh the cost by how much of the ordering matched.
//
// TODO(pmattis): Need to determine the relative weight for index selection
// based on sorting vs index selection based on filtering. Sorting is
// expensive due to the need to buffer up the rows and perform the sort, but
// not filtering is also expensive due to the larger number of rows scanned.
match := fwdMatch
if match < revMatch {
match = revMatch
v.reverse = true
}
weight := float64(orderCols+1) / float64(match+1)
v.cost *= weight
if match == orderCols && preferOrderMatching {
// Offset the non-covering index cost penalty.
v.cost *= (1.0 / nonCoveringIndexPenalty)
}
if log.V(2) {
log.Infof(ctx, "%s: analyzeOrdering: weight=%0.2f reverse=%v match=%d",
v.index.Name, weight, v.reverse, match)
}
}
// getColVarIdx detects whether an expression is a straightforward
// reference to a column or index variable. In this case it returns
// the index of that column's in the descriptor's []Column array.
// Used by indexInfo.makeIndexConstraints().
func getColVarIdx(expr parser.Expr) (ok bool, colIdx int) {
switch q := expr.(type) {
case *parser.IndexedVar:
return true, q.Idx
}
return false, -1
}
// makeOrConstraints populates the indexInfo.constraints field based on the
// analyzed expressions. Each element of constraints corresponds to one
// of the top-level disjunctions and is generated using makeIndexConstraint.
func (v *indexInfo) makeOrConstraints(orExprs []parser.TypedExprs) error {
constraints := make(orIndexConstraints, len(orExprs))
for i, e := range orExprs {
var err error
constraints[i], err = v.makeIndexConstraints(e)
if err != nil {
return err
}
// If an OR branch has no constraints, we cannot have _any_
// constraints.
if len(constraints[i]) == 0 {
return nil
}
}
v.constraints = constraints
return nil
}
// makeIndexConstraints generates constraints for a set of conjunctions (AND
// expressions). These expressions can be the entire filter, or they can be one
// of multiple top-level disjunctions (ORs).
//
// The constraints consist of start and end expressions for a prefix of the
// columns that make up the index. For example, consider the expression
// "a >= 1 AND b >= 2":
//
// {a: {start: >= 1}, b: {start: >= 2}}
//
// This method generates one indexConstraint for a prefix of the columns in
// the index (except for tuple constraints which can account for more than
// one column). A prefix of the generated constraints has a .start, and
// similarly a prefix of the constraints has a .end (in other words,
// once a constraint doesn't have a .start, no further constraints will
// have one). This is because they wouldn't be useful when generating spans.
//
// makeIndexConstraints takes into account the direction of the columns in the
// index. For ascending cols, start constraints look for comparison expressions
// with the operators >, >=, = or IN and end constraints look for comparison
// expressions with the operators <, <=, = or IN. Vice versa for descending
// cols.
//
// Whenever possible, < and > are converted to <= and >=, respectively.
// This is because we can use inclusive constraints better than exclusive ones;
// with inclusive constraints we can continue to accumulate constraints for
// next columns. Not so with exclusive ones: Consider "a < 1 AND b < 2".
// "a < 1" will be encoded as an exclusive span end; if we were to append
// anything about "b" to it, that would be incorrect.
// Note that it's not always possible to transform ">" to ">=", because some
// types do not support the Next() operation. Similarly, it is not always possible
// to transform "<" to "<=", because some types do not support the Prev() operation.
// So, the resulting constraints might contain ">" or "<" (depending on encoding
// direction), in which case that will be the last constraint with `.end` filled.
//
// TODO(pmattis): It would be more obvious to perform this transform in
// simplifyComparisonExpr, but doing so there eliminates some of the other
// simplifications. For example, "a < 1 OR a > 1" currently simplifies to "a !=
// 1", but if we performed this transform in simplifyComparisonExpr it would
// simplify to "a < 1 OR a >= 2" which is also the same as "a != 1", but not so
// obvious based on comparisons of the constants.
func (v *indexInfo) makeIndexConstraints(andExprs parser.TypedExprs) (indexConstraints, error) {
var constraints indexConstraints
trueStartDone := false
trueEndDone := false
for i := 0; i < len(v.index.ColumnIDs); i++ {
colID := v.index.ColumnIDs[i]
var colDir encoding.Direction
var err error
if colDir, err = v.index.ColumnDirections[i].ToEncodingDirection(); err != nil {
return nil, err
}
var constraint indexConstraint
// We're going to fill in that start and end of the constraint
// by indirection, which keeps in mind the direction of the
// column's encoding in the index.
// This allows us to produce direction-aware constraints, but
// still have the code below be intuitive (e.g. treat ">" always as
// a start constraint).
startExpr := &constraint.start
endExpr := &constraint.end
startDone := &trueStartDone
endDone := &trueEndDone
if colDir == encoding.Descending {
// For descending index cols, c.start is an end constraint
// and c.end is a start constraint.
startExpr = &constraint.end
endExpr = &constraint.start
startDone = &trueEndDone
endDone = &trueStartDone
}
exprLoop:
for _, e := range andExprs {
if c, ok := e.(*parser.ComparisonExpr); ok {
var tupleMap []int
if ok, colIdx := getColVarIdx(c.Left); ok && v.desc.Columns[colIdx].ID != colID {
// This expression refers to a column other than the one we're
// looking for.
continue
}
if _, ok := c.Right.(parser.Datum); !ok {
continue
}
if t, ok := c.Left.(*parser.Tuple); ok {
// If we have a tuple comparison we need to rearrange the comparison
// so that the order of the columns in the tuple matches the order in
// the index. For example, for an index on (a, b), the tuple
// comparison "(b, a) = (1, 2)" would be rewritten as "(a, b) = (2,
// 1)". Note that we don't actually need to rewrite the comparison,
// but simply provide a mapping from the order in the tuple to the
// order in the index.
for _, colID := range v.index.ColumnIDs[i:] {
idx := -1
for i, val := range t.Exprs {
ok, colIdx := getColVarIdx(val)
if ok && v.desc.Columns[colIdx].ID == colID {
idx = i
break
}
}
if idx == -1 {
break
}
tupleMap = append(tupleMap, idx)
}
if len(tupleMap) == 0 {
// This tuple does not contain the column we're looking for.
continue
}
// Skip all the next columns covered by this tuple.
i += (len(tupleMap) - 1)
if c.Operator != parser.In {
// Make sure all columns specified in the tuple are in the index.
// TODO(mjibson): support prefixes: (a,b,c) > (1,2,3) -> (a,b) >= (1,2)
if len(t.Exprs) > len(tupleMap) {
continue
}
// Since tuples comparison is lexicographic, we only support it if the tuple
// is in the same order as the index.
for i, v := range tupleMap {
if i != v {
continue exprLoop
}
}
// Due to the implementation of the encoding functions, it is currently
// difficult to support indexes of varying directions with tuples. For now,
// restrict them to a single direction. See #6346.
dir := v.index.ColumnDirections[i]
for _, ti := range tupleMap {
if dir != v.index.ColumnDirections[ti] {
continue exprLoop
}
}
}
constraint.tupleMap = tupleMap
}
preStart := *startExpr
preEnd := *endExpr
switch c.Operator {
case parser.EQ:
// An equality constraint will overwrite any other type
// of constraint.
if !*startDone {
*startExpr = c
}
if !*endDone {
*endExpr = c
}
case parser.NE:
// We rewrite "a != x" to "a IS NOT NULL", since this is all that
// makeSpans() cares about.
// We don't simplify "a != x" to "a IS NOT NULL" in
// simplifyExpr because doing so affects other simplifications.
if *startDone || *startExpr != nil {
continue
}
*startExpr = parser.NewTypedComparisonExpr(
parser.IsNot,
c.TypedLeft(),
parser.DNull,
)
case parser.In:
// Only allow the IN constraint if the previous constraints are all
// EQ. This is necessary to prevent overlapping spans from being
// generated. Consider the constraints [a >= 1, a <= 2, b IN (1,
// 2)]. This would turn into the spans /1/1-/3/2 and /1/2-/3/3.
ok := true
for _, c := range constraints {
ok = ok && (c.start == c.end) && (c.start.Operator == parser.EQ)
}
if !ok {
continue
}
if !*startDone && (*startExpr == nil || (*startExpr).Operator != parser.EQ) {
*startExpr = c
}
if !*endDone && (*endExpr == nil || (*endExpr).Operator != parser.EQ) {
*endExpr = c
}
case parser.GE:
if !*startDone && *startExpr == nil {
*startExpr = c
}
case parser.GT:
// Transform ">" into ">=".
if *startDone || (*startExpr != nil) {
continue
}
if c.Right.(parser.Datum).IsMax() {
*startExpr = parser.NewTypedComparisonExpr(
parser.EQ,
c.TypedLeft(),
c.TypedRight(),
)
} else if nextRightVal, hasNext := c.Right.(parser.Datum).Next(); hasNext {
*startExpr = parser.NewTypedComparisonExpr(
parser.GE,
c.TypedLeft(),
nextRightVal,
)
} else {
*startExpr = c
}
case parser.LT:
if *endDone || (*endExpr != nil) {
continue
}
// Transform "<" into "<=".
if c.Right.(parser.Datum).IsMin() {
*endExpr = parser.NewTypedComparisonExpr(
parser.EQ,
c.TypedLeft(),
c.TypedRight(),
)
} else if prevRightVal, hasPrev := c.Right.(parser.Datum).Prev(); hasPrev {
*endExpr = parser.NewTypedComparisonExpr(
parser.LE,
c.TypedLeft(),
prevRightVal,
)
} else {
*endExpr = c
}
case parser.LE:
if !*endDone && *endExpr == nil {
*endExpr = c
}
case parser.Is:
if c.Right == parser.DNull && !*endDone {
*endExpr = c
}
case parser.IsNot:
if c.Right == parser.DNull && !*startDone && (*startExpr == nil) {
*startExpr = c
}
}
// If a new constraint includes a mixed-type comparison expression,
// we can not include it in the index constraints because the index
// encoding would be incorrect. See #4313.
if preStart != *startExpr {
if (*startExpr).IsMixedTypeComparison() {
*startExpr = nil
}
}
if preEnd != *endExpr {
if (*endExpr).IsMixedTypeComparison() {
*endExpr = nil
}
}
}
}
if *endExpr != nil && (*endExpr).Operator == parser.LT {
*endDone = true
}
if !*startDone && *startExpr == nil {
// Add an IS NOT NULL constraint if there's an end constraint.
if (*endExpr != nil) &&
!((*endExpr).Operator == parser.Is && (*endExpr).Right == parser.DNull) {
*startExpr = parser.NewTypedComparisonExpr(
parser.IsNot,
(*endExpr).TypedLeft(),
parser.DNull,
)
}
}
if (*startExpr == nil) ||
(((*startExpr).Operator == parser.IsNot) && ((*startExpr).Right == parser.DNull)) {
// There's no point in allowing future start constraints after an IS NOT NULL
// one; since NOT NULL is not actually a value present in an index,
// values encoded after an NOT NULL don't matter.
*startDone = true
}
if constraint.start != nil || constraint.end != nil {
constraints = append(constraints, constraint)
}
if *endExpr == nil {
*endDone = true
}
if *startDone && *endDone {
// The rest of the expressions don't matter; when we construct index spans
// based on these constraints we won't be able to accumulate more in either
// the start key prefix nor the end key prefix.
break
}
}
return constraints, nil
}
// isCoveringIndex returns true if all of the columns needed from the scanNode are contained within
// the index. This allows a scan of only the index to be performed without requiring subsequent
// lookup of the full row.
func (v *indexInfo) isCoveringIndex(scan *scanNode) bool {
if v.index == &v.desc.PrimaryIndex {
// The primary key index always covers all of the columns.
return true
}
for i, needed := range scan.valNeededForCol {
if needed {
colID := v.desc.Columns[i].ID
if !v.index.ContainsColumnID(colID) {
return false
}
}
}
return true
}
type indexInfoByCost []*indexInfo
func (v indexInfoByCost) Len() int {
return len(v)
}
func (v indexInfoByCost) Less(i, j int) bool {
return v[i].cost < v[j].cost
}
func (v indexInfoByCost) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
func (v indexInfoByCost) Sort() {
sort.Sort(v)
}
func encodeStartConstraintAscending(c *parser.ComparisonExpr) logicalKeyPart {
switch c.Operator {
case parser.IsNot:
// A IS NOT NULL expression allows us to constrain the start of
// the range to not include NULL.
if c.Right != parser.DNull {
panic(fmt.Sprintf("expected NULL operand for IS NOT operator, found %v", c.Right))
}
return logicalKeyPart{
val: parser.DNull,
dir: encoding.Ascending,
inclusive: false,
}
case parser.NE:
panic("'!=' operators should have been transformed to 'IS NOT NULL'")
case parser.GE, parser.EQ, parser.GT:
return logicalKeyPart{
val: c.Right.(parser.Datum),
dir: encoding.Ascending,
inclusive: c.Operator != parser.GT,
}
default:
panic(fmt.Sprintf("unexpected operator: %s", c))
}
}
func encodeStartConstraintDescending(c *parser.ComparisonExpr) logicalKeyPart {
switch c.Operator {
case parser.Is:
// An IS NULL expressions allows us to constrain the start of the range
// to begin at NULL.
if c.Right != parser.DNull {
panic(fmt.Sprintf("expected NULL operand for IS operator, found %v", c.Right))
}
return logicalKeyPart{
val: parser.DNull,
dir: encoding.Descending,
inclusive: true,
}
case parser.NE:
panic("'!=' operators should have been transformed to 'IS NOT NULL'")
case parser.LE, parser.EQ, parser.LT:
return logicalKeyPart{
val: c.Right.(parser.Datum),
dir: encoding.Descending,
inclusive: c.Operator != parser.LT,
}
default:
panic(fmt.Sprintf("unexpected operator: %s", c))
}
}
func encodeEndConstraintAscending(c *parser.ComparisonExpr) logicalKeyPart {
switch c.Operator {
case parser.Is:
// An IS NULL expressions allows us to constrain the end of the range
// to stop at NULL.
if c.Right != parser.DNull {
panic(fmt.Sprintf("expected NULL operand for IS operator, found %v", c.Right))
}
return logicalKeyPart{
val: parser.DNull,
dir: encoding.Ascending,
inclusive: true,
}
case parser.NE:
panic("'!=' operators should have been transformed to 'IS NOT NULL'")
case parser.LE, parser.EQ, parser.LT:
return logicalKeyPart{
val: c.Right.(parser.Datum),
dir: encoding.Ascending,
inclusive: c.Operator != parser.LT,
}
default:
panic(fmt.Sprintf("unexpected operator: %s", c))
}
}
func encodeEndConstraintDescending(c *parser.ComparisonExpr) logicalKeyPart {
switch c.Operator {
case parser.IsNot:
// An IS NOT NULL expressions allows us to constrain the end of the range
// to stop at NULL.
if c.Right != parser.DNull {
panic(fmt.Sprintf("expected NULL operand for IS NOT operator, found %v", c.Right))
}
return logicalKeyPart{
val: parser.DNull,
dir: encoding.Descending,
inclusive: false,
}
case parser.NE:
panic("'!=' operators should have been transformed to 'IS NOT NULL'")
case parser.GE, parser.EQ, parser.GT:
return logicalKeyPart{
val: c.Right.(parser.Datum),
dir: encoding.Descending,
inclusive: c.Operator != parser.GT,
}
default:
panic(fmt.Sprintf("unexpected operator: %s", c))
}
}
// Splits spans according to a constraint like (...) in <tuple>.
// If the constraint is (a,b) IN ((1,2),(3,4)), each input span
// will be split into two: the first one will have "1/2" appended to
// the start and/or end, the second one will have "3/4" appended to
// the start and/or end.
//
// Returns the exploded spans.
func applyInConstraint(
spans []logicalSpan, c indexConstraint, firstCol int, index *sqlbase.IndexDescriptor,
) ([]logicalSpan, error) {
var e *parser.ComparisonExpr
// It might be that the IN constraint is a start constraint, an
// end constraint, or both, depending on how whether we had
// start and end constraints for all the previous index cols.
if c.start != nil && c.start.Operator == parser.In {
e = c.start
} else {
e = c.end
}
tuple := e.Right.(*parser.DTuple).D
existingSpans := spans
spans = make([]logicalSpan, 0, len(existingSpans)*len(tuple))
for _, datum := range tuple {
// parts will accumulate the constraint for the current element of the
// tuple.
var parts []logicalKeyPart
switch t := datum.(type) {
case *parser.DTuple:
// The constraint is a tuple of tuples, meaning something like
// (...) IN ((1,2),(3,4)).
for j, tupleIdx := range c.tupleMap {
dir, err := index.ColumnDirections[firstCol+j].ToEncodingDirection()
if err != nil {
return nil, err
}
parts = append(parts, logicalKeyPart{
val: t.D[tupleIdx],
dir: dir,
inclusive: true,
})
}
default:
// The constraint is a tuple of values, meaning something like
// a IN (1,2).
dir, err := index.ColumnDirections[firstCol].ToEncodingDirection()
if err != nil {
return nil, err
}
parts = append(parts, logicalKeyPart{
val: datum,
dir: dir,
inclusive: true,
})
}
for _, s := range existingSpans {
if c.start != nil {
// Don't append directly to the existing slice, or we
// may introduce unwanted aliasing (see #20035).
old := s.start
s.start = make([]logicalKeyPart, 0, len(old)+len(parts))
s.start = append(s.start, old...)
s.start = append(s.start, parts...)
}
if c.end != nil {
old := s.end
s.end = make([]logicalKeyPart, 0, len(old)+len(parts))
s.end = append(s.end, old...)
s.end = append(s.end, parts...)
}
spans = append(spans, s)