-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcustom_funcs.go
2747 lines (2472 loc) · 93.1 KB
/
custom_funcs.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 norm
import (
"fmt"
"math"
"sort"
"github.com/cockroachdb/apd"
"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/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/arith"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
// CustomFuncs contains all the custom match and replace functions used by
// the normalization rules. These are also imported and used by the explorer.
type CustomFuncs struct {
f *Factory
mem *memo.Memo
}
// Init initializes a new CustomFuncs with the given factory.
func (c *CustomFuncs) Init(f *Factory) {
c.f = f
c.mem = f.Memo()
}
// Succeeded returns true if a result expression is not nil.
func (c *CustomFuncs) Succeeded(result opt.Expr) bool {
return result != nil
}
// OrderingSucceeded returns true if an OrderingChoice is not nil.
func (c *CustomFuncs) OrderingSucceeded(result *physical.OrderingChoice) bool {
return result != nil
}
// DerefOrderingChoice returns an OrderingChoice from a pointer.
func (c *CustomFuncs) DerefOrderingChoice(result *physical.OrderingChoice) physical.OrderingChoice {
return *result
}
// MakeIntConst constructs a Const holding a DInt.
func (c *CustomFuncs) MakeIntConst(d *tree.DInt) opt.ScalarExpr {
return c.f.ConstructConst(d, types.Int)
}
// ----------------------------------------------------------------------
//
// ScalarList functions
// General custom match and replace functions used to test and construct
// scalar lists.
//
// ----------------------------------------------------------------------
// NeedSortedUniqueList returns true if the given list is composed entirely of
// constant values that are either not in sorted order or have duplicates. If
// true, then ConstructSortedUniqueList needs to be called on the list to
// normalize it.
func (c *CustomFuncs) NeedSortedUniqueList(list memo.ScalarListExpr) bool {
if len(list) <= 1 {
return false
}
ls := listSorter{cf: c, list: list}
var needSortedUniqueList bool
for i, item := range list {
if !opt.IsConstValueOp(item) {
return false
}
if i != 0 && !ls.less(i-1, i) {
needSortedUniqueList = true
}
}
return needSortedUniqueList
}
// ConstructSortedUniqueList sorts the given list and removes duplicates, and
// returns the resulting list. See the comment for listSorter.compare for
// comparison rule details.
func (c *CustomFuncs) ConstructSortedUniqueList(
list memo.ScalarListExpr,
) (memo.ScalarListExpr, *types.T) {
// Make a copy of the list, since it needs to stay immutable.
newList := make(memo.ScalarListExpr, len(list))
copy(newList, list)
ls := listSorter{cf: c, list: newList}
// Sort the list.
sort.Slice(ls.list, ls.less)
// Remove duplicates from the list.
n := 0
for i := range newList {
if i == 0 || ls.compare(i-1, i) < 0 {
newList[n] = newList[i]
n++
}
}
newList = newList[:n]
// Construct the type of the tuple.
contents := make([]*types.T, n)
for i := range newList {
contents[i] = newList[i].DataType()
}
return newList, types.MakeTuple(contents)
}
// ----------------------------------------------------------------------
//
// Typing functions
// General custom match and replace functions used to test and construct
// expression data types.
//
// ----------------------------------------------------------------------
// HasColType returns true if the given scalar expression has a static type
// that's identical to the requested coltype.
func (c *CustomFuncs) HasColType(scalar opt.ScalarExpr, dstTyp *types.T) bool {
return scalar.DataType().Identical(dstTyp)
}
// IsString returns true if the given scalar expression is of type String.
func (c *CustomFuncs) IsString(scalar opt.ScalarExpr) bool {
return scalar.DataType().Family() == types.StringFamily
}
// BoolType returns the boolean SQL type.
func (c *CustomFuncs) BoolType() *types.T {
return types.Bool
}
// AnyType returns the wildcard Any type.
func (c *CustomFuncs) AnyType() *types.T {
return types.Any
}
// CanConstructBinary returns true if (op left right) has a valid binary op
// overload and is therefore legal to construct. For example, while
// (Minus <date> <int>) is valid, (Minus <int> <date>) is not.
func (c *CustomFuncs) CanConstructBinary(op opt.Operator, left, right opt.ScalarExpr) bool {
return memo.BinaryOverloadExists(op, left.DataType(), right.DataType())
}
// ArrayType returns the type of the given column wrapped
// in an array.
func (c *CustomFuncs) ArrayType(inCol opt.ColumnID) *types.T {
inTyp := c.mem.Metadata().ColumnMeta(inCol).Type
return types.MakeArray(inTyp)
}
// BinaryType returns the type of the binary overload for the given operator and
// operands.
func (c *CustomFuncs) BinaryType(op opt.Operator, left, right opt.ScalarExpr) *types.T {
o, _ := memo.FindBinaryOverload(op, left.DataType(), right.DataType())
return o.ReturnType
}
// TypeOf returns the type of the expression.
func (c *CustomFuncs) TypeOf(e opt.ScalarExpr) *types.T {
return e.DataType()
}
// ----------------------------------------------------------------------
//
// Property functions
// General custom match and replace functions used to test expression
// logical properties.
//
// ----------------------------------------------------------------------
// OutputCols returns the set of columns returned by the input expression.
func (c *CustomFuncs) OutputCols(input memo.RelExpr) opt.ColSet {
return input.Relational().OutputCols
}
// OutputCols2 returns the union of columns returned by the left and right
// expressions.
func (c *CustomFuncs) OutputCols2(left, right memo.RelExpr) opt.ColSet {
return left.Relational().OutputCols.Union(right.Relational().OutputCols)
}
// NotNullCols returns the set of columns returned by the input expression that
// are guaranteed to never be NULL.
func (c *CustomFuncs) NotNullCols(input memo.RelExpr) opt.ColSet {
return input.Relational().NotNullCols
}
// CandidateKey returns the candidate key columns from the given input
// expression. If there is no candidate key, CandidateKey returns ok=false.
func (c *CustomFuncs) CandidateKey(input memo.RelExpr) (key opt.ColSet, ok bool) {
return input.Relational().FuncDeps.StrictKey()
}
// IsColNotNull returns true if the given input column is never null.
func (c *CustomFuncs) IsColNotNull(col opt.ColumnID, input memo.RelExpr) bool {
return input.Relational().NotNullCols.Contains(col)
}
// IsColNotNull2 returns true if the given column is part of the left or right
// expressions' set of not-null columns.
func (c *CustomFuncs) IsColNotNull2(col opt.ColumnID, left, right memo.RelExpr) bool {
return left.Relational().NotNullCols.Contains(col) ||
right.Relational().NotNullCols.Contains(col)
}
// OuterCols returns the set of outer columns associated with the given
// expression, whether it be a relational or scalar operator.
func (c *CustomFuncs) OuterCols(e opt.Expr) opt.ColSet {
return c.sharedProps(e).OuterCols
}
// HasOuterCols returns true if the input expression has at least one outer
// column, or in other words, a reference to a variable that is not bound within
// its own scope. For example:
//
// SELECT * FROM a WHERE EXISTS(SELECT * FROM b WHERE b.x = a.x)
//
// The a.x variable in the EXISTS subquery references a column outside the scope
// of the subquery. It is an "outer column" for the subquery (see the comment on
// RelationalProps.OuterCols for more details).
func (c *CustomFuncs) HasOuterCols(input opt.Expr) bool {
return !c.OuterCols(input).Empty()
}
// IsBoundBy returns true if all outer references in the source expression are
// bound by the given columns. For example:
//
// (InnerJoin
// (Scan a)
// (Scan b)
// [ ... $item:(FiltersItem (Eq (Variable a.x) (Const 1))) ... ]
// )
//
// The $item expression is fully bound by the output columns of the (Scan a)
// expression because all of its outer references are satisfied by the columns
// produced by the Scan.
func (c *CustomFuncs) IsBoundBy(src opt.Expr, cols opt.ColSet) bool {
return c.OuterCols(src).SubsetOf(cols)
}
// IsDeterminedBy returns true if all outer references in the source expression
// are bound by the closure of the given columns according to the functional
// dependencies of the input expression.
func (c *CustomFuncs) IsDeterminedBy(src opt.Expr, cols opt.ColSet, input memo.RelExpr) bool {
return input.Relational().FuncDeps.InClosureOf(c.OuterCols(src), cols)
}
// IsCorrelated returns true if any variable in the source expression references
// a column from the destination expression. For example:
// (InnerJoin
// (Scan a)
// (Scan b)
// [ ... (FiltersItem $item:(Eq (Variable a.x) (Const 1))) ... ]
// )
//
// The $item expression is correlated with the (Scan a) expression because it
// references one of its columns. But the $item expression is not correlated
// with the (Scan b) expression.
func (c *CustomFuncs) IsCorrelated(src, dst memo.RelExpr) bool {
return src.Relational().OuterCols.Intersects(dst.Relational().OutputCols)
}
// HasNoCols returns true if the input expression has zero output columns.
func (c *CustomFuncs) HasNoCols(input memo.RelExpr) bool {
return input.Relational().OutputCols.Empty()
}
// HasOneCol returns true if the input expression has exactly one output column.
func (c *CustomFuncs) HasOneCol(input memo.RelExpr) bool {
return input.Relational().OutputCols.Len() == 1
}
// HasZeroRows returns true if the input expression never returns any rows.
func (c *CustomFuncs) HasZeroRows(input memo.RelExpr) bool {
return input.Relational().Cardinality.IsZero()
}
// HasOneRow returns true if the input expression always returns exactly one
// row.
func (c *CustomFuncs) HasOneRow(input memo.RelExpr) bool {
return input.Relational().Cardinality.IsOne()
}
// HasZeroOrOneRow returns true if the input expression returns at most one row.
func (c *CustomFuncs) HasZeroOrOneRow(input memo.RelExpr) bool {
return input.Relational().Cardinality.IsZeroOrOne()
}
// CanHaveZeroRows returns true if the input expression might return zero rows.
func (c *CustomFuncs) CanHaveZeroRows(input memo.RelExpr) bool {
return input.Relational().Cardinality.CanBeZero()
}
// HasStrictKey returns true if the input expression has one or more columns
// that form a strict key (see comment for ColsAreStrictKey for definition).
func (c *CustomFuncs) HasStrictKey(input memo.RelExpr) bool {
inputFDs := &input.Relational().FuncDeps
_, hasKey := inputFDs.StrictKey()
return hasKey
}
// ColsAreStrictKey returns true if the given columns form a strict key for the
// given input expression. A strict key means that any two rows will have unique
// key column values. Nulls are treated as equal to one another (i.e. no
// duplicate nulls allowed). Having a strict key means that the set of key
// column values uniquely determine the values of all other columns in the
// relation.
func (c *CustomFuncs) ColsAreStrictKey(cols opt.ColSet, input memo.RelExpr) bool {
return input.Relational().FuncDeps.ColsAreStrictKey(cols)
}
// ColsAreConst returns true if the given columns have the same values for all
// rows in the given input expression.
func (c *CustomFuncs) ColsAreConst(cols opt.ColSet, input memo.RelExpr) bool {
return cols.SubsetOf(input.Relational().FuncDeps.ConstantCols())
}
// ColsAreEmpty returns true if the column set is empty.
func (c *CustomFuncs) ColsAreEmpty(cols opt.ColSet) bool {
return cols.Empty()
}
// ColsAreSubset returns true if the left columns are a subset of the right
// columns.
func (c *CustomFuncs) ColsAreSubset(left, right opt.ColSet) bool {
return left.SubsetOf(right)
}
// ColsAreEqual returns true if left and right contain the same set of columns.
func (c *CustomFuncs) ColsAreEqual(left, right opt.ColSet) bool {
return left.Equals(right)
}
// ColsIntersect returns true if at least one column appears in both the left
// and right sets.
func (c *CustomFuncs) ColsIntersect(left, right opt.ColSet) bool {
return left.Intersects(right)
}
// IntersectionCols returns the intersection of the left and right column sets.
func (c *CustomFuncs) IntersectionCols(left, right opt.ColSet) opt.ColSet {
return left.Intersection(right)
}
// UnionCols returns the union of the left and right column sets.
func (c *CustomFuncs) UnionCols(left, right opt.ColSet) opt.ColSet {
return left.Union(right)
}
// UnionCols3 returns the union of the three column sets.
func (c *CustomFuncs) UnionCols3(cols1, cols2, cols3 opt.ColSet) opt.ColSet {
cols := cols1.Union(cols2)
cols.UnionWith(cols3)
return cols
}
// UnionCols4 returns the union of the four column sets.
func (c *CustomFuncs) UnionCols4(cols1, cols2, cols3, cols4 opt.ColSet) opt.ColSet {
cols := cols1.Union(cols2)
cols.UnionWith(cols3)
cols.UnionWith(cols4)
return cols
}
// DifferenceCols returns the difference of the left and right column sets.
func (c *CustomFuncs) DifferenceCols(left, right opt.ColSet) opt.ColSet {
return left.Difference(right)
}
// AddColToSet returns a set containing both the given set and the given column.
func (c *CustomFuncs) AddColToSet(set opt.ColSet, col opt.ColumnID) opt.ColSet {
if set.Contains(col) {
return set
}
newSet := set.Copy()
newSet.Add(col)
return newSet
}
// SingleColFromSet returns the single column in s. Panics if s does not contain
// exactly one column.
func (c *CustomFuncs) SingleColFromSet(s opt.ColSet) opt.ColumnID {
return s.SingleColumn()
}
// sharedProps returns the shared logical properties for the given expression.
// Only relational expressions and certain scalar list items (e.g. FiltersItem,
// ProjectionsItem, AggregationsItem) have shared properties.
func (c *CustomFuncs) sharedProps(e opt.Expr) *props.Shared {
switch t := e.(type) {
case memo.RelExpr:
return &t.Relational().Shared
case memo.ScalarPropsExpr:
return &t.ScalarProps().Shared
default:
var p props.Shared
memo.BuildSharedProps(e, &p)
return &p
}
}
// MutationTable returns the table upon which the mutation is applied.
func (c *CustomFuncs) MutationTable(private *memo.MutationPrivate) opt.TableID {
return private.Table
}
// PrimaryKeyCols returns the key columns of the primary key of the table.
func (c *CustomFuncs) PrimaryKeyCols(table opt.TableID) opt.ColSet {
tabMeta := c.mem.Metadata().TableMeta(table)
return tabMeta.IndexKeyColumns(cat.PrimaryIndex)
}
// RedundantCols returns the subset of the given columns that are functionally
// determined by the remaining columns. In many contexts (such as if they are
// grouping columns), these columns can be dropped. The input expression's
// functional dependencies are used to make the decision.
func (c *CustomFuncs) RedundantCols(input memo.RelExpr, cols opt.ColSet) opt.ColSet {
reducedCols := input.Relational().FuncDeps.ReduceCols(cols)
if reducedCols.Equals(cols) {
return opt.ColSet{}
}
return cols.Difference(reducedCols)
}
// ----------------------------------------------------------------------
//
// Ordering functions
// General custom match and replace functions related to orderings.
//
// ----------------------------------------------------------------------
// HasColsInOrdering returns true if all columns that appear in an ordering are
// output columns of the input expression.
func (c *CustomFuncs) HasColsInOrdering(input memo.RelExpr, ordering physical.OrderingChoice) bool {
return ordering.CanProjectCols(input.Relational().OutputCols)
}
// OrderingCols returns all non-optional columns that are part of the given
// OrderingChoice.
func (c *CustomFuncs) OrderingCols(ordering physical.OrderingChoice) opt.ColSet {
return ordering.ColSet()
}
// PruneOrdering removes any columns referenced by an OrderingChoice that are
// not part of the needed column set. Should only be called if HasColsInOrdering
// is true.
func (c *CustomFuncs) PruneOrdering(
ordering physical.OrderingChoice, needed opt.ColSet,
) physical.OrderingChoice {
if ordering.SubsetOfCols(needed) {
return ordering
}
ordCopy := ordering.Copy()
ordCopy.ProjectCols(needed)
return ordCopy
}
// EmptyOrdering returns a pseudo-choice that does not require any
// ordering.
func (c *CustomFuncs) EmptyOrdering() physical.OrderingChoice {
return physical.OrderingChoice{}
}
// OrderingIntersects returns true if <ordering1> and <ordering2> have an
// intersection. See OrderingChoice.Intersection for more information.
func (c *CustomFuncs) OrderingIntersects(ordering1, ordering2 physical.OrderingChoice) bool {
return ordering1.Intersects(&ordering2)
}
// OrderingIntersection returns the intersection of two orderings. Should only be
// called if it is known that an intersection exists.
// See OrderingChoice.Intersection for more information.
func (c *CustomFuncs) OrderingIntersection(
ordering1, ordering2 physical.OrderingChoice,
) physical.OrderingChoice {
return ordering1.Intersection(&ordering2)
}
// MakeSegmentedOrdering returns an ordering choice which satisfies both
// limitOrdering and the ordering required by a window function. Returns nil if
// no such ordering exists. See OrderingChoice.PrefixIntersection for more
// details.
func (c *CustomFuncs) MakeSegmentedOrdering(
input memo.RelExpr,
prefix opt.ColSet,
ordering physical.OrderingChoice,
limitOrdering physical.OrderingChoice,
) *physical.OrderingChoice {
// The columns in the closure of the prefix may be included in it. It's
// beneficial to do so for a given column iff that column appears in the
// limit's ordering.
cl := input.Relational().FuncDeps.ComputeClosure(prefix)
cl.IntersectionWith(limitOrdering.ColSet())
cl.UnionWith(prefix)
prefix = cl
oc, ok := limitOrdering.PrefixIntersection(prefix, ordering.Columns)
if !ok {
return nil
}
return &oc
}
// AllArePrefixSafe returns whether every window function in the list satisfies
// the "prefix-safe" property.
//
// Being prefix-safe means that the computation of a window function on a given
// row does not depend on any of the rows that come after it. It's also
// precisely the property that lets us push limit operators below window
// functions:
//
// (Limit (Window $input) n) = (Window (Limit $input n))
//
// Note that the frame affects whether a given window function is prefix-safe or not.
// rank() is prefix-safe under any frame, but avg():
// * is not prefix-safe under RANGE BETWEEN UNBOUNDED PRECEDING TO CURRENT ROW
// (the default), because we might cut off mid-peer group. If we can
// guarantee that the ordering is over a key, then this becomes safe.
// * is not prefix-safe under ROWS BETWEEN UNBOUNDED PRECEDING TO UNBOUNDED
// FOLLOWING, because it needs to look at the entire partition.
// * is prefix-safe under ROWS BETWEEN UNBOUNDED PRECEDING TO CURRENT ROW,
// because it only needs to look at the rows up to any given row.
// (We don't currently handle this case).
//
// This function is best-effort. It's OK to report a function not as
// prefix-safe, even if it is.
func (c *CustomFuncs) AllArePrefixSafe(fns memo.WindowsExpr) bool {
for i := range fns {
if !c.isPrefixSafe(&fns[i]) {
return false
}
}
return true
}
// isPrefixSafe returns whether or not the given window function satisfies the
// "prefix-safe" property. See the comment above AllArePrefixSafe for more
// details.
func (c *CustomFuncs) isPrefixSafe(fn *memo.WindowsItem) bool {
switch fn.Function.Op() {
case opt.RankOp, opt.RowNumberOp, opt.DenseRankOp:
return true
}
// TODO(justin): Add other cases. I think aggregates are valid here if the
// upper bound is CURRENT ROW, and either:
// * the mode is ROWS, or
// * the mode is RANGE and the ordering is over a key.
return false
}
// OrdinalityOrdering returns an ordinality operator's ordering choice.
func (c *CustomFuncs) OrdinalityOrdering(private *memo.OrdinalityPrivate) physical.OrderingChoice {
return private.Ordering
}
// -----------------------------------------------------------------------
//
// Filter functions
// General custom match and replace functions used to test and construct
// filters in Select and Join rules.
//
// -----------------------------------------------------------------------
// FilterOuterCols returns the union of all outer columns from the given filter
// conditions.
func (c *CustomFuncs) FilterOuterCols(filters memo.FiltersExpr) opt.ColSet {
var colSet opt.ColSet
for i := range filters {
colSet.UnionWith(filters[i].ScalarProps().OuterCols)
}
return colSet
}
// FilterHasCorrelatedSubquery returns true if any of the filter conditions
// contain a correlated subquery.
func (c *CustomFuncs) FilterHasCorrelatedSubquery(filters memo.FiltersExpr) bool {
for i := range filters {
if filters[i].ScalarProps().HasCorrelatedSubquery {
return true
}
}
return false
}
// IsFilterFalse returns true if the filters always evaluate to false. The only
// case that's checked is the fully normalized case, when the list contains a
// single False condition.
func (c *CustomFuncs) IsFilterFalse(filters memo.FiltersExpr) bool {
return filters.IsFalse()
}
// IsContradiction returns true if the given filter item contains a
// contradiction constraint.
func (c *CustomFuncs) IsContradiction(item *memo.FiltersItem) bool {
return item.ScalarProps().Constraints == constraint.Contradiction
}
// ConcatFilters creates a new Filters operator that contains conditions from
// both the left and right boolean filter expressions.
func (c *CustomFuncs) ConcatFilters(left, right memo.FiltersExpr) memo.FiltersExpr {
// No need to recompute properties on the new filters, since they should
// still be valid.
newFilters := make(memo.FiltersExpr, len(left)+len(right))
copy(newFilters, left)
copy(newFilters[len(left):], right)
return newFilters
}
// RemoveFiltersItem returns a new list that is a copy of the given list, except
// that it does not contain the given search item. If the list contains the item
// multiple times, then only the first instance is removed. If the list does not
// contain the item, then the method panics.
func (c *CustomFuncs) RemoveFiltersItem(
filters memo.FiltersExpr, search *memo.FiltersItem,
) memo.FiltersExpr {
newFilters := make(memo.FiltersExpr, len(filters)-1)
for i := range filters {
if search == &filters[i] {
copy(newFilters, filters[:i])
copy(newFilters[i:], filters[i+1:])
return newFilters
}
}
panic(errors.AssertionFailedf("item to remove is not in the list: %v", search))
}
// ReplaceFiltersItem returns a new list that is a copy of the given list,
// except that the given search item has been replaced by the given replace
// item. If the list contains the search item multiple times, then only the
// first instance is replaced. If the list does not contain the item, then the
// method panics.
func (c *CustomFuncs) ReplaceFiltersItem(
filters memo.FiltersExpr, search *memo.FiltersItem, replace opt.ScalarExpr,
) memo.FiltersExpr {
newFilters := make([]memo.FiltersItem, len(filters))
for i := range filters {
if search == &filters[i] {
copy(newFilters, filters[:i])
newFilters[i] = c.f.ConstructFiltersItem(replace)
copy(newFilters[i+1:], filters[i+1:])
return newFilters
}
}
panic(errors.AssertionFailedf("item to replace is not in the list: %v", search))
}
// FiltersBoundBy returns true if all outer references in any of the filter
// conditions are bound by the given columns. For example:
//
// (InnerJoin
// (Scan a)
// (Scan b)
// $filters:[ (FiltersItem (Eq (Variable a.x) (Const 1))) ]
// )
//
// The $filters expression is fully bound by the output columns of the (Scan a)
// expression because all of its outer references are satisfied by the columns
// produced by the Scan.
func (c *CustomFuncs) FiltersBoundBy(filters memo.FiltersExpr, cols opt.ColSet) bool {
for i := range filters {
if !filters[i].ScalarProps().OuterCols.SubsetOf(cols) {
return false
}
}
return true
}
// ExtractBoundConditions returns a new list containing only those expressions
// from the given list that are fully bound by the given columns (i.e. all
// outer references are to one of these columns). For example:
//
// (InnerJoin
// (Scan a)
// (Scan b)
// (Filters [
// (Eq (Variable a.x) (Variable b.x))
// (Gt (Variable a.x) (Const 1))
// ])
// )
//
// Calling ExtractBoundConditions with the filter conditions list and the output
// columns of (Scan a) would extract the (Gt) expression, since its outer
// references only reference columns from a.
func (c *CustomFuncs) ExtractBoundConditions(
filters memo.FiltersExpr, cols opt.ColSet,
) memo.FiltersExpr {
newFilters := make(memo.FiltersExpr, 0, len(filters))
for i := range filters {
if c.IsBoundBy(&filters[i], cols) {
newFilters = append(newFilters, filters[i])
}
}
return newFilters
}
// ExtractUnboundConditions is the opposite of ExtractBoundConditions. Instead of
// extracting expressions that are bound by the given columns, it extracts
// list expressions that have at least one outer reference that is *not* bound
// by the given columns (i.e. it has a "free" variable).
func (c *CustomFuncs) ExtractUnboundConditions(
filters memo.FiltersExpr, cols opt.ColSet,
) memo.FiltersExpr {
newFilters := make(memo.FiltersExpr, 0, len(filters))
for i := range filters {
if !c.IsBoundBy(&filters[i], cols) {
newFilters = append(newFilters, filters[i])
}
}
return newFilters
}
// ExtractDeterminedConditions returns a new list of filters containing only
// those expressions from the given list which are bound by columns which
// are functionally determined by the given columns.
func (c *CustomFuncs) ExtractDeterminedConditions(
filters memo.FiltersExpr, cols opt.ColSet, input memo.RelExpr,
) memo.FiltersExpr {
newFilters := make(memo.FiltersExpr, 0, len(filters))
for i := range filters {
if c.IsDeterminedBy(&filters[i], cols, input) {
newFilters = append(newFilters, filters[i])
}
}
return newFilters
}
// ExtractUndeterminedConditions is the opposite of
// ExtractDeterminedConditions.
func (c *CustomFuncs) ExtractUndeterminedConditions(
filters memo.FiltersExpr, cols opt.ColSet, input memo.RelExpr,
) memo.FiltersExpr {
newFilters := make(memo.FiltersExpr, 0, len(filters))
for i := range filters {
if !c.IsDeterminedBy(&filters[i], cols, input) {
newFilters = append(newFilters, filters[i])
}
}
return newFilters
}
// CanConsolidateFilters returns true if there are at least two different
// filter conditions that contain the same variable, where the conditions
// have tight constraints and contain a single variable. For example,
// CanConsolidateFilters returns true with filters {x > 5, x < 10}, but false
// with {x > 5, y < 10} and {x > 5, x = y}.
func (c *CustomFuncs) CanConsolidateFilters(filters memo.FiltersExpr) bool {
var seen opt.ColSet
for i := range filters {
if col, ok := c.canConsolidateFilter(&filters[i]); ok {
if seen.Contains(col) {
return true
}
seen.Add(col)
}
}
return false
}
// canConsolidateFilter determines whether a filter condition can be
// consolidated. Filters can be consolidated if they have tight constraints
// and contain a single variable. Examples of such filters include x < 5 and
// x IS NULL. If the filter can be consolidated, canConsolidateFilter returns
// the column ID of the variable and ok=true. Otherwise, canConsolidateFilter
// returns ok=false.
func (c *CustomFuncs) canConsolidateFilter(filter *memo.FiltersItem) (col opt.ColumnID, ok bool) {
if !filter.ScalarProps().TightConstraints {
return 0, false
}
outerCols := c.OuterCols(filter)
if outerCols.Len() != 1 {
return 0, false
}
col, _ = outerCols.Next(0)
return col, true
}
// ConsolidateFilters consolidates filter conditions that contain the same
// variable, where the conditions have tight constraints and contain a single
// variable. The consolidated filters are combined with a tree of nested
// And operations, and wrapped with a Range expression.
//
// See the ConsolidateSelectFilters rule for more details about why this is
// necessary.
func (c *CustomFuncs) ConsolidateFilters(filters memo.FiltersExpr) memo.FiltersExpr {
// First find the columns that have filter conditions that can be
// consolidated.
var seen, seenTwice opt.ColSet
for i := range filters {
if col, ok := c.canConsolidateFilter(&filters[i]); ok {
if seen.Contains(col) {
seenTwice.Add(col)
} else {
seen.Add(col)
}
}
}
newFilters := make(memo.FiltersExpr, seenTwice.Len(), len(filters)-seenTwice.Len())
// newFilters contains an empty item for each of the new Range expressions
// that will be created below. Fill in rangeMap to track which column
// corresponds to each item.
var rangeMap util.FastIntMap
i := 0
for col, ok := seenTwice.Next(0); ok; col, ok = seenTwice.Next(col + 1) {
rangeMap.Set(int(col), i)
i++
}
// Iterate through each existing filter condition, and either consolidate it
// into one of the new Range expressions or add it unchanged to the new
// filters.
for i := range filters {
if col, ok := c.canConsolidateFilter(&filters[i]); ok && seenTwice.Contains(col) {
// This is one of the filter conditions that can be consolidated into a
// Range.
cond := filters[i].Condition
switch t := cond.(type) {
case *memo.RangeExpr:
// If it is already a range expression, unwrap it.
cond = t.And
}
rangeIdx, _ := rangeMap.Get(int(col))
rangeItem := &newFilters[rangeIdx]
if rangeItem.Condition == nil {
// This is the first condition.
rangeItem.Condition = cond
} else {
// Build a left-deep tree of ANDs sorted by ID.
rangeItem.Condition = c.mergeSortedAnds(rangeItem.Condition, cond)
}
} else {
newFilters = append(newFilters, filters[i])
}
}
// Construct each of the new Range operators now that we have built the
// conjunctions.
for i, n := 0, seenTwice.Len(); i < n; i++ {
newFilters[i] = c.f.ConstructFiltersItem(c.f.ConstructRange(newFilters[i].Condition))
}
return newFilters
}
// mergeSortedAnds merges two left-deep trees of nested AndExprs sorted by ID.
// Returns a single sorted, left-deep tree of nested AndExprs, with any
// duplicate expressions eliminated.
func (c *CustomFuncs) mergeSortedAnds(left, right opt.ScalarExpr) opt.ScalarExpr {
if right == nil {
return left
}
if left == nil {
return right
}
// Since both trees are left-deep, perform a merge-sort from right to left.
nextLeft := left
nextRight := right
var remainingLeft, remainingRight opt.ScalarExpr
if and, ok := left.(*memo.AndExpr); ok {
remainingLeft = and.Left
nextLeft = and.Right
}
if and, ok := right.(*memo.AndExpr); ok {
remainingRight = and.Left
nextRight = and.Right
}
if nextLeft.ID() == nextRight.ID() {
// Eliminate duplicates.
return c.mergeSortedAnds(left, remainingRight)
}
if nextLeft.ID() < nextRight.ID() {
return c.f.ConstructAnd(c.mergeSortedAnds(left, remainingRight), nextRight)
}
return c.f.ConstructAnd(c.mergeSortedAnds(remainingLeft, right), nextLeft)
}
// AreFiltersSorted determines whether the expressions in a FiltersExpr are
// ordered by their expression IDs.
func (c *CustomFuncs) AreFiltersSorted(f memo.FiltersExpr) bool {
for i, n := 0, f.ChildCount(); i < n-1; i++ {
if f.Child(i).Child(0).(opt.ScalarExpr).ID() > f.Child(i+1).Child(0).(opt.ScalarExpr).ID() {
return false
}
}
return true
}
// SortFilters sorts a filter list by the IDs of the expressions. This has the
// effect of canonicalizing FiltersExprs which may have the same filters, but
// in a different order.
func (c *CustomFuncs) SortFilters(f memo.FiltersExpr) memo.FiltersExpr {
result := make(memo.FiltersExpr, len(f))
for i, n := 0, f.ChildCount(); i < n; i++ {
fi := f.Child(i).(*memo.FiltersItem)
result[i] = *fi
}
result.Sort()
return result
}
func (c *CustomFuncs) extractVarEqualsConst(
e opt.Expr,
) (ok bool, left *memo.VariableExpr, right *memo.ConstExpr) {
if eq, ok := e.(*memo.EqExpr); ok {
if l, ok := eq.Left.(*memo.VariableExpr); ok {
if r, ok := eq.Right.(*memo.ConstExpr); ok {
return true, l, r
}
}
}
return false, nil, nil
}
// CanInlineConstVar returns true if there is an opportunity in the filters to
// inline a variable restricted to be a constant, as in:
// SELECT * FROM foo WHERE a = 4 AND a IN (1, 2, 3, 4).
// =>
// SELECT * FROM foo WHERE a = 4 AND 4 IN (1, 2, 3, 4).
func (c *CustomFuncs) CanInlineConstVar(f memo.FiltersExpr) bool {
// usedIndices tracks the set of filter indices we've used to infer constant
// values, so we don't inline into them.
var usedIndices util.FastIntSet
// fixedCols is the set of columns that the filters restrict to be a constant
// value.
var fixedCols opt.ColSet
for i := range f {
if ok, l, _ := c.extractVarEqualsConst(f[i].Condition); ok {
colType := c.mem.Metadata().ColumnMeta(l.Col).Type
if sqlbase.DatumTypeHasCompositeKeyEncoding(colType) {
// TODO(justin): allow inlining if the check we're doing is oblivious
// to composite-ness.
continue
}
if !fixedCols.Contains(l.Col) {
fixedCols.Add(l.Col)
usedIndices.Add(i)
}
}
}
for i := range f {
if usedIndices.Contains(i) {
continue
}
if f[i].ScalarProps().OuterCols.Intersects(fixedCols) {
return true
}
}
return false
}
// InlineConstVar performs the inlining detected by CanInlineConstVar.
func (c *CustomFuncs) InlineConstVar(f memo.FiltersExpr) memo.FiltersExpr {
// usedIndices tracks the set of filter indices we've used to infer constant
// values, so we don't inline into them.
var usedIndices util.FastIntSet
// fixedCols is the set of columns that the filters restrict to be a constant
// value.
var fixedCols opt.ColSet
// vals maps columns which are restricted to be constant to the value they
// are restricted to.
vals := make(map[opt.ColumnID]opt.ScalarExpr)
for i := range f {
if ok, v, e := c.extractVarEqualsConst(f[i].Condition); ok {
colType := c.mem.Metadata().ColumnMeta(v.Col).Type
if sqlbase.DatumTypeHasCompositeKeyEncoding(colType) {
continue
}
if _, ok := vals[v.Col]; !ok {
vals[v.Col] = e
fixedCols.Add(v.Col)
usedIndices.Add(i)
}
}