-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCJoinOrderDPv2.cpp
More file actions
2166 lines (1920 loc) · 66.4 KB
/
Copy pathCJoinOrderDPv2.cpp
File metadata and controls
2166 lines (1920 loc) · 66.4 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 (C) 2019 VMware, Inc. or its affiliates.
//
// @filename:
// CJoinOrderDPv2.cpp
//
// @doc:
// Implementation of dynamic programming-based join order generation
//---------------------------------------------------------------------------
#include "gpopt/xforms/CJoinOrderDPv2.h"
#include "gpos/base.h"
#include "gpos/common/CBitSet.h"
#include "gpos/common/CBitSetIter.h"
#include "gpos/common/clibwrapper.h"
#include "gpos/error/CAutoTrace.h"
#include "gpopt/base/CDrvdPropScalar.h"
#include "gpopt/base/COptCtxt.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/cost/ICostModelParams.h"
#include "gpopt/exception.h"
#include "gpopt/operators/CLogicalInnerJoin.h"
#include "gpopt/operators/CLogicalLeftOuterJoin.h"
#include "gpopt/operators/CLogicalSelect.h"
#include "gpopt/operators/CNormalizer.h"
#include "gpopt/operators/CPhysicalJoin.h"
#include "gpopt/operators/CPredicateUtils.h"
#include "gpopt/operators/CScalarNAryJoinPredList.h"
#include "gpopt/optimizer/COptimizerConfig.h"
#include "naucrates/md/CMDIdRelStats.h"
#include "naucrates/md/IMDRelStats.h"
#include "naucrates/statistics/CJoinStatsProcessor.h"
using namespace gpopt;
// how many expressions will we return at the end of the DP phase?
// Note that this includes query, mincard and greedy solutions.
#define GPOPT_DPV2_JOIN_ORDERING_TOPK 10
// cost penalty (a factor) for cross product for enumeration algorithms other than GreedyAvoidXProd
// (value determined by simple experiments on TPC-DS queries)
// This is the default value for optimizer_nestloop_factor
#define GPOPT_DPV2_CROSS_JOIN_DEFAULT_PENALTY 1024
// prohibitively high penalty for cross products when in GreedyAvoidXProd
#define GPOPT_DPV2_CROSS_JOIN_GREEDY_PENALTY 1e9
// prohibitively high penalty for broadcast when it exceeds a threshold (similar to the real cost model)
#define BROACAST_PENALTY 1e14
// from cost model used during optimization in CCostModelParamsGPDB.cpp
#define BCAST_SEND_COST 4.965e-05
#define BCAST_RECV_COST 1.35e-06
#define SEQ_SCAN_COST 5.50e-07
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::CJoinOrderDPv2
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CJoinOrderDPv2::CJoinOrderDPv2(CMemoryPool *mp,
CExpressionArray *pdrgpexprAtoms,
CExpressionArray *innerJoinConjuncts,
CExpressionArray *onPredConjuncts,
ULongPtrArray *childPredIndexes,
CColRefSet *outerRefs)
: CJoinOrder(mp, pdrgpexprAtoms, innerJoinConjuncts, onPredConjuncts,
childPredIndexes),
m_expression_to_edge_map(nullptr),
m_on_pred_conjuncts(onPredConjuncts),
m_child_pred_indexes(childPredIndexes),
m_non_inner_join_dependencies(nullptr),
m_cross_prod_penalty(GPOPT_DPV2_CROSS_JOIN_DEFAULT_PENALTY),
m_outer_refs(outerRefs),
m_atom_sibling_required(nullptr)
{
m_join_levels = GPOS_NEW(mp) DPv2Levels(mp, m_ulComps + 1);
// populate levels array with n+1 levels for an n-way join
// level 0 remains unused, so index i corresponds to level i,
// making it easier for humans to read the code
for (ULONG l = 0; l <= m_ulComps; l++)
{
m_join_levels->Append(
GPOS_NEW(mp) SLevelInfo(l, GPOS_NEW(mp) SGroupInfoArray(mp)));
}
m_bitset_to_group_info_map = GPOS_NEW(mp) BitSetToGroupInfoMap(mp);
// Contains top k expressions for a general DP algorithm, without considering cost of motions/PS
m_top_k_expressions =
GPOS_NEW(mp) CKHeap<SExpressionInfoArray, SExpressionInfo>(
mp, GPOPT_DPV2_JOIN_ORDERING_TOPK);
// We use a separate heap to ensure we produce an alternative expression that contains a dynamic PS
// If no dynamic PS is valid, this will be empty.
m_top_k_part_expressions =
GPOS_NEW(mp) CKHeap<SExpressionInfoArray, SExpressionInfo>(
mp, 1 /* keep top 1 expression */
);
m_mp = mp;
if (0 < m_on_pred_conjuncts->Size())
{
// we have non-inner joins, add dependency info
ULONG numNonInnerJoins = m_on_pred_conjuncts->Size();
m_non_inner_join_dependencies =
GPOS_NEW(mp) CBitSetArray(mp, numNonInnerJoins);
for (ULONG ul = 0; ul < numNonInnerJoins; ul++)
{
m_non_inner_join_dependencies->Append(GPOS_NEW(mp) CBitSet(mp));
}
// compute dependencies of the NIJ right children
// (those components must appear on the left of the NIJ)
// Note: NIJ = Non-inner join, e.g. LOJ
for (ULONG en = 0; en < m_ulEdges; en++)
{
SEdge *pedge = m_rgpedge[en];
if (0 < pedge->m_loj_num)
{
// edge represents a non-inner join pred
ULONG logicalChildNum =
FindLogicalChildByNijId(pedge->m_loj_num);
CBitSet *nijBitSet =
(*m_non_inner_join_dependencies)[pedge->m_loj_num - 1];
GPOS_ASSERT(0 < logicalChildNum);
nijBitSet->Union(pedge->m_pbs);
// clear the bit representing the right side of the NIJ, we only
// want to track the components needed on the left side
nijBitSet->ExchangeClear(logicalChildNum);
}
}
}
PopulateExpressionToEdgeMapIfNeeded();
// Precompute per-atom sibling requirements. An atom's outer references
// that are not in m_outer_refs (those would propagate up to the parent of
// the NAryJoin) must be supplied by another atom in the NAryJoin. If
// atom j produces such a column, j is required whenever atom i appears in
// a join subset. This keeps join enumeration from forming subsets like
// {x, lateral_ref_to_y} that would leave the LATERAL's outer-ref unbound
// when the partial join expression is evaluated.
m_atom_sibling_required = GPOS_NEW(mp) CBitSetArray(mp, m_ulComps);
for (ULONG i = 0; i < m_ulComps; i++)
{
m_atom_sibling_required->Append(GPOS_NEW(mp) CBitSet(mp));
}
for (ULONG i = 0; i < m_ulComps; i++)
{
CExpression *pexpr_i = m_rgpcomp[i]->m_pexpr;
CColRefSet *outer_refs_i = pexpr_i->DeriveOuterReferences();
if (outer_refs_i->IsDisjoint(m_outer_refs) &&
0 == outer_refs_i->Size())
{
continue;
}
CColRefSet *sibling_refs = GPOS_NEW(mp) CColRefSet(mp, *outer_refs_i);
sibling_refs->Difference(m_outer_refs);
if (0 < sibling_refs->Size())
{
for (ULONG j = 0; j < m_ulComps; j++)
{
if (i == j)
{
continue;
}
CColRefSet *output_j =
m_rgpcomp[j]->m_pexpr->DeriveOutputColumns();
if (!sibling_refs->IsDisjoint(output_j))
{
(*m_atom_sibling_required)[i]->ExchangeSet(j);
}
}
}
sibling_refs->Release();
}
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::~CJoinOrderDPv2
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CJoinOrderDPv2::~CJoinOrderDPv2()
{
// in optimized build, we flush-down memory pools without leak checking,
// we can save time in optimized build by skipping all de-allocations here,
// we still have all de-allocations enabled in debug-build to detect any possible leaks
CRefCount::SafeRelease(m_non_inner_join_dependencies);
CRefCount::SafeRelease(m_child_pred_indexes);
m_bitset_to_group_info_map->Release();
CRefCount::SafeRelease(m_expression_to_edge_map);
m_top_k_expressions->Release();
m_top_k_part_expressions->Release();
m_join_levels->Release();
CRefCount::SafeRelease(m_atom_sibling_required);
m_on_pred_conjuncts->Release();
m_outer_refs->Release();
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::ComputeCost
//
// @doc:
// Primitive costing of join expressions;
// Cost of a join expression is the "internal data flow" of the join
// tree, the sum of all the rows flowing from the leaf nodes up to
// the root.
// NOTE: We could consider the width of the rows as well, if we had
// a reliable way of determining the actual width.
//
//---------------------------------------------------------------------------
void
CJoinOrderDPv2::ComputeCost(SExpressionInfo *expr_info,
CDouble join_cardinality)
{
// cardinality of the expression itself is one part of the cost
CDouble dCost(join_cardinality);
if (expr_info->m_left_child_expr.IsValid())
{
GPOS_ASSERT(expr_info->m_right_child_expr.IsValid());
// add cardinalities of the children to the cost
dCost = dCost + expr_info->m_left_child_expr.GetExprInfo()->m_cost;
dCost = dCost + expr_info->m_right_child_expr.GetExprInfo()->m_cost;
// if none of the preds are hashable, penalize this join as it will
// generate a NLJ (which is penalized in the optimization phase)
if (!CUtils::IsHashJoinPossible(m_mp, expr_info->m_expr))
{
// penalize cross joins, similar to what we do in the optimization phase
dCost = dCost * m_cross_prod_penalty;
}
expr_info->m_cost_adj_PS =
expr_info->m_cost_adj_PS +
expr_info->m_left_child_expr.GetExprInfo()->m_cost_adj_PS;
expr_info->m_cost_adj_PS =
expr_info->m_cost_adj_PS +
expr_info->m_right_child_expr.GetExprInfo()->m_cost_adj_PS;
}
expr_info->m_cost = dCost;
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::PexprBuildInnerJoinPred
//
// @doc:
// Build predicate connecting the two given sets
//
//---------------------------------------------------------------------------
CExpression *
CJoinOrderDPv2::PexprBuildInnerJoinPred(CBitSet *pbsFst, CBitSet *pbsSnd)
{
GPOS_ASSERT(pbsFst->IsDisjoint(pbsSnd));
// collect edges connecting the given sets
CBitSet *pbsEdges = GPOS_NEW(m_mp) CBitSet(m_mp);
CBitSet *pbs = GPOS_NEW(m_mp) CBitSet(m_mp, *pbsFst);
pbs->Union(pbsSnd);
for (ULONG ul = 0; ul < m_ulEdges; ul++)
{
SEdge *pedge = m_rgpedge[ul];
if (
// edge represents an inner join pred
0 == pedge->m_loj_num &&
// all columns referenced in the edge pred are provided
pbs->ContainsAll(pedge->m_pbs) &&
// the edge represents a true join predicate between the two components
!pbsFst->IsDisjoint(pedge->m_pbs) &&
!pbsSnd->IsDisjoint(pedge->m_pbs))
{
BOOL fSet GPOS_ASSERTS_ONLY = pbsEdges->ExchangeSet(ul);
GPOS_ASSERT(!fSet);
}
}
pbs->Release();
CExpression *pexprPred = nullptr;
if (0 < pbsEdges->Size())
{
CExpressionArray *pdrgpexpr = GPOS_NEW(m_mp) CExpressionArray(m_mp);
CBitSetIter bsi(*pbsEdges);
while (bsi.Advance())
{
ULONG ul = bsi.Bit();
SEdge *pedge = m_rgpedge[ul];
pedge->m_pexpr->AddRef();
pdrgpexpr->Append(pedge->m_pexpr);
}
pexprPred = CPredicateUtils::PexprConjunction(m_mp, pdrgpexpr);
}
pbsEdges->Release();
return pexprPred;
}
void
CJoinOrderDPv2::DeriveStats(CExpression *pexpr)
{
try
{
// We want to let the histogram code compute the join selectivity and the number of NDVs based
// on actual histogram buckets, taking into account the overlap of the data ranges. It helps
// with getting more consistent and accurate cardinality estimates for DP.
// Eventually, this should probably become the default method.
CJoinStatsProcessor::SetComputeScaleFactorFromHistogramBuckets(true);
CJoinOrder::DeriveStats(pexpr);
CJoinStatsProcessor::SetComputeScaleFactorFromHistogramBuckets(false);
}
catch (...)
{
CJoinStatsProcessor::SetComputeScaleFactorFromHistogramBuckets(false);
throw;
}
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::GetJoinExprForProperties
//
// @doc:
// Build a CExpression joining the two given sets, choosing child
// expressions with given properties
//
//---------------------------------------------------------------------------
CJoinOrderDPv2::SExpressionInfo *
CJoinOrderDPv2::GetJoinExprForProperties(
SGroupInfo *left_child, SGroupInfo *right_child,
SExpressionProperties &required_properties)
{
SGroupAndExpression left_expr =
GetBestExprForProperties(left_child, required_properties);
SGroupAndExpression right_expr =
GetBestExprForProperties(right_child, required_properties);
if (!left_expr.IsValid() || !right_expr.IsValid())
{
return nullptr;
}
return GetJoinExpr(left_expr, right_expr, required_properties);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::GetJoinExpr
//
// @doc:
// Build a CExpression joining the two given sets from given expressions
//
//---------------------------------------------------------------------------
CJoinOrderDPv2::SExpressionInfo *
CJoinOrderDPv2::GetJoinExpr(const SGroupAndExpression &left_child_expr,
const SGroupAndExpression &right_child_expr,
SExpressionProperties &result_properties)
{
SGroupInfo *left_group_info = left_child_expr.m_group_info;
if (IsRightChildOfNIJ(left_group_info))
{
// can't use the right child of an NIJ on the left side
return nullptr;
}
SExpressionInfo *left_expr_info = left_child_expr.GetExprInfo();
SGroupInfo *right_group_info = right_child_expr.m_group_info;
SExpressionInfo *right_expr_info = right_child_expr.GetExprInfo();
// LATERAL sibling visibility: every atom in the combined subset must have
// all of its required-sibling atoms already present. Otherwise the
// combined expression has an atom whose outer references reach an atom
// that's not yet in the join, and the resulting partial plan would leave
// those refs unbound at execution time.
if (nullptr != m_atom_sibling_required)
{
CBitSet *combined_atoms =
GPOS_NEW(m_mp) CBitSet(m_mp, *left_group_info->m_atoms);
combined_atoms->Union(right_group_info->m_atoms);
CBitSetIter iter(*combined_atoms);
BOOL valid = true;
while (valid && iter.Advance())
{
ULONG atom_id = iter.Bit();
CBitSet *required = (*m_atom_sibling_required)[atom_id];
if (0 < required->Size() && !combined_atoms->ContainsAll(required))
{
valid = false;
}
}
combined_atoms->Release();
if (!valid)
{
return nullptr;
}
}
CExpression *scalar_expr = nullptr;
CBitSet *required_on_left = nullptr;
BOOL isLOJ =
IsRightChildOfNIJ(right_group_info, &scalar_expr, &required_on_left);
if (!isLOJ)
{
// inner join, compute the predicate from the join graph
GPOS_ASSERT(nullptr == scalar_expr);
scalar_expr = PexprBuildInnerJoinPred(left_group_info->m_atoms,
right_group_info->m_atoms);
}
else
{
// check whether scalar_expr can be computed from left_child and right_child,
// otherwise this is not a valid join
GPOS_ASSERT(nullptr != scalar_expr && nullptr != required_on_left);
if (!left_group_info->m_atoms->ContainsAll(required_on_left))
{
// the left child does not produce all the values needed in the ON
// predicate, so this is not a valid join
return nullptr;
}
scalar_expr->AddRef();
}
if (nullptr == scalar_expr)
{
// this is a cross product
if (right_group_info->IsAnAtom())
{
// generate a TRUE boolean expression as the join predicate of the cross product
scalar_expr = CUtils::PexprScalarConstBool(m_mp, true);
}
else
{
// we don't do bushy cross products, any mandatory or optional cross products
// are linear trees
return nullptr;
}
}
CExpression *join_expr = nullptr;
CExpression *left_expr = left_expr_info->m_expr;
CExpression *right_expr = right_expr_info->m_expr;
left_expr->AddRef();
right_expr->AddRef();
if (isLOJ)
{
join_expr = CUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>(
m_mp, left_expr, right_expr, scalar_expr);
}
else
{
join_expr = CUtils::PexprLogicalJoin<CLogicalInnerJoin>(
m_mp, left_expr, right_expr, scalar_expr);
}
return GPOS_NEW(m_mp) SExpressionInfo(m_mp, join_expr, left_child_expr,
right_child_expr, result_properties);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::IsASupersetOfProperties
//
// @doc:
// Return whether <prop> provides a superset of the properties <other_prop>
//
//---------------------------------------------------------------------------
BOOL
CJoinOrderDPv2::IsASupersetOfProperties(SExpressionProperties &prop,
SExpressionProperties &other_prop)
{
// are the bits in other_prop a subset of the bits in prop?
return 0 == (other_prop.m_join_order & ~prop.m_join_order);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::ArePropertiesDisjoint
//
// @doc:
// Return whether each of the two properties provides something that
// the other property doesn't provide.
//
//---------------------------------------------------------------------------
BOOL
CJoinOrderDPv2::ArePropertiesDisjoint(SExpressionProperties &prop,
SExpressionProperties &other_prop)
{
return !IsASupersetOfProperties(prop, other_prop) &&
!IsASupersetOfProperties(other_prop, prop);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::GetBestExprForProperties
//
// @doc:
// Given a group and required properties, return an expression in the
// group that satisfies the required properties or return an invalid
// SGroupAndExpression object if no such expression exists.
// Use SGroupAndExpression::IsValid() to test the validity of the
// return value.
//
//---------------------------------------------------------------------------
CJoinOrderDPv2::SGroupAndExpression
CJoinOrderDPv2::GetBestExprForProperties(SGroupInfo *group_info,
SExpressionProperties &props)
{
ULONG best_ix = gpos::ulong_max;
CDouble best_cost(0.0);
for (ULONG ul = 0; ul < group_info->m_best_expr_info_array->Size(); ul++)
{
SExpressionInfo *expr_info = (*group_info->m_best_expr_info_array)[ul];
if (IsASupersetOfProperties(expr_info->m_properties, props))
{
if (gpos::ulong_max == best_ix || expr_info->GetCost() < best_cost)
{
// we found a candidate with the best cost so far that satisfies the properties
best_ix = ul;
best_cost = expr_info->GetCost();
}
}
}
return SGroupAndExpression(group_info, best_ix);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::AddNewPropertyToExpr
//
// @doc:
// Add a new property that an existing expression in a group provides.
// NOTE: This method should be used with care! Only add a property that
// does not yet exist in the current level or in any higher level.
//
//---------------------------------------------------------------------------
void
CJoinOrderDPv2::AddNewPropertyToExpr(SExpressionInfo *expr_info,
SExpressionProperties props)
{
expr_info->m_properties.Add(props);
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::AddExprToGroupIfNecessary
//
// @doc:
// Check a new expression to see whether it provides any new property or
// whether it provides the same property as an existing expression at a
// lower cost. If so, add the new expression or replace an existing
// expression with the better one. Otherwise, release the expression.
//
//---------------------------------------------------------------------------
void
CJoinOrderDPv2::AddExprToGroupIfNecessary(SGroupInfo *group_info,
SExpressionInfo *new_expr_info)
{
// compute the cost for the new expression
ComputeCost(new_expr_info, group_info->m_cardinality);
CDouble new_cost = new_expr_info->GetCost();
if (group_info->m_atoms->Size() == m_ulComps)
{
// At the top level, we have only one group. To be able to return multiple results
// for the xform, we keep the top k expressions (all from the same group) in a KHeap
new_expr_info->AddRef();
if (new_expr_info->m_properties.Satisfies(EJoinOrderHasPS))
{
m_top_k_part_expressions->Insert(new_expr_info);
}
else
{
m_top_k_expressions->Insert(new_expr_info);
}
}
if (0 == group_info->m_best_expr_info_array->Size() ||
new_cost < group_info->m_lowest_expr_cost)
{
// update the low water mark for the cost seen in this group
group_info->m_lowest_expr_cost = new_cost;
}
// loop through the existing expressions, comparing cost and properties with each
// existing expression, and perform the following action if cost and properties of
// the new expression are:
//
// case properties cost action
// ---- ---------- ------ -------------------
// 1 < < continue
// 2 < >= discard, stop
// 3 = < replace, stop
// 4 = >= discard, stop
// 5 > <= replace, stop (*)
// 6 > > continue
// 7 different any continue
//
// if we reach the end of the list of existing expressions and have not yet stopped,
// then we add the new expression.
//
// (*) Note that if we find a new expression that provides more properties for the same
// or lower cost, we could potentially replace more than one expression. Right now this
// is not done, we replace only the first such expression we find (see the rule below
// for the reason).
//
// Since we are using indexes into the array of expressions, we follow this ground rule
// to keep those indexes consistent: Once an SExpressionInfo is inserted into the
// m_best_expr_info_array at an index i, this entry will remain at the same index.
// This method ensures that its cost can only go down and its properties can only increase.
// This rule holds across multiple enumeration algorithms. Therefore, SExpressionInfos from higher
// groups can reliably refer to indexes in the m_best_expr_info_array of their child groups.
BOOL discard = false;
BOOL replaced_expr = false;
for (ULONG ul = 0; ul < group_info->m_best_expr_info_array->Size(); ul++)
{
SExpressionInfo *expr_info = (*group_info->m_best_expr_info_array)[ul];
BOOL old_ge_new = IsASupersetOfProperties(expr_info->m_properties,
new_expr_info->m_properties);
BOOL new_ge_old = IsASupersetOfProperties(new_expr_info->m_properties,
expr_info->m_properties);
CDouble old_cost = expr_info->GetCost();
CDouble new_cost = new_expr_info->GetCost();
if (old_ge_new)
{
if (!new_ge_old)
{
// new expression provides fewer properties
if (new_cost < old_cost)
{
// case 1
continue;
}
else
{
// case 2
discard = true;
break;
}
}
else
{
// both expressions provide the same properties
if (new_cost < old_cost)
{
// case 3
group_info->m_best_expr_info_array->Replace(ul,
new_expr_info);
replaced_expr = true;
break;
}
else
{
// case 4
discard = true;
break;
}
}
}
else
{
if (new_ge_old)
{
// new expression provides more properties
if (new_cost <= old_cost)
{
// case 5
group_info->m_best_expr_info_array->Replace(ul,
new_expr_info);
replaced_expr = true;
break;
}
else
{
// case 6
continue;
}
}
else
{
// new expression provides different properties, neither more nor less
// case 7
continue;
}
}
}
if (discard)
{
// the new expression needs to be discarded
new_expr_info->Release();
}
else if (!replaced_expr)
{
// we went through all existing expressions without replacing an existing one and
// without deciding to discard the new expression, therefore we need to add the
// new expression
group_info->m_best_expr_info_array->Append(new_expr_info);
}
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::PopulateExpressionToEdgeMapIfNeeded
//
// @doc:
// In some cases we may not place all of the predicates in the NAry join in
// the resulting tree of binary joins. If that situation is a possibility,
// we'll create a map from expressions to edges, so that we can find any
// unused edges to be placed in a select node on top of the join.
//
// Examples:
// select * from foo left join bar on foo.a=bar.a where coalesce(bar.b, 0) < 10;
// select * from foo left join bar on foo.a=bar.a where foo.a = outer_ref;
//
//---------------------------------------------------------------------------
void
CJoinOrderDPv2::PopulateExpressionToEdgeMapIfNeeded()
{
BOOL populate = false;
if (0 < m_outer_refs->Size())
{
// with outer refs we can get predicates like <col> = <outer ref>
// that are not real join predicates
populate = true;
}
if (!populate && nullptr != m_child_pred_indexes)
{
// check for WHERE predicates involving LOJ right children
// make a bitset b with all the LOJ right children
CBitSet *loj_right_children = GPOS_NEW(m_mp) CBitSet(m_mp);
for (ULONG c = 0; c < m_child_pred_indexes->Size(); c++)
{
if (0 < *((*m_child_pred_indexes)[c]))
{
loj_right_children->ExchangeSet(c);
}
}
for (ULONG en1 = 0; en1 < m_ulEdges; en1++)
{
SEdge *pedge = m_rgpedge[en1];
if (pedge->m_loj_num == 0)
{
// check whether this inner join (WHERE) predicate refers to any LOJ right child
// (whether its bitset overlaps with b)
// or whether we see any local predicates (this should be uncommon)
if (!loj_right_children->IsDisjoint(pedge->m_pbs) ||
1 == pedge->m_pbs->Size())
{
populate = true;
break;
}
}
}
loj_right_children->Release();
}
if (populate)
{
m_expression_to_edge_map = GPOS_NEW(m_mp) ExpressionToEdgeMap(m_mp);
for (ULONG en2 = 0; en2 < m_ulEdges; en2++)
{
SEdge *pedge = m_rgpedge[en2];
pedge->AddRef();
pedge->m_pexpr->AddRef();
m_expression_to_edge_map->Insert(pedge->m_pexpr, pedge);
}
}
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::AddSelectNodeForRemainingEdges
//
// @doc:
// add a select node with any remaining edges (predicates) that have
// not been incorporated in the join tree
//
//---------------------------------------------------------------------------
CExpression *
CJoinOrderDPv2::AddSelectNodeForRemainingEdges(CExpression *join_expr)
{
if (nullptr == m_expression_to_edge_map)
{
return join_expr;
}
CExpressionArray *exprArray = GPOS_NEW(m_mp) CExpressionArray(m_mp);
RecursivelyMarkEdgesAsUsed(join_expr);
// find any unused edges and add them to a select
for (ULONG en = 0; en < m_ulEdges; en++)
{
SEdge *pedge = m_rgpedge[en];
if (pedge->m_fUsed)
{
// mark the edge as unused for the next alternative, where
// we will have to repeat this check
pedge->m_fUsed = false;
}
else
{
// found an unused edge, this one will need to go into
// a select node on top of the join
pedge->m_pexpr->AddRef();
exprArray->Append(pedge->m_pexpr);
}
}
if (0 < exprArray->Size())
{
CExpression *conj = CPredicateUtils::PexprConjunction(m_mp, exprArray);
return GPOS_NEW(m_mp) CExpression(
m_mp, GPOS_NEW(m_mp) CLogicalSelect(m_mp), join_expr, conj);
}
exprArray->Release();
return join_expr;
}
//---------------------------------------------------------------------------
// @function:
// CJoinOrderDPv2::RecursivelyMarkEdgesAsUsed
//
// @doc:
// mark all the edges corresponding to any part of <expr> as used
//
//---------------------------------------------------------------------------
void
CJoinOrderDPv2::RecursivelyMarkEdgesAsUsed(CExpression *expr)
{
GPOS_CHECK_STACK_SIZE;
if (expr->Pop()->FLogical())
{
for (ULONG ul = 0; ul < expr->Arity(); ul++)
{
RecursivelyMarkEdgesAsUsed((*expr)[ul]);
}
}
else
{
GPOS_ASSERT(expr->Pop()->FScalar());
const SEdge *edge = m_expression_to_edge_map->Find(expr);
if (nullptr != edge)
{
// we found the edge belonging to this expression, terminate the recursion
const_cast<SEdge *>(edge)->m_fUsed = true;
return;
}
// we should not reach the leaves of the tree without finding an edge
GPOS_ASSERT(0 < expr->Arity() || CUtils::FScalarConstTrue(expr));
// this is an AND of multiple edges
for (ULONG ul = 0; ul < expr->Arity(); ul++)
{
RecursivelyMarkEdgesAsUsed((*expr)[ul]);
}
}
}
// Consider partition selector/broadcast and populate join_expr_info accordingly
// Specifically, we're looking for joins in the form
// Join
// - DTS
// - table scan (or tree)
// - predicate
//
// In this case, we can put the PS over the table scan
// We make a few assumptions:
// 1. The benefits of a PS are from the selectivity of a single table, rather than the join result between two tables. We find this table by looking for logical selects.
// 2. The selectivty of this single table is equal to the selectivity of the PS
//
// If the right atom is a PT, then we need to check if the left expression has a PS that may satisfy it.
// If it is, we mark this SExpressionInfo as containing a PS
// We only consider linear trees here, since bushy trees would increase the search space and increase the
// chance of motions between the PS and PT, which then would fail requirements during optimization
//
// This function includes 4 main steps:
// 1. Exit early if group contains a partition table or if partition table already has a partition selector
// 2. Exit if distribution specs are incompitible and motion would be added, which makes partition selector invalid
// 3. Check whether join expression condition contains the partition key
// 4. DPE cost adjustment
void
CJoinOrderDPv2::PopulateDPEInfo(SExpressionInfo *join_expr_info,
SGroupInfo *part_table_group_info,
SGroupInfo *part_selector_group_info)
{
SGroupInfoArray *atom_groups = GetGroupsForLevel(1);
CBitSetIter iter_pt(*part_table_group_info->m_atoms);
CExpression *pt_atom_expr = nullptr;
CPartKeysArray *partition_keys = nullptr;
SGroupInfo *pt_atom = nullptr;
// iterate through each atom of the "outer" (left) group, and look for a partition table
// that does not yet have a partition selector.
// Once a partition table is found, check if it has a valid partition selector. I
// if no valid partition selectors are found, continue to the next partition table.
while (iter_pt.Advance())
{
pt_atom = (*atom_groups)[iter_pt.Bit()];
pt_atom_expr = (*pt_atom->m_best_expr_info_array)[0]->m_expr;
partition_keys =
(*pt_atom->m_best_expr_info_array)[0]->m_atom_part_keys_array;
// continue if there are no partition keys or if the partition table already has an
// associated partition selector
if (partition_keys == nullptr || partition_keys->Size() == 0 ||
join_expr_info->m_contain_PS->Get(iter_pt.Bit()))
{
continue;
}
// check if this join order will produce a valid partition selector
// this can only occur if the distribution spec matches.
// consider the below join tree:
// HJ3
// HJ2 PS2
// PT2 HJ1
// PT1 PS1
// If there is a motion between PT2 and PS2, then this is not a valid plan for partition selection
// Therefore, when considering a table that may produce a partition selector, we need to check the join expression
// below the current join.
// columns of child join condition (HJ2 in example above)
CColRefSet *left_child_join_condition_cols = nullptr;
// only check for a valid partition selector for joins with more than 1 level.
// For single level joins, eg: A HJ B, there is no join below A and we can skip this logic
// and go straight ahead to check if the join expr overlaps the partition key
if (!part_table_group_info->IsAnAtom())
{
CExpression *left_child_join_expr =
join_expr_info->m_left_child_expr.GetExprInfo()->m_expr;
left_child_join_condition_cols =
(*left_child_join_expr)[left_child_join_expr->Arity() - 1]
->DeriveUsedColumns();
// retrieve the table descriptor in order to get the distribution columns of the partition table
CLogical *popLogical = CLogical::PopConvert(pt_atom_expr->Pop());
CTableDescriptor *atom_table_descriptor =
CLogical::PtabdescFromTableGet(popLogical);
if (nullptr != atom_table_descriptor &&
nullptr != left_child_join_condition_cols)
{
CColRefArray *atomOutputColArray =
pt_atom_expr->DeriveOutputColumns()->Pdrgpcr(m_mp);
if (atomOutputColArray->Size() != atom_table_descriptor->Pdrgpcoldesc()->Size())
{
// Skip DPE optimization for this case
atomOutputColArray->Release();
continue;
}
CColRefSet *pt_atom_distribution_cols = CLogical::PcrsDist(
m_mp, atom_table_descriptor, atomOutputColArray);
atomOutputColArray->Release();