-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCExpressionPreprocessor.cpp
More file actions
3541 lines (3115 loc) · 114 KB
/
Copy pathCExpressionPreprocessor.cpp
File metadata and controls
3541 lines (3115 loc) · 114 KB
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
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright 2012 EMC Corp.
//
// @filename:
// CExpressionPreprocessor.cpp
//
// @doc:
// Expression tree preprocessing routines, needed to prepare an input
// logical expression to be optimized
//---------------------------------------------------------------------------
#include "gpopt/operators/CExpressionPreprocessor.h"
#include "gpos/base.h"
#include "gpos/common/CAutoRef.h"
#include "gpos/common/CAutoTimer.h"
#include "gpopt/base/CCastUtils.h"
#include "gpopt/base/CColRefSetIter.h"
#include "gpopt/base/CColRefTable.h"
#include "gpopt/base/CConstraintInterval.h"
#include "gpopt/base/COptCtxt.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/exception.h"
#include "gpopt/mdcache/CMDAccessor.h"
#include "gpopt/operators/CExpressionFactorizer.h"
#include "gpopt/operators/CExpressionUtils.h"
#include "gpopt/operators/CLeftJoinPruningPreprocessor.h"
#include "gpopt/operators/CLogicalCTEAnchor.h"
#include "gpopt/operators/CLogicalCTEConsumer.h"
#include "gpopt/operators/CLogicalCTEProducer.h"
#include "gpopt/operators/CLogicalConstTableGet.h"
#include "gpopt/operators/CLogicalDynamicGet.h"
#include "gpopt/operators/CLogicalGbAgg.h"
#include "gpopt/operators/CLogicalInnerJoin.h"
#include "gpopt/operators/CLogicalLimit.h"
#include "gpopt/operators/CLogicalNAryJoin.h"
#include "gpopt/operators/CLogicalProject.h"
#include "gpopt/operators/CLogicalSelect.h"
#include "gpopt/operators/CLogicalSequenceProject.h"
#include "gpopt/operators/CLogicalSetOp.h"
#include "gpopt/operators/CLogicalUnion.h"
#include "gpopt/operators/CLogicalUnionAll.h"
#include "gpopt/operators/CLogicalUpdate.h"
#include "gpopt/operators/CNormalizer.h"
#include "gpopt/operators/COrderedAggPreprocessor.h"
#include "gpopt/operators/CPredicateUtils.h"
#include "gpopt/operators/CScalarCmp.h"
#include "gpopt/operators/CScalarNAryJoinPredList.h"
#include "gpopt/operators/CScalarProjectElement.h"
#include "gpopt/operators/CScalarProjectList.h"
#include "gpopt/operators/CScalarSubquery.h"
#include "gpopt/operators/CScalarSubqueryAny.h"
#include "gpopt/operators/CScalarSubqueryExists.h"
#include "gpopt/operators/CScalarSubqueryQuantified.h"
#include "gpopt/optimizer/COptimizerConfig.h"
#include "gpopt/translate/CTranslatorDXLToExpr.h"
#include "gpopt/xforms/CXform.h"
#include "naucrates/md/IMDScalarOp.h"
#include "naucrates/md/IMDType.h"
#include "naucrates/statistics/CStatistics.h"
#include "naucrates/traceflags/traceflags.h"
using namespace gpopt;
static void UpdateExprToConstantPredicateMapping(
CMemoryPool *mp, CExpression *pexprFilter,
ExprToConstantMap *phmExprToConst, BOOL doInsert);
static CExpression *SubstituteConstantIdentifier(
CMemoryPool *mp, CExpression *pexpr, ExprToConstantMap *phmExprToConst);
// maximum number of equality predicates to be derived from existing equalities
#define GPOPT_MAX_DERIVED_PREDS 50
// eliminate self comparisons in the given expression
CExpression *
CExpressionPreprocessor::PexprEliminateSelfComparison(CMemoryPool *mp,
CExpression *pexpr,
CColRefSet *pcrsNotNull)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
if (CUtils::FScalarCmp(pexpr))
{
return CPredicateUtils::PexprEliminateSelfComparison(mp, pexpr,
pcrsNotNull);
}
// Use current expr rather then the root to get not null columns
else if (pop->FLogical())
{
pcrsNotNull = pexpr->DeriveNotNullColumns();
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprEliminateSelfComparison(mp, (*pexpr)[ul], pcrsNotNull);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// remove superfluous equality operations
CExpression *
CExpressionPreprocessor::PexprPruneSuperfluousEquality(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
if (pexpr->Pop()->FScalar())
{
return CPredicateUtils::PexprPruneSuperfluosEquality(mp, pexpr);
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprPruneSuperfluousEquality(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
COperator *pop = pexpr->Pop();
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// an existential subquery whose inner expression is a GbAgg
// with no grouping columns is replaced with a Boolean constant
//
// Example:
//
// exists(select sum(i) from X) --> True
// not exists(select sum(i) from X) --> False
CExpression *
CExpressionPreprocessor::PexprTrimExistentialSubqueries(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
if (CUtils::FExistentialSubquery(pop))
{
CExpression *pexprInner = (*pexpr)[0];
if (COperator::EopLogicalGbAgg == pexprInner->Pop()->Eopid() &&
0 ==
CLogicalGbAgg::PopConvert(pexprInner->Pop())->Pdrgpcr()->Size())
{
GPOS_ASSERT(0 < (*pexprInner)[1]->Arity() &&
"Project list of GbAgg is expected to be non-empty");
BOOL fValue = true;
if (COperator::EopScalarSubqueryNotExists == pop->Eopid())
{
fValue = false;
}
return CUtils::PexprScalarConstBool(mp, fValue);
}
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprTrimExistentialSubqueries(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
if (CPredicateUtils::FAnd(pexpr))
{
return CPredicateUtils::PexprConjunction(mp, pdrgpexprChildren);
}
if (CPredicateUtils::FOr(pexpr))
{
return CPredicateUtils::PexprDisjunction(mp, pdrgpexprChildren);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// a quantified subquery with maxcard 1 is simplified as a scalar subquery
//
// Example:
// a = ANY (select sum(i) from X) --> a = (select sum(i) from X)
// a <> ALL (select sum(i) from X) --> a <> (select sum(i) from X)
CExpression *
CExpressionPreprocessor::PexprSimplifyQuantifiedSubqueries(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
if (CUtils::FQuantifiedSubquery(pop) &&
1 == (*pexpr)[0]->DeriveMaxCard().Ull())
{
CExpression *pexprInner = (*pexpr)[0];
// skip intermediate unary nodes
CExpression *pexprChild = pexprInner;
COperator *popChild = pexprChild->Pop();
while (nullptr != pexprChild && CUtils::FLogicalUnary(popChild))
{
pexprChild = (*pexprChild)[0];
popChild = pexprChild->Pop();
}
// inspect next node
BOOL fGbAggWithoutGrpCols =
COperator::EopLogicalGbAgg == popChild->Eopid() &&
0 == CLogicalGbAgg::PopConvert(popChild)->Pdrgpcr()->Size();
BOOL fOneRowConstTable =
COperator::EopLogicalConstTableGet == popChild->Eopid() &&
1 == CLogicalConstTableGet::PopConvert(popChild)
->Pdrgpdrgpdatum()
->Size();
if (fGbAggWithoutGrpCols || fOneRowConstTable)
{
// quantified subquery with max card 1
CExpression *pexprScalar = (*pexpr)[1];
CScalarSubqueryQuantified *popSubqQuantified =
CScalarSubqueryQuantified::PopConvert(pexpr->Pop());
const CColRef *colref = popSubqQuantified->Pcr();
pexprInner->AddRef();
CExpression *pexprSubquery = GPOS_NEW(mp) CExpression(
mp,
GPOS_NEW(mp)
CScalarSubquery(mp, colref, false /*fGeneratedByExist*/,
true /*fGeneratedByQuantified*/),
pexprInner);
CMDAccessor *md_accessor = COptCtxt::PoctxtFromTLS()->Pmda();
IMDId *mdid = popSubqQuantified->MdIdOp();
const CWStringConst *str =
md_accessor->RetrieveScOp(mdid)->Mdname().GetMDName();
mdid->AddRef();
pexprScalar->AddRef();
return CUtils::PexprScalarCmp(mp, pexprScalar, pexprSubquery, *str,
mdid);
}
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprSimplifyQuantifiedSubqueries(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// preliminary unnesting of scalar subqueries
// Example:
// Input: SELECT k, (SELECT (SELECT Y.i FROM Y WHERE Y.j=X.j)) from X
// Output: SELECT k, (SELECT Y.i FROM Y WHERE Y.j=X.j) from X
CExpression *
CExpressionPreprocessor::PexprUnnestScalarSubqueries(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
// look for a Project Element with a scalar subquery below it
if (CUtils::FProjElemWithScalarSubq(pexpr))
{
// recursively process scalar subquery
CExpression *pexprSubq = PexprUnnestScalarSubqueries(mp, (*pexpr)[0]);
// if the scalar subquery is replaced by the CScalarIdent in the previous
// recursive call we simply return the CScalarIdent and stop preprocessing
// at this stage.
// +--CScalarProjectList
// +--CScalarProjectElement "?column?" (2)
// +--CScalarIdent "column1" (1)
if (COperator::EopScalarIdent == pexprSubq->Pop()->Eopid())
{
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pexprSubq);
}
// check if subquery is defined as a Project on Const Table
CExpression *pexprSubqChild = (*pexprSubq)[0];
if (CUtils::FProjectConstTableWithOneScalarSubq(pexprSubqChild))
{
CExpression *pexprConstTable = (*pexprSubqChild)[0];
CExpression *pexprPrjList = (*pexprSubqChild)[1];
GPOS_ASSERT(1 == pexprPrjList->Arity());
CExpression *pexprPrjElem = (*pexprPrjList)[0];
CExpression *pexprInnerSubq = (*pexprPrjElem)[0];
GPOS_ASSERT(COperator::EopScalarSubquery ==
pexprInnerSubq->Pop()->Eopid());
// make sure that inner subquery has no outer references to Const Table
// since Const Table will be eliminated in output expression
CColRefSet *pcrsConstTableOutput =
pexprConstTable->DeriveOutputColumns();
CColRefSet *outer_refs =
(*pexprInnerSubq)[0]->DeriveOuterReferences();
if (0 == outer_refs->Size() ||
outer_refs->IsDisjoint(pcrsConstTableOutput))
{
// recursively process inner subquery
CExpression *pexprUnnestedSubq =
PexprUnnestScalarSubqueries(mp, pexprInnerSubq);
// the original subquery is processed and can be removed now
pexprSubq->Release();
// build the new Project Element after eliminating outer subquery
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pexprUnnestedSubq);
}
}
// otherwise, return a Project Element with the processed outer subquery
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pexprSubq);
}
else if (CUtils::FScalarSubqWithConstTblGet(pexpr))
{
const CColRef *pcrSubq =
CScalarSubquery::PopConvert(pexpr->Pop())->Pcr();
CColRefSet *pcrsConstTableOutput = (*pexpr)[0]->DeriveOutputColumns();
// if the subquery has outer ref, we do not make use of the output columns of constant table get.
// In this scenairo, we replace the entire scalar subquery with a CScalarIdent with the outer reference.
// Otherwise, the subquery remains unchanged.
// Input:
// +--CScalarSubquery["b" (8)]
// +--CLogicalConstTableGet Columns: ["" (16)] Values: [(1)]
// Output:
// +--CScalarIdent "b" (8)
if (!pcrsConstTableOutput->FMember(pcrSubq))
{
CScalarSubquery *pScalarSubquery =
CScalarSubquery::PopConvert(pexpr->Pop());
return CUtils::PexprScalarIdent(mp, pScalarSubquery->Pcr());
}
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild = PexprUnnestScalarSubqueries(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// an intermediate limit is removed if it has neither row count nor offset
CExpression *
CExpressionPreprocessor::PexprRemoveSuperfluousLimit(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
// if current operator is a logical limit with zero offset, no specified
// row count, AND no ORDER BY columns, skip to limit's logical child.
// A limit with ORDER BY but no count represents a subquery sort that
// an ancestor (e.g. outer LIMIT) may depend on, so we must keep it.
if (COperator::EopLogicalLimit == pop->Eopid() &&
CUtils::FHasZeroOffset(pexpr) &&
!CLogicalLimit::PopConvert(pop)->FHasCount())
{
CLogicalLimit *popLgLimit = CLogicalLimit::PopConvert(pop);
if (popLgLimit->Pos()->IsEmpty() &&
(!popLgLimit->IsTopLimitUnderDMLorCTAS() ||
(popLgLimit->IsTopLimitUnderDMLorCTAS() &&
GPOS_FTRACE(EopttraceRemoveOrderBelowDML))))
{
return PexprRemoveSuperfluousLimit(mp, (*pexpr)[0]);
}
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild = PexprRemoveSuperfluousLimit(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// distinct is removed from a DQA if it has a max or min agg
// e.g. select max(distinct(a)) from tbl -> select max(a) from tbl
CExpression *
CExpressionPreprocessor::PexprRemoveSuperfluousDistinctInDQA(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
if (COperator::EopLogicalGbAgg == pop->Eopid())
{
const CExpression *const pexprProjectList = (*pexpr)[1];
GPOS_ASSERT(COperator::EopScalarProjectList ==
pexprProjectList->Pop()->Eopid());
const ULONG arity = pexprProjectList->Arity();
CMDAccessor *md_accessor = COptCtxt::PoctxtFromTLS()->Pmda();
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *const pexprPrjElem = (*pexprProjectList)[ul];
if (COperator::EopScalarAggFunc ==
(*pexprPrjElem)[0]->Pop()->Eopid())
{
CScalarAggFunc *popAggFunc =
CScalarAggFunc::PopConvert((*pexprPrjElem)[0]->Pop());
IMDId *agg_child_mdid =
CScalar::PopConvert((*pexprPrjElem)[0]->Pop())->MdidType();
const IMDType *agg_child_type =
md_accessor->RetrieveType(agg_child_mdid);
if (popAggFunc->IsDistinct() &&
popAggFunc->IsMinMax(agg_child_type))
{
popAggFunc->SetIsDistinct(false);
}
}
}
}
// recursively process children
const ULONG arity = pexpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprRemoveSuperfluousDistinctInDQA(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// Remove outer references from order spec inside limit, grouping columns
// in GbAgg, and Partition/Order columns in window operators. Also handle
// cases where we would end up with an empty groupby list and project list,
// which is not supported.
//
// Example, for the schema: t(a, b), s(i, j)
// The query:
// select * from t where a < all (select i from s order by j, b limit 1);
// should be equivalent to:
// select * from t where a < all (select i from s order by j limit 1);
// after removing the outer reference (b) from the order by clause of the
// subquery (all tuples in the subquery have the same value for the outer ref)
//
// Similarly,
// select * from t where a in (select count(i) from s group by j, b);
// is equivalent to:
// select * from t where a in (select count(i) from s group by j);
//
// Similarly,
// select * from t where a in (select row_number() over (partition by t.a order by t.b) from s);
// is equivalent to:
// select * from t where a in (select row_number() over () from s);
CExpression *
CExpressionPreprocessor::PexprRemoveSuperfluousOuterRefs(CMemoryPool *mp,
CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
// operator, possibly altered below if we need to change the operator
COperator *pop = pexpr->Pop();
// expression, possibly altered below if we need to change the children
CExpression *newExpr = pexpr;
COperator::EOperatorId op_id = pop->Eopid();
BOOL fHasOuterRefs = (pop->FLogical() && CUtils::HasOuterRefs(pexpr));
pop->AddRef();
if (fHasOuterRefs)
{
// special handling for three operator types: Limit, GrbyAgg, Sequence
if (COperator::EopLogicalLimit == op_id)
{
CColRefSet *outer_refs = pexpr->DeriveOuterReferences();
CLogicalLimit *popLimit = CLogicalLimit::PopConvert(pop);
COrderSpec *pos = popLimit->Pos();
COrderSpec *posNew = pos->PosExcludeColumns(mp, outer_refs);
pop->Release();
pop = GPOS_NEW(mp) CLogicalLimit(
mp, posNew, popLimit->FGlobal(), popLimit->FHasCount(),
popLimit->IsTopLimitUnderDMLorCTAS());
}
else if (COperator::EopLogicalGbAgg == op_id)
{
CColRefSet *outer_refs = pexpr->DeriveOuterReferences();
CLogicalGbAgg *popAgg = CLogicalGbAgg::PopConvert(pop);
CColRefArray *colref_array = CUtils::PdrgpcrExcludeColumns(
mp, popAgg->Pdrgpcr(), outer_refs);
CExpression *pExprProjList = (*pexpr)[1];
// It's only valid to remove the outer reference if:
// the projection list is NOT empty
// or
// the outer references are NOT the ONLY Group By column
//
// For example:
// -- Cannot remove t.b from groupby, because this will produce an invalid plan
// -- with both groupby list and project list empty, in this case we need to add
// -- a project node below the GrbyAgg
// select a from t where c in (select distinct t.b from s)
//
// -- remove t.b from groupby is ok, because there is at least one agg function: count()
// select a from t where c in (select count(s.j) from s group by t.b)
//
// -- remove t.b from groupby is ok, because there is other groupby column s.j
// select a from t where c in (select s.j from s group by t.b, s.j)
//
// -- remove t.b from groupby is ok, because outer reference is a
// -- constant for each invocation of subquery
// select a from t where c in (select count(s.j) from s group by s.i, t.b)
//
if (0 < pExprProjList->Arity() || 0 < colref_array->Size())
{
// remove outer refs from the groupby columns list
CColRefArray *pdrgpcrMinimal = popAgg->PdrgpcrMinimal();
if (nullptr != pdrgpcrMinimal)
{
pdrgpcrMinimal = CUtils::PdrgpcrExcludeColumns(
mp, pdrgpcrMinimal, outer_refs);
}
CColRefArray *pdrgpcrArgDQA = popAgg->PdrgpcrArgDQA();
if (nullptr != pdrgpcrArgDQA)
{
pdrgpcrArgDQA->AddRef();
}
pop->Release();
pop = GPOS_NEW(mp) CLogicalGbAgg(
mp, colref_array, pdrgpcrMinimal, popAgg->Egbaggtype(),
popAgg->FGeneratesDuplicates(), pdrgpcrArgDQA);
}
else
{
// grouping_cols has outer references that can't be removed, because
// that would make both pExprProjList and grouping_cols empty, which is not allowed.
// The solution in this case is to add a project node below that will simply echo
// the outer reference, and to use that newly produced ColRef as groupby column.
CExpression *child = (*pexpr)[0];
CExpressionArray *grouping_cols_arr =
CUtils::PdrgpexprScalarIdents(mp, popAgg->Pdrgpcr());
GPOS_ASSERT(0 < grouping_cols_arr->Size());
child->AddRef();
// add a project node on top of our child
CExpression *projectExpr = CUtils::PexprAddProjection(
mp, child, grouping_cols_arr,
false // don't add to hash table,
// this is done at the end
// of preprocessing
);
grouping_cols_arr->Release();
// build a children array for the new GrbyAgg expression
CExpressionArray *new_children =
GPOS_NEW(mp) CExpressionArray(mp);
new_children->Append(projectExpr);
for (ULONG ul = 1; ul < pexpr->PdrgPexpr()->Size(); ul++)
{
new_children->Append((*pexpr->PdrgPexpr())[ul]);
(*pexpr->PdrgPexpr())[ul]->AddRef();
}
// build a new CLogicalGbAgg operator, with a new grouping columns list
CColRefArray *new_grouping_cols = GPOS_NEW(mp) CColRefArray(mp);
CExpression *new_projected_cols = (*projectExpr)[1];
for (ULONG ul = 0; ul < new_projected_cols->Arity(); ul++)
{
new_grouping_cols->Append(
CUtils::PcrFromProjElem((*new_projected_cols)[ul]));
}
GPOS_ASSERT(nullptr == popAgg->PdrgpcrArgDQA());
pop = GPOS_NEW(mp) CLogicalGbAgg(mp, new_grouping_cols, nullptr,
popAgg->Egbaggtype(),
popAgg->FGeneratesDuplicates(),
nullptr // no DQA cols
);
// release the previous pop
popAgg->Release();
popAgg = nullptr;
// finally, put it all together, our new GrbyAgg now has a project node below
// it that will turn the outer reference into a produced ColRef that is used
// as a groupby column
pop->AddRef();
newExpr = GPOS_NEW(mp) CExpression(mp, pop, new_children);
// clean up
colref_array->Release();
}
}
else if (COperator::EopLogicalSequenceProject == op_id)
{
CExpressionHandle exprhdl(mp);
exprhdl.Attach(pexpr);
exprhdl.DeriveProps(nullptr /*pdpctxt*/);
CLogicalSequenceProject *popSequenceProject =
CLogicalSequenceProject::PopConvert(pop);
if (popSequenceProject->FHasLocalReferencesTo(
exprhdl.DeriveOuterReferences()))
{
COperator *popNew =
popSequenceProject->PopRemoveLocalOuterRefs(mp, exprhdl);
pop->Release();
pop = popNew;
}
}
}
// recursively process children
const ULONG arity = newExpr->Arity();
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild =
PexprRemoveSuperfluousOuterRefs(mp, (*newExpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
if (newExpr != pexpr)
{
newExpr->Release();
}
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// generate a ScalarBoolOp expression or simply return the only expression
// in the array if there is only one.
CExpression *
CExpressionPreprocessor::PexprScalarBoolOpConvert2In(
CMemoryPool *mp, CScalarBoolOp::EBoolOperator eboolop,
CExpressionArray *pdrgpexpr)
{
GPOS_ASSERT(nullptr != pdrgpexpr);
GPOS_ASSERT(0 < pdrgpexpr->Size());
if (1 == pdrgpexpr->Size())
{
// if there is one child, do not wrap it in a bool op
CExpression *pexpr = (*pdrgpexpr)[0];
pexpr->AddRef();
pdrgpexpr->Release();
return pexpr;
}
return GPOS_NEW(mp)
CExpression(mp, GPOS_NEW(mp) CScalarBoolOp(mp, eboolop), pdrgpexpr);
}
// checks if the given expression is likely to be simplified by the constraints
// framework during array conversion. eboolop is the CScalarBoolOp type
// of the expression which contains the argument expression
BOOL
CExpressionPreprocessor::FConvert2InIsConvertable(
CExpression *pexpr, CScalarBoolOp::EBoolOperator eboolopParent)
{
bool fConvertableExpression = false;
if (CPredicateUtils::FCompareIdentToConst(pexpr))
{
fConvertableExpression |=
IMDType::EcmptEq ==
CScalarCmp::PopConvert(pexpr->Pop())->ParseCmpType() &&
CScalarBoolOp::EboolopOr == eboolopParent;
fConvertableExpression |=
IMDType::EcmptNEq ==
CScalarCmp::PopConvert(pexpr->Pop())->ParseCmpType() &&
CScalarBoolOp::EboolopAnd == eboolopParent;
}
else if (CPredicateUtils::FCompareIdentToConstArray(pexpr) ||
CPredicateUtils::FCompareCastIdentToConstArray(pexpr))
{
fConvertableExpression = true;
}
if (fConvertableExpression)
{
GPOS_ASSERT(0 < pexpr->Arity());
CScalarIdent *pscid = nullptr;
if (CUtils::FScalarIdent((*pexpr)[0]))
{
pscid = CScalarIdent::PopConvert((*pexpr)[0]->Pop());
}
else
{
GPOS_ASSERT(CScalarIdent::FCastedScId((*pexpr)[0]));
pscid = CScalarIdent::PopConvert((*(*pexpr)[0])[0]->Pop());
}
if (!CUtils::FConstrainableType(pscid->MdidType()))
{
fConvertableExpression = false;
}
}
return fConvertableExpression;
}
// converts series of AND or OR comparisons into array IN expressions. For
// example, x = 1 OR x = 2 will convert to x IN (1,2). This stage assumes
// the expression has been unnested using CExpressionUtils::PexprUnnest.
CExpression *
CExpressionPreprocessor::PexprConvert2In(
CMemoryPool *mp,
CExpression *pexpr // does not take ownership
)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
if (CPredicateUtils::FOr(pexpr) || CPredicateUtils::FAnd(pexpr))
{
// the bool op type of this node
CScalarBoolOp::EBoolOperator eboolop =
CScalarBoolOp::PopConvert(pop)->Eboolop();
// derive constraints on all of the simple scalar children
// and add them to a new AND or OR expression
CExpressionArray *pdrgpexprCollapse = GPOS_NEW(mp) CExpressionArray(mp);
CExpressionArray *pdrgpexprRemainder =
GPOS_NEW(mp) CExpressionArray(mp);
const ULONG arity = pexpr->Arity();
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild = (*pexpr)[ul];
if (FConvert2InIsConvertable(pexprChild, eboolop))
{
pexprChild->AddRef();
pdrgpexprCollapse->Append(pexprChild);
}
else
{
// recursively convert the remainder and add to the array
pdrgpexprRemainder->Append(PexprConvert2In(mp, pexprChild));
}
}
if (0 != pdrgpexprCollapse->Size())
{
// create the constraint, rederive the collapsed expression
// add the new derived expr to remainder
CColRefSetArray *colref_array = nullptr;
pop->AddRef();
CAutoRef<CExpression> apexprPreCollapse(
GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprCollapse));
CAutoRef<CConstraint> apcnst(CConstraint::PcnstrFromScalarExpr(
mp, apexprPreCollapse.Value(), &colref_array));
GPOS_ASSERT(nullptr != apcnst.Value());
CExpression *pexprPostCollapse = apcnst->PexprScalar(mp);
pexprPostCollapse->AddRef();
pdrgpexprRemainder->Append(pexprPostCollapse);
CRefCount::SafeRelease(colref_array);
}
else
{
pdrgpexprCollapse->Release();
}
GPOS_ASSERT(0 < pdrgpexprRemainder->Size());
return PexprScalarBoolOpConvert2In(mp, eboolop, pdrgpexprRemainder);
}
CExpressionArray *pdrgpexpr = GPOS_NEW(mp) CExpressionArray(mp);
CExpressionArray *pdrgexprChildren = pexpr->PdrgPexpr();
for (ULONG ul = 0; ul < pexpr->Arity(); ul++)
{
pdrgpexpr->Append(PexprConvert2In(mp, (*pdrgexprChildren)[ul]));
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexpr);
}
// collapse cascaded inner and left outer joins into NAry-joins
CExpression *
CExpressionPreprocessor::PexprCollapseJoins(CMemoryPool *mp, CExpression *pexpr)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(nullptr != mp);
GPOS_ASSERT(nullptr != pexpr);
COperator *pop = pexpr->Pop();
const ULONG arity = pexpr->Arity();
if (CPredicateUtils::FInnerOrNAryJoin(pexpr) ||
(GPOS_FTRACE(EopttraceEnableLOJInNAryJoin) &&
CPredicateUtils::FLeftOuterJoin(pexpr)))
{
CExpressionArray *newChildNodes = GPOS_NEW(mp) CExpressionArray(mp);
ULongPtrArray *lojChildPredIndexes = GPOS_NEW(mp) ULongPtrArray(mp);
CExpressionArray *innerJoinPredicates =
GPOS_NEW(mp) CExpressionArray(mp);
CExpressionArray *lojPredicates = GPOS_NEW(mp) CExpressionArray(mp);
CollectJoinChildrenRecursively(mp, pexpr, newChildNodes,
lojChildPredIndexes, innerJoinPredicates,
lojPredicates);
if (lojPredicates->Size() > 0)
{
// each logical child must have an associated predicate index
GPOS_ASSERT(newChildNodes->Size() == lojChildPredIndexes->Size());
// this NAry join involves LOJs; create a CScalarNAryJoinPredList to hold
// the information which predicates are inner join preds and which ON predicates
// are associated with the LOJs' right children
CExpressionArray *naryJoinPredicates =
GPOS_NEW(mp) CExpressionArray(mp);
// create a new CScalarNAryJoinPredList as the last child of the NAry join
// the first child are all the inner join predicates
naryJoinPredicates->Append(
CPredicateUtils::PexprConjunction(mp, innerJoinPredicates));
// the remaining children are the LOJ predicates, one by one
for (ULONG ul = 0; ul < lojPredicates->Size(); ul++)
{
CExpression *predicate = (*lojPredicates)[ul];
predicate->AddRef();
naryJoinPredicates->Append(predicate);
}
CExpression *nAryJoinPredicateList = GPOS_NEW(mp)
CExpression(mp, GPOS_NEW(mp) CScalarNAryJoinPredList(mp),
naryJoinPredicates);
newChildNodes->Append(nAryJoinPredicateList);
// some sanity checks
// Example: t1 join t2 on p12 left outer join t3 on p23 join t4 on p24 left outer join t5 on p35
// results from this call:
// newChildNodes: [ t1, t2, t3, t4, t5 ]
// lojChildPredIndexes: [ 0, 0, 1, 0, 2 ] (one entry per logical leaf node)
// innerjoinPredicates: [ p12, p24 ] (all correspond to child pred index 0 (GPOPT_ZERO_INNER_JOIN_PRED_INDEX))
// lojPredicates: [ p23, p35 ] (p23 corresponds to child pred index 1, p35 corresponds to child pred index 2)
// the leftmost child must have a predicate index of
// GPOPT_ZERO_INNER_JOIN_PRED_INDEX, since it cannot be the right child of an LOJ
GPOS_ASSERT(GPOPT_ZERO_INNER_JOIN_PRED_INDEX ==
*(*lojChildPredIndexes)[0]);
#ifdef GPOS_DEBUG
// lojChildPredIndexes must contain the numbers 1 ... lojPredicates->Size()
// in ascending order, each number exactly once, with optional additional
// GPOPT_ZERO_INNER_JOIN_PRED_INDEX (0) entries in-between entries
ULONG highestNumberSeen = 0;
for (ULONG ix = 1; ix < lojChildPredIndexes->Size(); ix++)
{
ULONG nextNumber = *((*lojChildPredIndexes)[ix]);
if (nextNumber == highestNumberSeen + 1)
{
// child is right child of an LOJ
highestNumberSeen = nextNumber;
}
else
{
// if we don't see the next number for a child, it must
// be associated with the collective inner join predicates
GPOS_ASSERT(GPOPT_ZERO_INNER_JOIN_PRED_INDEX == nextNumber);
}
}
GPOS_ASSERT(highestNumberSeen == lojPredicates->Size());
#endif
}
else
{
// no LOJs involved, just add the ANDed preds as the scalar child
newChildNodes->Append(
CPredicateUtils::PexprConjunction(mp, innerJoinPredicates));
lojChildPredIndexes->Release();
lojChildPredIndexes = nullptr;
}
CExpression *pexprNAryJoin = GPOS_NEW(mp) CExpression(
mp, GPOS_NEW(mp) CLogicalNAryJoin(mp, lojChildPredIndexes),
newChildNodes);
COptimizerConfig *optimizer_config =
COptCtxt::PoctxtFromTLS()->GetOptimizerConfig();
ULONG ulJoinArityLimit =
optimizer_config->GetHint()
->UlJoinArityForAssociativityCommutativity();
// The last child of an n-ary join expression is the scalar expression
if (pexprNAryJoin->Arity() - 1 > ulJoinArityLimit)
{
GPOPT_DISABLE_XFORM(CXform::ExfInnerJoinCommutativity);
GPOPT_DISABLE_XFORM(CXform::ExfJoinAssociativity);
}
lojPredicates->Release();
return pexprNAryJoin;
}
// current operator is not an inner-join or supported LOJ, recursively process children
CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp);
for (ULONG ul = 0; ul < arity; ul++)
{
CExpression *pexprChild = PexprCollapseJoins(mp, (*pexpr)[ul]);
pdrgpexprChildren->Append(pexprChild);
}
pop->AddRef();
return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren);
}
// collect the children of a join backbone into an array of logical leaf
// nodes (leaves of the backbone, that is) and arrays of predicates, such
// that we can still associate the correct ON predicates to the children
void
CExpressionPreprocessor::CollectJoinChildrenRecursively(
CMemoryPool *mp, CExpression *pexpr, CExpressionArray *logicalLeafNodes,
ULongPtrArray *lojChildPredIndexes, CExpressionArray *innerJoinPredicates,
CExpressionArray *lojPredicates)
{
// protect against stack overflow during recursion
GPOS_CHECK_STACK_SIZE;
GPOS_ASSERT(pexpr->Pop()->FLogical());
if (CPredicateUtils::FInnerOrNAryJoin(pexpr))
{
const ULONG arity = pexpr->Arity();