-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
index_constraints.go
1442 lines (1322 loc) · 47.1 KB
/
index_constraints.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 2017 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 idxconstraint
import (
"context"
"regexp"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/constraint"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/norm"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
// Convenience aliases to avoid the constraint prefix everywhere.
const includeBoundary = constraint.IncludeBoundary
const excludeBoundary = constraint.ExcludeBoundary
var emptyKey = constraint.EmptyKey
var emptySpans = constraint.Spans{}
func (c *indexConstraintCtx) contradiction(offset int, out *constraint.Constraint) {
out.Init(&c.keyCtx[offset], &emptySpans)
}
func (c *indexConstraintCtx) unconstrained(offset int, out *constraint.Constraint) {
out.InitSingleSpan(&c.keyCtx[offset], &constraint.UnconstrainedSpan)
}
// singleSpan creates a constraint with a single span.
//
// If swap is true, the start and end key/boundary are swapped (this is provided
// just for convenience, to avoid having two branches in every caller).
func (c *indexConstraintCtx) singleSpan(
offset int,
start constraint.Key,
startBoundary constraint.SpanBoundary,
end constraint.Key,
endBoundary constraint.SpanBoundary,
swap bool,
out *constraint.Constraint,
) {
var span constraint.Span
if !swap {
span.Init(start, startBoundary, end, endBoundary)
} else {
span.Init(end, endBoundary, start, startBoundary)
}
keyCtx := &c.keyCtx[offset]
span.PreferInclusive(keyCtx)
out.InitSingleSpan(keyCtx, &span)
}
// eqSpan returns a span that constrains a column to a single value (which
// can be DNull).
func (c *indexConstraintCtx) eqSpan(offset int, value tree.Datum, out *constraint.Constraint) {
var span constraint.Span
key := constraint.MakeKey(value)
span.Init(key, includeBoundary, key, includeBoundary)
out.InitSingleSpan(&c.keyCtx[offset], &span)
}
func (c *indexConstraintCtx) notNullStartKey(offset int) (constraint.Key, constraint.SpanBoundary) {
if !c.isNullable(offset) {
return emptyKey, includeBoundary
}
return constraint.MakeKey(tree.DNull), excludeBoundary
}
// makeNotNullSpan returns a span that constrains the column to non-NULL values.
// If the column is not nullable, returns a full span.
func (c *indexConstraintCtx) makeNotNullSpan(offset int, out *constraint.Constraint) {
if !c.isNullable(offset) {
// The column is not nullable; not-null constraints aren't useful.
c.unconstrained(offset, out)
return
}
c.singleSpan(
offset,
constraint.MakeKey(tree.DNull), excludeBoundary,
emptyKey, includeBoundary,
c.columns[offset].Descending(),
out,
)
}
// makeStringPrefixSpan returns a span that constrains string column <offset>
// to strings having the given prefix.
func (c *indexConstraintCtx) makeStringPrefixSpan(
offset int, prefix string, out *constraint.Constraint,
) {
startKey, startBoundary := constraint.MakeKey(tree.NewDString(prefix)), includeBoundary
endKey, endBoundary := emptyKey, includeBoundary
i := len(prefix) - 1
for ; i >= 0 && prefix[i] == 0xFF; i-- {
}
// If i < 0, we have a prefix like "\xff\xff\xff"; there is no ending value.
if i >= 0 {
// A few examples:
// prefix -> endValue
// ABC -> ABD
// ABC\xff -> ABD
// ABC\xff\xff -> ABD
endVal := []byte(prefix[:i+1])
endVal[i]++
endDatum := tree.NewDString(string(endVal))
endKey = constraint.MakeKey(endDatum)
endBoundary = excludeBoundary
}
c.singleSpan(
offset,
startKey, startBoundary, endKey, endBoundary,
c.columns[offset].Descending(),
out,
)
}
// verifyType checks that the type of the index column <offset> matches the
// given type. We disallow mixed-type comparisons because it would result in
// incorrect encodings (#4313).
func (c *indexConstraintCtx) verifyType(offset int, typ *types.T) bool {
return typ.Family() == types.UnknownFamily || c.colType(offset).Equivalent(typ)
}
// makeSpansForSingleColumn creates spans for a single index column from a
// simple comparison expression. The arguments are the operator and right
// operand. The <tight> return value indicates if the spans are exactly
// equivalent to the expression (and not weaker).
func (c *indexConstraintCtx) makeSpansForSingleColumn(
offset int, op opt.Operator, val opt.Expr, out *constraint.Constraint,
) (tight bool) {
if op == opt.InOp && memo.CanExtractConstTuple(val) {
tupVal := val.(*memo.TupleExpr)
keyCtx := &c.keyCtx[offset]
var spans constraint.Spans
spans.Alloc(len(tupVal.Elems))
for _, child := range tupVal.Elems {
datum := memo.ExtractConstDatum(child)
if !c.verifyType(offset, datum.ResolvedType()) {
c.unconstrained(offset, out)
return false
}
if datum == tree.DNull {
// Ignore NULLs - they can't match any values
continue
}
var sp constraint.Span
sp.Init(
constraint.MakeKey(datum), includeBoundary,
constraint.MakeKey(datum), includeBoundary,
)
spans.Append(&sp)
}
if c.columns[offset].Descending() {
// Reverse the order of the spans.
for i, j := 0, spans.Count()-1; i < j; i, j = i+1, j-1 {
si, sj := spans.Get(i), spans.Get(j)
*si, *sj = *sj, *si
}
}
spans.SortAndMerge(keyCtx)
out.Init(keyCtx, &spans)
return true
}
if opt.IsConstValueOp(val) {
return c.makeSpansForSingleColumnDatum(offset, op, memo.ExtractConstDatum(val), out)
}
c.unconstrained(offset, out)
return false
}
// makeSpansForSingleColumnDatum creates spans for a single index column from a
// simple comparison expression with a constant value on the right-hand side.
func (c *indexConstraintCtx) makeSpansForSingleColumnDatum(
offset int, op opt.Operator, datum tree.Datum, out *constraint.Constraint,
) (tight bool) {
if !c.verifyType(offset, datum.ResolvedType()) {
c.unconstrained(offset, out)
return false
}
if datum == tree.DNull {
switch op {
case opt.EqOp, opt.LtOp, opt.GtOp, opt.LeOp, opt.GeOp, opt.NeOp:
// The result of this expression is always NULL. Normally, this expression
// should have been converted to NULL during type checking; but if the
// NULL is coming from a placeholder, that doesn't happen.
c.contradiction(offset, out)
return true
case opt.IsOp:
if !c.isNullable(offset) {
// The column is not nullable; IS NULL is always false.
c.contradiction(offset, out)
return true
}
c.eqSpan(offset, tree.DNull, out)
return true
case opt.IsNotOp:
c.makeNotNullSpan(offset, out)
return true
}
c.unconstrained(offset, out)
return false
}
switch op {
case opt.EqOp, opt.IsOp:
c.eqSpan(offset, datum, out)
return true
case opt.LtOp, opt.GtOp, opt.LeOp, opt.GeOp:
startKey, startBoundary := c.notNullStartKey(offset)
endKey, endBoundary := emptyKey, includeBoundary
k := constraint.MakeKey(datum)
switch op {
case opt.LtOp:
endKey, endBoundary = k, excludeBoundary
case opt.LeOp:
endKey, endBoundary = k, includeBoundary
case opt.GtOp:
startKey, startBoundary = k, excludeBoundary
case opt.GeOp:
startKey, startBoundary = k, includeBoundary
}
c.singleSpan(
offset, startKey, startBoundary, endKey, endBoundary,
c.columns[offset].Descending(),
out,
)
return true
case opt.NeOp, opt.IsNotOp:
// Build constraint that doesn't contain the key:
// if nullable or IsNotOp : [ - key) (key - ]
// if not nullable and NeOp : (/NULL - key) (key - ]
//
// If the key is the minimum possible value for the column type, the span
// (/NULL - key) will never contain any values and can be omitted. The span
// [ - key) is similar if the column is not nullable.
//
// Similarly, if the key is the maximum possible value, the span (key - ]
// can be omitted.
startKey, startBoundary := emptyKey, includeBoundary
if op == opt.NeOp {
startKey, startBoundary = c.notNullStartKey(offset)
}
key := constraint.MakeKey(datum)
descending := c.columns[offset].Descending()
if !(startKey.IsEmpty() && c.isNullable(offset)) && datum.IsMin(c.evalCtx) {
// Omit the (/NULL - key) span by setting a contradiction, so that the
// UnionWith call below will result in just the second span.
c.contradiction(offset, out)
} else {
c.singleSpan(offset, startKey, startBoundary, key, excludeBoundary, descending, out)
}
if !datum.IsMax(c.evalCtx) {
var other constraint.Constraint
c.singleSpan(offset, key, excludeBoundary, emptyKey, includeBoundary, descending, &other)
out.UnionWith(c.evalCtx, &other)
}
return true
case opt.LikeOp:
if s, ok := tree.AsDString(datum); ok {
if i := strings.IndexAny(string(s), "_%"); i >= 0 {
if i == 0 {
// Mask starts with _ or %.
c.unconstrained(offset, out)
return false
}
c.makeStringPrefixSpan(offset, string(s[:i]), out)
// A mask like ABC% is equivalent to restricting the prefix to ABC.
// A mask like ABC%Z requires restricting the prefix, but is a stronger
// condition.
return (i == len(s)-1) && s[i] == '%'
}
// No wildcard characters, this is an equality.
c.eqSpan(offset, &s, out)
return true
}
case opt.SimilarToOp:
// a SIMILAR TO 'foo_*' -> prefix "foo"
if s, ok := tree.AsDString(datum); ok {
pattern := tree.SimilarEscape(string(s))
if re, err := regexp.Compile(pattern); err == nil {
prefix, complete := re.LiteralPrefix()
if complete {
c.eqSpan(offset, tree.NewDString(prefix), out)
return true
}
c.makeStringPrefixSpan(offset, prefix, out)
return false
}
}
}
c.unconstrained(offset, out)
return false
}
// makeSpansForTupleInequality creates spans for index columns starting at
// <offset> from a tuple inequality.
// Assumes that ev.Operator() is an inequality and both sides are tuples.
// The <tight> return value indicates if the spans are exactly equivalent
// to the expression (and not weaker).
func (c *indexConstraintCtx) makeSpansForTupleInequality(
offset int, e opt.Expr, out *constraint.Constraint,
) (tight bool) {
lhs, rhs := e.Child(0).(*memo.TupleExpr), e.Child(1).(*memo.TupleExpr)
// Find the longest prefix of the tuple that maps to index columns (with the
// same direction) starting at <offset>.
prefixLen := 0
descending := c.columns[offset].Descending()
nullVal := false
for i, leftChild := range lhs.Elems {
rightChild := rhs.Elems[i]
if !(offset+i < len(c.columns) && c.isIndexColumn(leftChild, offset+i)) {
// Variable doesn't refer to the column of interest.
break
}
if !opt.IsConstValueOp(rightChild) {
// Right-hand value is not a constant.
break
}
if !c.verifyType(offset+i, rightChild.DataType()) {
// We have a mixed-type comparison; we can't encode this in a span
// (see #4313).
break
}
if rightChild.Op() == opt.NullOp {
// NULLs are tricky and require special handling; see
// nullVal related code below.
nullVal = true
break
}
if c.columns[offset+i].Descending() != descending && e.Op() != opt.NeOp {
// The direction changed. For example:
// a ASCENDING, b DESCENDING, c ASCENDING
// (a, b, c) >= (1, 2, 3)
// We can only use a >= 1 here.
//
// TODO(radu): we could support inequalities for cases like this by
// allowing negation, for example:
// (a, -b, c) >= (1, -2, 3)
//
// The != operator is an exception where the column directions don't
// matter. For example, for (a, b, c) != (1, 2, 3) the spans
// [ - /1/2/2], [1/2/4 - ] apply for any combination of directions.
break
}
prefixLen++
}
if prefixLen == 0 {
c.unconstrained(offset, out)
return false
}
datums := make(tree.Datums, prefixLen)
for i := range datums {
datums[i] = memo.ExtractConstDatum(rhs.Elems[i])
}
// less is true if the op is < or <= and false if the op is > or >=.
// boundary is inclusive if the op is <= or >= and exclusive if the op
// is < or >.
var less bool
var boundary constraint.SpanBoundary
switch e.Op() {
case opt.NeOp:
if prefixLen < len(lhs.Elems) {
// If we have (a, b, c) != (1, 2, 3), we cannot
// determine any constraint on (a, b).
c.unconstrained(offset, out)
return false
}
key := constraint.MakeCompositeKey(datums...)
c.singleSpan(offset, emptyKey, includeBoundary, key, excludeBoundary, false /* swap */, out)
var other constraint.Constraint
c.singleSpan(offset, key, excludeBoundary, emptyKey, includeBoundary, false /* swap */, &other)
out.UnionWith(c.evalCtx, &other)
// If any columns are nullable, the spans could include unwanted NULLs.
// For example, for
// (@1, @2, @3) != (1, 2, 3)
// we need to exclude tuples like
// (1, NULL, NULL)
// (NULL, 2, 3)
//
// But note that some tuples with NULLs can satisfy the condition, e.g.
// (5, NULL, NULL)
// (NULL, 5, 5)
tight = true
for i := 0; i < prefixLen; i++ {
if c.isNullable(offset + i) {
tight = false
break
}
}
return tight
case opt.LtOp:
less, boundary = true, excludeBoundary
case opt.LeOp:
less, boundary = true, includeBoundary
case opt.GtOp:
less, boundary = false, excludeBoundary
case opt.GeOp:
less, boundary = false, includeBoundary
default:
panic(errors.AssertionFailedf("unsupported op %s", errors.Safe(e.Op())))
}
// The spans are "tight" unless we used just a prefix.
tight = (prefixLen == len(lhs.Elems))
if nullVal {
// NULL is treated semantically as "unknown value", so
// (1, 2) > (1, NULL) is NULL,
// but
// (2, 2) > (1, NULL) is true.
//
// So either of these constraints:
// (a, b) > (1, NULL)
// (a, b) >= (1, NULL)
// is true if and only if a > 1.
boundary = excludeBoundary
tight = true
} else if !tight {
// If we only keep a prefix, exclusive inequalities become inclusive.
// For example:
// (a, b, c) > (1, 2, 3) becomes (a, b) >= (1, 2)
boundary = includeBoundary
}
// We use notNullStartKey to disallow NULLs on the first column.
startKey, startBoundary := c.notNullStartKey(offset)
endKey, endBoundary := emptyKey, includeBoundary
if less {
endKey, endBoundary = constraint.MakeCompositeKey(datums...), boundary
} else {
startKey, startBoundary = constraint.MakeCompositeKey(datums...), boundary
}
// Consider (a, b, c) <= (1, 2, 3).
//
// If the columns are not null, the condition is equivalent to
// the span [ - /1/2/3].
//
// If column a is nullable, the condition is equivalent to the
// span (/NULL - /1/2/3].
//
// However, if column b or c is nullable, we still have to filter
// out the NULLs on those columns, so whatever span we generate is
// not "tight". For example, the span (/NULL - /1/2/3] can contain
// (1, NULL, NULL) which is not <= (1, 2, 3).
// TODO(radu): we could generate multiple spans:
// (/NULL - /0], (/1/NULL - /1/1], (/1/2/NULL, /1/2/3]
//
// If the condition is > or >= this is not a problem. For example
// (a, b, c) >= (1, 2, 3) has the span [/1/2/3 - ] which excludes
// any values of the form (1, NULL, x) or (1, 2, NULL). Other values
// with NULLs like (2, NULL, NULL) are ok because
// (2, NULL, NULL) >= (1, 2, 3).
// Note that if the direction is descending, the handling of < and > flips.
if tight && (less != descending) {
for i := 1; i < prefixLen; i++ {
if c.isNullable(offset + i) {
tight = false
break
}
}
}
c.singleSpan(offset, startKey, startBoundary, endKey, endBoundary, descending, out)
return tight
}
// makeSpansForTupleIn creates spans for index columns starting at
// <offset> from a tuple IN tuple expression, for example:
// (a, b, c) IN ((1, 2, 3), (4, 5, 6))
// Assumes that both sides are tuples.
// The <tight> return value indicates if the spans are exactly equivalent
// to the expression (and not weaker).
func (c *indexConstraintCtx) makeSpansForTupleIn(
offset int, e opt.Expr, out *constraint.Constraint,
) (tight bool) {
lhs, rhs := e.Child(0).(*memo.TupleExpr), e.Child(1).(*memo.TupleExpr)
// Find the longest prefix of columns starting at <offset> which is contained
// in the left-hand tuple; tuplePos[i] is the position of column <offset+i> in
// the tuple.
var tuplePos []int
for i := offset; i < len(c.columns); i++ {
found := false
for j, child := range lhs.Elems {
if c.isIndexColumn(child, i) {
tuplePos = append(tuplePos, j)
found = true
break
}
}
if !found {
break
}
}
if len(tuplePos) == 0 {
c.unconstrained(offset, out)
return false
}
// Create a span for each (tuple) value inside the right-hand side tuple.
keyCtx := &c.keyCtx[offset]
var spans constraint.Spans
var sp constraint.Span
spans.Alloc(len(rhs.Elems))
for _, child := range rhs.Elems {
valTuple, ok := child.(*memo.TupleExpr)
if !ok {
c.unconstrained(offset, out)
return false
}
vals := make(tree.Datums, len(tuplePos))
for i, pos := range tuplePos {
val := valTuple.Elems[pos]
if !opt.IsConstValueOp(val) {
c.unconstrained(offset, out)
return false
}
datum := memo.ExtractConstDatum(val)
if !c.verifyType(offset+i, datum.ResolvedType()) {
c.unconstrained(offset, out)
return false
}
vals[i] = datum
}
containsNull := false
for _, d := range vals {
containsNull = containsNull || (d == tree.DNull)
}
// If the tuple contains a NULL, ignore it (it can't match any values).
if !containsNull {
key := constraint.MakeCompositeKey(vals...)
sp.Init(key, includeBoundary, key, includeBoundary)
spans.Append(&sp)
}
}
// Sort and de-duplicate the values.
// We don't rely on the sorted order of the right-hand side tuple because it's
// only useful if all of the following are met:
// - we use all columns in the tuple, i.e. len(tuplePos) = lhs.ChildCount().
// - the columns are in the right order, i.e. tuplePos[i] = i.
// - the columns have the same directions
// Note that SortAndMerge exits quickly if the ordering is already correct.
spans.SortAndMerge(keyCtx)
out.Init(keyCtx, &spans)
// The spans are "tight" unless we used just a prefix.
return len(tuplePos) == len(lhs.Elems)
}
// makeSpansForExpr creates spans for index columns starting at <offset>
// from the given expression.
//
// The <tight> return value indicates if the spans are exactly equivalent to the
// expression (and not weaker). See simplifyFilter for more information.
func (c *indexConstraintCtx) makeSpansForExpr(
offset int, e opt.Expr, out *constraint.Constraint,
) (tight bool) {
if opt.IsConstValueOp(e) {
datum := memo.ExtractConstDatum(e)
if datum == tree.DBoolFalse || datum == tree.DNull {
// Condition is never true.
c.contradiction(offset, out)
return true
}
c.unconstrained(offset, out)
return datum == tree.DBoolTrue
}
switch t := e.(type) {
case *memo.FiltersExpr:
switch len(*t) {
case 0:
c.unconstrained(offset, out)
return true
case 1:
return c.makeSpansForExpr(offset, (*t)[0].Condition, out)
default:
return c.makeSpansForAnd(offset, t, out)
}
case *memo.FiltersItem:
// Pass through the call.
return c.makeSpansForExpr(offset, t.Condition, out)
case *memo.AndExpr:
return c.makeSpansForAnd(offset, t, out)
case *memo.OrExpr:
return c.makeSpansForOr(offset, t, out)
case *memo.VariableExpr:
// Support (@1) as (@1 = TRUE) if @1 is boolean.
if c.colType(offset).Family() == types.BoolFamily && c.isIndexColumn(t, offset) {
return c.makeSpansForSingleColumnDatum(offset, opt.EqOp, tree.DBoolTrue, out)
}
case *memo.NotExpr:
// Support (NOT @1) as (@1 = FALSE) if @1 is boolean.
if c.colType(offset).Family() == types.BoolFamily && c.isIndexColumn(t.Input, offset) {
return c.makeSpansForSingleColumnDatum(offset, opt.EqOp, tree.DBoolFalse, out)
}
case *memo.RangeExpr:
return c.makeSpansForExpr(offset, t.And, out)
}
if e.ChildCount() < 2 {
c.unconstrained(offset, out)
return false
}
child0, child1 := e.Child(0), e.Child(1)
// Check for an operation where the left-hand side is an
// indexed var for this column.
if c.isIndexColumn(child0, offset) {
tight := c.makeSpansForSingleColumn(offset, e.Op(), child1, out)
if !out.IsUnconstrained() || tight {
return tight
}
// We couldn't get any constraints for the column; see if we can at least
// deduce a not-NULL constraint.
if c.isNullable(offset) && opt.BoolOperatorRequiresNotNullArgs(e.Op()) {
c.makeNotNullSpan(offset, out)
return false
}
}
// Check for tuple operations.
if child0.Op() == opt.TupleOp && child1.Op() == opt.TupleOp {
switch e.Op() {
case opt.LtOp, opt.LeOp, opt.GtOp, opt.GeOp, opt.NeOp:
// Tuple inequality.
return c.makeSpansForTupleInequality(offset, e, out)
case opt.InOp:
// Tuple IN tuple.
return c.makeSpansForTupleIn(offset, e, out)
}
}
// Last resort: for conditions like a > b, our column can appear on the right
// side. We can deduce a not-null constraint from such conditions.
if c.isNullable(offset) && c.isIndexColumn(child1, offset) &&
opt.BoolOperatorRequiresNotNullArgs(e.Op()) {
c.makeNotNullSpan(offset, out)
return false
}
c.unconstrained(offset, out)
return false
}
// makeSpansForAnd calculates spans for an AndOp or FiltersOp.
func (c *indexConstraintCtx) makeSpansForAnd(
offset int, e opt.Expr, out *constraint.Constraint,
) (tight bool) {
// We need to handle both FiltersExpr and AndExpr. In FiltersExpr, we already
// have a list of conjuncts. But AndExpr is a binary operator so we may have
// nested Ands; we collect all the conjuncts in this case.
//
// Note that the common case is Filters; we only see And when it is part of a
// larger filter (e.g. an Or).
var filters memo.FiltersExpr
if f, ok := e.(*memo.FiltersExpr); ok {
filters = *f
} else {
filters = make(memo.FiltersExpr, 0, 2)
var collectConjunctions func(e opt.ScalarExpr)
collectConjunctions = func(e opt.ScalarExpr) {
if and, ok := e.(*memo.AndExpr); ok {
collectConjunctions(and.Left)
collectConjunctions(and.Right)
} else {
filters = append(filters, memo.FiltersItem{Condition: e})
}
}
collectConjunctions(e.(*memo.AndExpr))
}
// tightDeltaMap maps each filter to the relative index column offset at which
// we generated tight constraints for that expression (if any).
// Note that it is not possible for a given condition to generate tight
// constraints at different column offsets.
var tightDeltaMap util.FastIntMap
// TODO(radu): sorting the expressions by the variable index, or pre-building
// a map could help here.
tight = c.makeSpansForExpr(offset, filters[0].Condition, out)
if tight {
tightDeltaMap.Set(0, 0)
}
var exprConstraint constraint.Constraint
for i := 1; i < len(filters); i++ {
filterTight := c.makeSpansForExpr(offset, filters[i].Condition, &exprConstraint)
if filterTight {
tightDeltaMap.Set(i, 0)
}
tight = tight && filterTight
out.IntersectWith(c.evalCtx, &exprConstraint)
}
if out.IsUnconstrained() {
return tight
}
if tight {
return true
}
// Now we try to refine the result with constraints on suffixes of the index
// columns (i.e. higher offsets).
// TODO(radu): we should be able to get the constraints for all offsets in a
// single traversal of the subtree.
var ofsC constraint.Constraint
for delta := 0; ; {
// In each iteration, we try to extend keys with constraints for the offset
// that corresponds to where the key ends. We can skip offsets at which no
// keys end.
// To calculate this, we get the minimum length of any key that doesn't end
// at or after the current offset.
minLen := len(c.columns)
for j := 0; j < out.Spans.Count(); j++ {
sp := out.Spans.Get(j)
l := sp.StartKey().Length()
if l > delta && minLen > l {
minLen = l
}
l = sp.EndKey().Length()
if l > delta && minLen > l {
minLen = l
}
}
delta = minLen
if offset+delta >= len(c.columns) {
break
}
tight := c.makeSpansForExpr(offset+delta, filters[0].Condition, &ofsC)
if tight {
tightDeltaMap.Set(0, delta)
}
for j := 1; j < len(filters); j++ {
tight := c.makeSpansForExpr(offset+delta, filters[j].Condition, &exprConstraint)
if tight {
tightDeltaMap.Set(j, delta)
}
ofsC.IntersectWith(c.evalCtx, &exprConstraint)
}
out.Combine(c.evalCtx, &ofsC)
}
// It's hard in the most general case to determine if the constraints are
// tight. But we can cover a lot of cases using the following sufficient
// condition:
// - let `prefix` be the longest prefix of columns for which all spans have the
// same start and end value (see Constraint.Prefix).
// - every filter must have generated tight spans for a set of columns
// starting at an offset that is at most `prefix`.
//
// This is because the Combine call above can only keep the constraints tight
// if it is "appending" to single-value spans.
prefix := out.Prefix(c.evalCtx)
for i := range filters {
delta, ok := tightDeltaMap.Get(i)
if !ok || delta > prefix {
return false
}
}
return true
}
// makeSpansForOr calculates spans for an OrOp.
func (c *indexConstraintCtx) makeSpansForOr(
offset int, e opt.Expr, out *constraint.Constraint,
) (tight bool) {
or := e.(*memo.OrExpr)
tightLeft := c.makeSpansForExpr(offset, or.Left, out)
if out.IsUnconstrained() {
// If spans can't be generated for the left child, exit early.
c.unconstrained(offset, out)
return false
}
var rightConstraint constraint.Constraint
tightRight := c.makeSpansForExpr(offset, or.Right, &rightConstraint)
out.UnionWith(c.evalCtx, &rightConstraint)
// The OR is "tight" if both constraints were tight.
return tightLeft && tightRight
}
// makeInvertedIndexSpansForJSONContainmentExpr is the implementation of
// makeInvertedIndexSpans for JSON inverted indexes. The input datum is the JSON
// to produce spans for. If allPaths is true, the slice is populated with
// all constraints found. Otherwise, this function stops at the first
// constraint.
func (c *indexConstraintCtx) makeInvertedIndexSpansForJSONContainmentExpr(
datum *tree.DJSON, constraints []*constraint.Constraint, allPaths bool,
) (bool, []*constraint.Constraint) {
out := &constraint.Constraint{}
constrained := false
rd := datum.JSON
switch rd.Type() {
case json.ArrayJSONType, json.ObjectJSONType:
// First, check if there's more than one path through the datum.
paths, err := json.AllPaths(rd)
if err != nil {
log.Errorf(context.TODO(), "unexpected JSON error: %+v", err)
c.unconstrained(0 /* offset */, out)
return false, append(constraints, out)
}
for i := range paths {
hasContainerLeaf, err := paths[i].HasContainerLeaf()
if err != nil {
log.Errorf(context.TODO(), "unexpected JSON error: %+v", err)
c.unconstrained(0 /* offset */, out)
return false, append(constraints, out)
}
if hasContainerLeaf {
// We want to have a full index scan if the RHS contains either [] or {}.
continue
}
pathDatum, err := tree.MakeDJSON(paths[i])
if err != nil {
log.Errorf(context.TODO(), "unexpected JSON error: %+v", err)
c.unconstrained(0 /* offset */, out)
return false, append(constraints, out)
}
c.eqSpan(0 /* offset */, pathDatum, out)
constraints = append(constraints, out)
// The span is tight if we just had 1 path through the index constraint.
constrained = true
if !allPaths {
return len(paths) == 1, constraints
}
// Reset out for next iteration
out = &constraint.Constraint{}
}
// We found no paths that could constrain the scan.
if !constrained {
c.unconstrained(0 /* offset */, out)
return false, append(constraints, out)
}
return len(paths) == 1, constraints
default:
// If we find a scalar on the right side of the @> operator it means that we need to find
// both matching scalars and arrays that contain that value. In order to do this we generate
// two logical spans, one for the original scalar and one for arrays containing the scalar.
// This is valid because in JSON something can either be an array or scalar so the spans are
// guaranteed not to overlap when mapped onto the primary key space. Therefore there won't be
// any duplicate primary keys when we retrieve rows for both sets.
j := json.NewArrayBuilder(1)
j.Add(rd)
dJSON, err := tree.MakeDJSON(j.Build())
if err != nil {
break
}
// This is the span for the scalar.
c.eqSpan(0 /* offset */, datum, out)
// This is the span to match arrays.
var other constraint.Constraint
c.eqSpan(0 /* offset */, dJSON, &other)
out.UnionWith(c.evalCtx, &other)
return true, append(constraints, out)
}
// Just assume that we didn't find any constraints if we ran into an error.
return false, constraints
}
// makeInvertedIndexSpansForArrayContainmentExpr is the implementation of
// makeInvertedIndexSpans for array inverted indexes. The input arr is the array
// to produce spans for. If allPaths is true, the slice is populated with
// all constraints found. Otherwise, this function stops at the first
// constraint.
func (c *indexConstraintCtx) makeInvertedIndexSpansForArrayContainmentExpr(
arr *tree.DArray, constraints []*constraint.Constraint, allPaths bool,
) (bool, []*constraint.Constraint) {
if len(arr.Array) == 0 {
// Arrays always contain the empty array.
out := &constraint.Constraint{}
c.unconstrained(0 /* offset */, out)
return false, append(constraints, out)
}
if arr.HasNulls {
out := &constraint.Constraint{}
// In SQL, testing an array that contains NULL for containment within
// another array always returns false, so if we see a null in the array
// we're producing spans for, we have a contradiction.
c.contradiction(0 /* offset */, out)
return false, append(constraints, out)
}
// We're going to make one span to search for every value inside of the
// array datum.
for i := range arr.Array {
out := &constraint.Constraint{}
if arr.Array[i] == tree.DNull {
// This shouldn't ever happen - it means that arr.HasNulls was
// incorrectly set to false... but we'll be good citizens and make a
// contradiction here anyway, just in case.
c.contradiction(0 /* offset */, out)
return false, append(constraints, out)
}
array := tree.NewDArray(arr.ParamTyp)
array.Array = make(tree.Datums, 1)
array.Array[0] = arr.Array[i]
c.eqSpan(0 /* offset */, array, out)
constraints = append(constraints, out)
if !allPaths {
// The span is tight if we just had 1 path through the index constraint.
break
}
}
return len(arr.Array) == 1, constraints
}
// makeInvertedIndexSpanForJSONFetchValEqExpr attempts to create an inverted
// index scan for filters of the form json->'key' = 'value'. An inverted index
// constraint is only generated when all of the following are true:
//
// 1. The fetch column is an index column.
//
// 2. The fetch key (RHS of ->) is a constant string. This is required because
// we build a JSON object that is used as the boundaries of the span. An
// integer fetch key fetches a value at an index in a JSON array, not a
// JSON object.
//
// 3. The RHS of the equality operator is a constant, scalar JSON value.
// Supporting non-scalar JSON values would require the filter to be
// re-applied to the JSON column after scanning the index. As an example of
// what would happen without re-applying the filter, a row with column j as
// {"a": [1, 2]} would be incorrectly returned from the query filter
// j->'a' = '[1]'.
//
func (c *indexConstraintCtx) makeInvertedIndexSpanForJSONFetchValEqExpr(
fetch *memo.FetchValExpr, rhs opt.Expr, constraints []*constraint.Constraint,
) (bool, []*constraint.Constraint) {
appendUnconstrained := func() []*constraint.Constraint {
out := &constraint.Constraint{}
c.unconstrained(0 /* offset */, out)
return append(constraints, out)
}
if !c.isIndexColumn(fetch.Json, 0 /* index */) {
return false, appendUnconstrained()
}
keyConst, ok := fetch.Index.(*memo.ConstExpr)
if !ok {
return false, appendUnconstrained()
}
key, ok := keyConst.Value.(*tree.DString)
if !ok {
return false, appendUnconstrained()
}
rightConst := rhs.(*memo.ConstExpr)
if !ok {
return false, appendUnconstrained()
}