LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - joinrels.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 456 483 94.4 %
Date: 2019-09-22 07:07:17 Functions: 17 17 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * joinrels.c
       4             :  *    Routines to determine which relations should be joined
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/optimizer/path/joinrels.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "miscadmin.h"
      18             : #include "optimizer/appendinfo.h"
      19             : #include "optimizer/joininfo.h"
      20             : #include "optimizer/pathnode.h"
      21             : #include "optimizer/paths.h"
      22             : #include "partitioning/partbounds.h"
      23             : #include "utils/lsyscache.h"
      24             : #include "utils/memutils.h"
      25             : 
      26             : 
      27             : static void make_rels_by_clause_joins(PlannerInfo *root,
      28             :                                       RelOptInfo *old_rel,
      29             :                                       List *other_rels_list,
      30             :                                       ListCell *other_rels);
      31             : static void make_rels_by_clauseless_joins(PlannerInfo *root,
      32             :                                           RelOptInfo *old_rel,
      33             :                                           List *other_rels);
      34             : static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
      35             : static bool has_legal_joinclause(PlannerInfo *root, RelOptInfo *rel);
      36             : static bool restriction_is_constant_false(List *restrictlist,
      37             :                                           RelOptInfo *joinrel,
      38             :                                           bool only_pushed_down);
      39             : static void populate_joinrel_with_paths(PlannerInfo *root, RelOptInfo *rel1,
      40             :                                         RelOptInfo *rel2, RelOptInfo *joinrel,
      41             :                                         SpecialJoinInfo *sjinfo, List *restrictlist);
      42             : static void try_partitionwise_join(PlannerInfo *root, RelOptInfo *rel1,
      43             :                                    RelOptInfo *rel2, RelOptInfo *joinrel,
      44             :                                    SpecialJoinInfo *parent_sjinfo,
      45             :                                    List *parent_restrictlist);
      46             : static SpecialJoinInfo *build_child_join_sjinfo(PlannerInfo *root,
      47             :                                                 SpecialJoinInfo *parent_sjinfo,
      48             :                                                 Relids left_relids, Relids right_relids);
      49             : static int  match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel,
      50             :                                          bool strict_op);
      51             : 
      52             : 
      53             : /*
      54             :  * join_search_one_level
      55             :  *    Consider ways to produce join relations containing exactly 'level'
      56             :  *    jointree items.  (This is one step of the dynamic-programming method
      57             :  *    embodied in standard_join_search.)  Join rel nodes for each feasible
      58             :  *    combination of lower-level rels are created and returned in a list.
      59             :  *    Implementation paths are created for each such joinrel, too.
      60             :  *
      61             :  * level: level of rels we want to make this time
      62             :  * root->join_rel_level[j], 1 <= j < level, is a list of rels containing j items
      63             :  *
      64             :  * The result is returned in root->join_rel_level[level].
      65             :  */
      66             : void
      67       59496 : join_search_one_level(PlannerInfo *root, int level)
      68             : {
      69       59496 :     List      **joinrels = root->join_rel_level;
      70             :     ListCell   *r;
      71             :     int         k;
      72             : 
      73             :     Assert(joinrels[level] == NIL);
      74             : 
      75             :     /* Set join_cur_level so that new joinrels are added to proper list */
      76       59496 :     root->join_cur_level = level;
      77             : 
      78             :     /*
      79             :      * First, consider left-sided and right-sided plans, in which rels of
      80             :      * exactly level-1 member relations are joined against initial relations.
      81             :      * We prefer to join using join clauses, but if we find a rel of level-1
      82             :      * members that has no join clauses, we will generate Cartesian-product
      83             :      * joins against all initial rels not already contained in it.
      84             :      */
      85      210108 :     foreach(r, joinrels[level - 1])
      86             :     {
      87      150612 :         RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
      88             : 
      89      156578 :         if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
      90        5966 :             has_join_restriction(root, old_rel))
      91      146234 :         {
      92             :             /*
      93             :              * There are join clauses or join order restrictions relevant to
      94             :              * this rel, so consider joins between this rel and (only) those
      95             :              * initial rels it is linked to by a clause or restriction.
      96             :              *
      97             :              * At level 2 this condition is symmetric, so there is no need to
      98             :              * look at initial rels before this one in the list; we already
      99             :              * considered such joins when we were at the earlier rel.  (The
     100             :              * mirror-image joins are handled automatically by make_join_rel.)
     101             :              * In later passes (level > 2), we join rels of the previous level
     102             :              * to each initial rel they don't already include but have a join
     103             :              * clause or restriction with.
     104             :              */
     105             :             List       *other_rels_list;
     106             :             ListCell   *other_rels;
     107             : 
     108      146234 :             if (level == 2)     /* consider remaining initial rels */
     109             :             {
     110      101662 :                 other_rels_list = joinrels[level - 1];
     111      101662 :                 other_rels = lnext(other_rels_list, r);
     112             :             }
     113             :             else                /* consider all initial rels */
     114             :             {
     115       44572 :                 other_rels_list = joinrels[1];
     116       44572 :                 other_rels = list_head(other_rels_list);
     117             :             }
     118             : 
     119      146234 :             make_rels_by_clause_joins(root,
     120             :                                       old_rel,
     121             :                                       other_rels_list,
     122             :                                       other_rels);
     123             :         }
     124             :         else
     125             :         {
     126             :             /*
     127             :              * Oops, we have a relation that is not joined to any other
     128             :              * relation, either directly or by join-order restrictions.
     129             :              * Cartesian product time.
     130             :              *
     131             :              * We consider a cartesian product with each not-already-included
     132             :              * initial rel, whether it has other join clauses or not.  At
     133             :              * level 2, if there are two or more clauseless initial rels, we
     134             :              * will redundantly consider joining them in both directions; but
     135             :              * such cases aren't common enough to justify adding complexity to
     136             :              * avoid the duplicated effort.
     137             :              */
     138        4378 :             make_rels_by_clauseless_joins(root,
     139             :                                           old_rel,
     140        4378 :                                           joinrels[1]);
     141             :         }
     142             :     }
     143             : 
     144             :     /*
     145             :      * Now, consider "bushy plans" in which relations of k initial rels are
     146             :      * joined to relations of level-k initial rels, for 2 <= k <= level-2.
     147             :      *
     148             :      * We only consider bushy-plan joins for pairs of rels where there is a
     149             :      * suitable join clause (or join order restriction), in order to avoid
     150             :      * unreasonable growth of planning time.
     151             :      */
     152       65822 :     for (k = 2;; k++)
     153        6326 :     {
     154       65822 :         int         other_level = level - k;
     155             : 
     156             :         /*
     157             :          * Since make_join_rel(x, y) handles both x,y and y,x cases, we only
     158             :          * need to go as far as the halfway point.
     159             :          */
     160       65822 :         if (k > other_level)
     161       59496 :             break;
     162             : 
     163       31450 :         foreach(r, joinrels[k])
     164             :         {
     165       25124 :             RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
     166             :             List       *other_rels_list;
     167             :             ListCell   *other_rels;
     168             :             ListCell   *r2;
     169             : 
     170             :             /*
     171             :              * We can ignore relations without join clauses here, unless they
     172             :              * participate in join-order restrictions --- then we might have
     173             :              * to force a bushy join plan.
     174             :              */
     175       25208 :             if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
     176          84 :                 !has_join_restriction(root, old_rel))
     177          44 :                 continue;
     178             : 
     179       25080 :             if (k == other_level)
     180             :             {
     181             :                 /* only consider remaining rels */
     182       14992 :                 other_rels_list = joinrels[k];
     183       14992 :                 other_rels = lnext(other_rels_list, r);
     184             :             }
     185             :             else
     186             :             {
     187       10088 :                 other_rels_list = joinrels[other_level];
     188       10088 :                 other_rels = list_head(other_rels_list);
     189             :             }
     190             : 
     191      108322 :             for_each_cell(r2, other_rels_list, other_rels)
     192             :             {
     193       83242 :                 RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
     194             : 
     195       83242 :                 if (!bms_overlap(old_rel->relids, new_rel->relids))
     196             :                 {
     197             :                     /*
     198             :                      * OK, we can build a rel of the right level from this
     199             :                      * pair of rels.  Do so if there is at least one relevant
     200             :                      * join clause or join order restriction.
     201             :                      */
     202        7518 :                     if (have_relevant_joinclause(root, old_rel, new_rel) ||
     203         616 :                         have_join_order_restriction(root, old_rel, new_rel))
     204             :                     {
     205        6302 :                         (void) make_join_rel(root, old_rel, new_rel);
     206             :                     }
     207             :                 }
     208             :             }
     209             :         }
     210             :     }
     211             : 
     212             :     /*----------
     213             :      * Last-ditch effort: if we failed to find any usable joins so far, force
     214             :      * a set of cartesian-product joins to be generated.  This handles the
     215             :      * special case where all the available rels have join clauses but we
     216             :      * cannot use any of those clauses yet.  This can only happen when we are
     217             :      * considering a join sub-problem (a sub-joinlist) and all the rels in the
     218             :      * sub-problem have only join clauses with rels outside the sub-problem.
     219             :      * An example is
     220             :      *
     221             :      *      SELECT ... FROM a INNER JOIN b ON TRUE, c, d, ...
     222             :      *      WHERE a.w = c.x and b.y = d.z;
     223             :      *
     224             :      * If the "a INNER JOIN b" sub-problem does not get flattened into the
     225             :      * upper level, we must be willing to make a cartesian join of a and b;
     226             :      * but the code above will not have done so, because it thought that both
     227             :      * a and b have joinclauses.  We consider only left-sided and right-sided
     228             :      * cartesian joins in this case (no bushy).
     229             :      *----------
     230             :      */
     231       59496 :     if (joinrels[level] == NIL)
     232             :     {
     233             :         /*
     234             :          * This loop is just like the first one, except we always call
     235             :          * make_rels_by_clauseless_joins().
     236             :          */
     237          36 :         foreach(r, joinrels[level - 1])
     238             :         {
     239          24 :             RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
     240             : 
     241          24 :             make_rels_by_clauseless_joins(root,
     242             :                                           old_rel,
     243          24 :                                           joinrels[1]);
     244             :         }
     245             : 
     246             :         /*----------
     247             :          * When special joins are involved, there may be no legal way
     248             :          * to make an N-way join for some values of N.  For example consider
     249             :          *
     250             :          * SELECT ... FROM t1 WHERE
     251             :          *   x IN (SELECT ... FROM t2,t3 WHERE ...) AND
     252             :          *   y IN (SELECT ... FROM t4,t5 WHERE ...)
     253             :          *
     254             :          * We will flatten this query to a 5-way join problem, but there are
     255             :          * no 4-way joins that join_is_legal() will consider legal.  We have
     256             :          * to accept failure at level 4 and go on to discover a workable
     257             :          * bushy plan at level 5.
     258             :          *
     259             :          * However, if there are no special joins and no lateral references
     260             :          * then join_is_legal() should never fail, and so the following sanity
     261             :          * check is useful.
     262             :          *----------
     263             :          */
     264          16 :         if (joinrels[level] == NIL &&
     265           4 :             root->join_info_list == NIL &&
     266           0 :             !root->hasLateralRTEs)
     267           0 :             elog(ERROR, "failed to build any %d-way joins", level);
     268             :     }
     269       59496 : }
     270             : 
     271             : /*
     272             :  * make_rels_by_clause_joins
     273             :  *    Build joins between the given relation 'old_rel' and other relations
     274             :  *    that participate in join clauses that 'old_rel' also participates in
     275             :  *    (or participate in join-order restrictions with it).
     276             :  *    The join rels are returned in root->join_rel_level[join_cur_level].
     277             :  *
     278             :  * Note: at levels above 2 we will generate the same joined relation in
     279             :  * multiple ways --- for example (a join b) join c is the same RelOptInfo as
     280             :  * (b join c) join a, though the second case will add a different set of Paths
     281             :  * to it.  This is the reason for using the join_rel_level mechanism, which
     282             :  * automatically ensures that each new joinrel is only added to the list once.
     283             :  *
     284             :  * 'old_rel' is the relation entry for the relation to be joined
     285             :  * 'other_rels_list': a list containing the other
     286             :  * rels to be considered for joining
     287             :  * 'other_rels': the first cell to be considered
     288             :  *
     289             :  * Currently, this is only used with initial rels in other_rels, but it
     290             :  * will work for joining to joinrels too.
     291             :  */
     292             : static void
     293      146234 : make_rels_by_clause_joins(PlannerInfo *root,
     294             :                           RelOptInfo *old_rel,
     295             :                           List *other_rels_list,
     296             :                           ListCell *other_rels)
     297             : {
     298             :     ListCell   *l;
     299             : 
     300      431090 :     for_each_cell(l, other_rels_list, other_rels)
     301             :     {
     302      284856 :         RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
     303             : 
     304      446626 :         if (!bms_overlap(old_rel->relids, other_rel->relids) &&
     305      188442 :             (have_relevant_joinclause(root, old_rel, other_rel) ||
     306       26672 :              have_join_order_restriction(root, old_rel, other_rel)))
     307             :         {
     308      136416 :             (void) make_join_rel(root, old_rel, other_rel);
     309             :         }
     310             :     }
     311      146234 : }
     312             : 
     313             : /*
     314             :  * make_rels_by_clauseless_joins
     315             :  *    Given a relation 'old_rel' and a list of other relations
     316             :  *    'other_rels', create a join relation between 'old_rel' and each
     317             :  *    member of 'other_rels' that isn't already included in 'old_rel'.
     318             :  *    The join rels are returned in root->join_rel_level[join_cur_level].
     319             :  *
     320             :  * 'old_rel' is the relation entry for the relation to be joined
     321             :  * 'other_rels': a list containing the other rels to be considered for joining
     322             :  *
     323             :  * Currently, this is only used with initial rels in other_rels, but it would
     324             :  * work for joining to joinrels too.
     325             :  */
     326             : static void
     327        4402 : make_rels_by_clauseless_joins(PlannerInfo *root,
     328             :                               RelOptInfo *old_rel,
     329             :                               List *other_rels)
     330             : {
     331             :     ListCell   *l;
     332             : 
     333       13720 :     foreach(l, other_rels)
     334             :     {
     335        9318 :         RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
     336             : 
     337        9318 :         if (!bms_overlap(other_rel->relids, old_rel->relids))
     338             :         {
     339        4596 :             (void) make_join_rel(root, old_rel, other_rel);
     340             :         }
     341             :     }
     342        4402 : }
     343             : 
     344             : 
     345             : /*
     346             :  * join_is_legal
     347             :  *     Determine whether a proposed join is legal given the query's
     348             :  *     join order constraints; and if it is, determine the join type.
     349             :  *
     350             :  * Caller must supply not only the two rels, but the union of their relids.
     351             :  * (We could simplify the API by computing joinrelids locally, but this
     352             :  * would be redundant work in the normal path through make_join_rel.)
     353             :  *
     354             :  * On success, *sjinfo_p is set to NULL if this is to be a plain inner join,
     355             :  * else it's set to point to the associated SpecialJoinInfo node.  Also,
     356             :  * *reversed_p is set true if the given relations need to be swapped to
     357             :  * match the SpecialJoinInfo node.
     358             :  */
     359             : static bool
     360      150634 : join_is_legal(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
     361             :               Relids joinrelids,
     362             :               SpecialJoinInfo **sjinfo_p, bool *reversed_p)
     363             : {
     364             :     SpecialJoinInfo *match_sjinfo;
     365             :     bool        reversed;
     366             :     bool        unique_ified;
     367             :     bool        must_be_leftjoin;
     368             :     ListCell   *l;
     369             : 
     370             :     /*
     371             :      * Ensure output params are set on failure return.  This is just to
     372             :      * suppress uninitialized-variable warnings from overly anal compilers.
     373             :      */
     374      150634 :     *sjinfo_p = NULL;
     375      150634 :     *reversed_p = false;
     376             : 
     377             :     /*
     378             :      * If we have any special joins, the proposed join might be illegal; and
     379             :      * in any case we have to determine its join type.  Scan the join info
     380             :      * list for matches and conflicts.
     381             :      */
     382      150634 :     match_sjinfo = NULL;
     383      150634 :     reversed = false;
     384      150634 :     unique_ified = false;
     385      150634 :     must_be_leftjoin = false;
     386             : 
     387      344092 :     foreach(l, root->join_info_list)
     388             :     {
     389      198612 :         SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
     390             : 
     391             :         /*
     392             :          * This special join is not relevant unless its RHS overlaps the
     393             :          * proposed join.  (Check this first as a fast path for dismissing
     394             :          * most irrelevant SJs quickly.)
     395             :          */
     396      198612 :         if (!bms_overlap(sjinfo->min_righthand, joinrelids))
     397       66006 :             continue;
     398             : 
     399             :         /*
     400             :          * Also, not relevant if proposed join is fully contained within RHS
     401             :          * (ie, we're still building up the RHS).
     402             :          */
     403      132606 :         if (bms_is_subset(joinrelids, sjinfo->min_righthand))
     404        2274 :             continue;
     405             : 
     406             :         /*
     407             :          * Also, not relevant if SJ is already done within either input.
     408             :          */
     409      252796 :         if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
     410      122464 :             bms_is_subset(sjinfo->min_righthand, rel1->relids))
     411       55390 :             continue;
     412       79844 :         if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
     413        4902 :             bms_is_subset(sjinfo->min_righthand, rel2->relids))
     414        1974 :             continue;
     415             : 
     416             :         /*
     417             :          * If it's a semijoin and we already joined the RHS to any other rels
     418             :          * within either input, then we must have unique-ified the RHS at that
     419             :          * point (see below).  Therefore the semijoin is no longer relevant in
     420             :          * this join path.
     421             :          */
     422       72968 :         if (sjinfo->jointype == JOIN_SEMI)
     423             :         {
     424        4034 :             if (bms_is_subset(sjinfo->syn_righthand, rel1->relids) &&
     425         672 :                 !bms_equal(sjinfo->syn_righthand, rel1->relids))
     426          12 :                 continue;
     427        4788 :             if (bms_is_subset(sjinfo->syn_righthand, rel2->relids) &&
     428        1438 :                 !bms_equal(sjinfo->syn_righthand, rel2->relids))
     429           4 :                 continue;
     430             :         }
     431             : 
     432             :         /*
     433             :          * If one input contains min_lefthand and the other contains
     434             :          * min_righthand, then we can perform the SJ at this join.
     435             :          *
     436             :          * Reject if we get matches to more than one SJ; that implies we're
     437             :          * considering something that's not really valid.
     438             :          */
     439      140022 :         if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
     440       67070 :             bms_is_subset(sjinfo->min_righthand, rel2->relids))
     441             :         {
     442       63062 :             if (match_sjinfo)
     443        5154 :                 return false;   /* invalid join path */
     444       63062 :             match_sjinfo = sjinfo;
     445       63062 :             reversed = false;
     446             :         }
     447       12814 :         else if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
     448        2924 :                  bms_is_subset(sjinfo->min_righthand, rel1->relids))
     449             :         {
     450        2476 :             if (match_sjinfo)
     451           0 :                 return false;   /* invalid join path */
     452        2476 :             match_sjinfo = sjinfo;
     453        2476 :             reversed = true;
     454             :         }
     455        9098 :         else if (sjinfo->jointype == JOIN_SEMI &&
     456        1912 :                  bms_equal(sjinfo->syn_righthand, rel2->relids) &&
     457         228 :                  create_unique_path(root, rel2, rel2->cheapest_total_path,
     458             :                                     sjinfo) != NULL)
     459             :         {
     460             :             /*----------
     461             :              * For a semijoin, we can join the RHS to anything else by
     462             :              * unique-ifying the RHS (if the RHS can be unique-ified).
     463             :              * We will only get here if we have the full RHS but less
     464             :              * than min_lefthand on the LHS.
     465             :              *
     466             :              * The reason to consider such a join path is exemplified by
     467             :              *  SELECT ... FROM a,b WHERE (a.x,b.y) IN (SELECT c1,c2 FROM c)
     468             :              * If we insist on doing this as a semijoin we will first have
     469             :              * to form the cartesian product of A*B.  But if we unique-ify
     470             :              * C then the semijoin becomes a plain innerjoin and we can join
     471             :              * in any order, eg C to A and then to B.  When C is much smaller
     472             :              * than A and B this can be a huge win.  So we allow C to be
     473             :              * joined to just A or just B here, and then make_join_rel has
     474             :              * to handle the case properly.
     475             :              *
     476             :              * Note that actually we'll allow unique-ified C to be joined to
     477             :              * some other relation D here, too.  That is legal, if usually not
     478             :              * very sane, and this routine is only concerned with legality not
     479             :              * with whether the join is good strategy.
     480             :              *----------
     481             :              */
     482         224 :             if (match_sjinfo)
     483          80 :                 return false;   /* invalid join path */
     484         144 :             match_sjinfo = sjinfo;
     485         144 :             reversed = false;
     486         144 :             unique_ified = true;
     487             :         }
     488        8650 :         else if (sjinfo->jointype == JOIN_SEMI &&
     489        1664 :                  bms_equal(sjinfo->syn_righthand, rel1->relids) &&
     490         204 :                  create_unique_path(root, rel1, rel1->cheapest_total_path,
     491             :                                     sjinfo) != NULL)
     492             :         {
     493             :             /* Reversed semijoin case */
     494         204 :             if (match_sjinfo)
     495          44 :                 return false;   /* invalid join path */
     496         160 :             match_sjinfo = sjinfo;
     497         160 :             reversed = true;
     498         160 :             unique_ified = true;
     499             :         }
     500             :         else
     501             :         {
     502             :             /*
     503             :              * Otherwise, the proposed join overlaps the RHS but isn't a valid
     504             :              * implementation of this SJ.  But don't panic quite yet: the RHS
     505             :              * violation might have occurred previously, in one or both input
     506             :              * relations, in which case we must have previously decided that
     507             :              * it was OK to commute some other SJ with this one.  If we need
     508             :              * to perform this join to finish building up the RHS, rejecting
     509             :              * it could lead to not finding any plan at all.  (This can occur
     510             :              * because of the heuristics elsewhere in this file that postpone
     511             :              * clauseless joins: we might not consider doing a clauseless join
     512             :              * within the RHS until after we've performed other, validly
     513             :              * commutable SJs with one or both sides of the clauseless join.)
     514             :              * This consideration boils down to the rule that if both inputs
     515             :              * overlap the RHS, we can allow the join --- they are either
     516             :              * fully within the RHS, or represent previously-allowed joins to
     517             :              * rels outside it.
     518             :              */
     519        8762 :             if (bms_overlap(rel1->relids, sjinfo->min_righthand) &&
     520        1776 :                 bms_overlap(rel2->relids, sjinfo->min_righthand))
     521          80 :                 continue;       /* assume valid previous violation of RHS */
     522             : 
     523             :             /*
     524             :              * The proposed join could still be legal, but only if we're
     525             :              * allowed to associate it into the RHS of this SJ.  That means
     526             :              * this SJ must be a LEFT join (not SEMI or ANTI, and certainly
     527             :              * not FULL) and the proposed join must not overlap the LHS.
     528             :              */
     529       12460 :             if (sjinfo->jointype != JOIN_LEFT ||
     530        5554 :                 bms_overlap(joinrelids, sjinfo->min_lefthand))
     531        5030 :                 return false;   /* invalid join path */
     532             : 
     533             :             /*
     534             :              * To be valid, the proposed join must be a LEFT join; otherwise
     535             :              * it can't associate into this SJ's RHS.  But we may not yet have
     536             :              * found the SpecialJoinInfo matching the proposed join, so we
     537             :              * can't test that yet.  Remember the requirement for later.
     538             :              */
     539        1876 :             must_be_leftjoin = true;
     540             :         }
     541             :     }
     542             : 
     543             :     /*
     544             :      * Fail if violated any SJ's RHS and didn't match to a LEFT SJ: the
     545             :      * proposed join can't associate into an SJ's RHS.
     546             :      *
     547             :      * Also, fail if the proposed join's predicate isn't strict; we're
     548             :      * essentially checking to see if we can apply outer-join identity 3, and
     549             :      * that's a requirement.  (This check may be redundant with checks in
     550             :      * make_outerjoininfo, but I'm not quite sure, and it's cheap to test.)
     551             :      */
     552      146864 :     if (must_be_leftjoin &&
     553         692 :         (match_sjinfo == NULL ||
     554        1384 :          match_sjinfo->jointype != JOIN_LEFT ||
     555         692 :          !match_sjinfo->lhs_strict))
     556         692 :         return false;           /* invalid join path */
     557             : 
     558             :     /*
     559             :      * We also have to check for constraints imposed by LATERAL references.
     560             :      */
     561      144788 :     if (root->hasLateralRTEs)
     562             :     {
     563             :         bool        lateral_fwd;
     564             :         bool        lateral_rev;
     565             :         Relids      join_lateral_rels;
     566             : 
     567             :         /*
     568             :          * The proposed rels could each contain lateral references to the
     569             :          * other, in which case the join is impossible.  If there are lateral
     570             :          * references in just one direction, then the join has to be done with
     571             :          * a nestloop with the lateral referencer on the inside.  If the join
     572             :          * matches an SJ that cannot be implemented by such a nestloop, the
     573             :          * join is impossible.
     574             :          *
     575             :          * Also, if the lateral reference is only indirect, we should reject
     576             :          * the join; whatever rel(s) the reference chain goes through must be
     577             :          * joined to first.
     578             :          *
     579             :          * Another case that might keep us from building a valid plan is the
     580             :          * implementation restriction described by have_dangerous_phv().
     581             :          */
     582        3088 :         lateral_fwd = bms_overlap(rel1->relids, rel2->lateral_relids);
     583        3088 :         lateral_rev = bms_overlap(rel2->relids, rel1->lateral_relids);
     584        3088 :         if (lateral_fwd && lateral_rev)
     585          12 :             return false;       /* have lateral refs in both directions */
     586        3076 :         if (lateral_fwd)
     587             :         {
     588             :             /* has to be implemented as nestloop with rel1 on left */
     589        1064 :             if (match_sjinfo &&
     590          72 :                 (reversed ||
     591          64 :                  unique_ified ||
     592          64 :                  match_sjinfo->jointype == JOIN_FULL))
     593           8 :                 return false;   /* not implementable as nestloop */
     594             :             /* check there is a direct reference from rel2 to rel1 */
     595        1056 :             if (!bms_overlap(rel1->relids, rel2->direct_lateral_relids))
     596          12 :                 return false;   /* only indirect refs, so reject */
     597             :             /* check we won't have a dangerous PHV */
     598        1044 :             if (have_dangerous_phv(root, rel1->relids, rel2->lateral_relids))
     599          48 :                 return false;   /* might be unable to handle required PHV */
     600             :         }
     601        2012 :         else if (lateral_rev)
     602             :         {
     603             :             /* has to be implemented as nestloop with rel2 on left */
     604         438 :             if (match_sjinfo &&
     605          96 :                 (!reversed ||
     606          48 :                  unique_ified ||
     607          48 :                  match_sjinfo->jointype == JOIN_FULL))
     608           0 :                 return false;   /* not implementable as nestloop */
     609             :             /* check there is a direct reference from rel1 to rel2 */
     610         390 :             if (!bms_overlap(rel2->relids, rel1->direct_lateral_relids))
     611           0 :                 return false;   /* only indirect refs, so reject */
     612             :             /* check we won't have a dangerous PHV */
     613         390 :             if (have_dangerous_phv(root, rel2->relids, rel1->lateral_relids))
     614          56 :                 return false;   /* might be unable to handle required PHV */
     615             :         }
     616             : 
     617             :         /*
     618             :          * LATERAL references could also cause problems later on if we accept
     619             :          * this join: if the join's minimum parameterization includes any rels
     620             :          * that would have to be on the inside of an outer join with this join
     621             :          * rel, then it's never going to be possible to build the complete
     622             :          * query using this join.  We should reject this join not only because
     623             :          * it'll save work, but because if we don't, the clauseless-join
     624             :          * heuristics might think that legality of this join means that some
     625             :          * other join rel need not be formed, and that could lead to failure
     626             :          * to find any plan at all.  We have to consider not only rels that
     627             :          * are directly on the inner side of an OJ with the joinrel, but also
     628             :          * ones that are indirectly so, so search to find all such rels.
     629             :          */
     630        2952 :         join_lateral_rels = min_join_parameterization(root, joinrelids,
     631             :                                                       rel1, rel2);
     632        2952 :         if (join_lateral_rels)
     633             :         {
     634         562 :             Relids      join_plus_rhs = bms_copy(joinrelids);
     635             :             bool        more;
     636             : 
     637             :             do
     638             :             {
     639         690 :                 more = false;
     640        1246 :                 foreach(l, root->join_info_list)
     641             :                 {
     642         556 :                     SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
     643             : 
     644             :                     /* ignore full joins --- their ordering is predetermined */
     645         556 :                     if (sjinfo->jointype == JOIN_FULL)
     646          12 :                         continue;
     647             : 
     648        1004 :                     if (bms_overlap(sjinfo->min_lefthand, join_plus_rhs) &&
     649         460 :                         !bms_is_subset(sjinfo->min_righthand, join_plus_rhs))
     650             :                     {
     651         188 :                         join_plus_rhs = bms_add_members(join_plus_rhs,
     652         188 :                                                         sjinfo->min_righthand);
     653         188 :                         more = true;
     654             :                     }
     655             :                 }
     656         690 :             } while (more);
     657         562 :             if (bms_overlap(join_plus_rhs, join_lateral_rels))
     658         128 :                 return false;   /* will not be able to join to some RHS rel */
     659             :         }
     660             :     }
     661             : 
     662             :     /* Otherwise, it's a valid join */
     663      144524 :     *sjinfo_p = match_sjinfo;
     664      144524 :     *reversed_p = reversed;
     665      144524 :     return true;
     666             : }
     667             : 
     668             : 
     669             : /*
     670             :  * make_join_rel
     671             :  *     Find or create a join RelOptInfo that represents the join of
     672             :  *     the two given rels, and add to it path information for paths
     673             :  *     created with the two rels as outer and inner rel.
     674             :  *     (The join rel may already contain paths generated from other
     675             :  *     pairs of rels that add up to the same set of base rels.)
     676             :  *
     677             :  * NB: will return NULL if attempted join is not valid.  This can happen
     678             :  * when working with outer joins, or with IN or EXISTS clauses that have been
     679             :  * turned into joins.
     680             :  */
     681             : RelOptInfo *
     682      150546 : make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
     683             : {
     684             :     Relids      joinrelids;
     685             :     SpecialJoinInfo *sjinfo;
     686             :     bool        reversed;
     687             :     SpecialJoinInfo sjinfo_data;
     688             :     RelOptInfo *joinrel;
     689             :     List       *restrictlist;
     690             : 
     691             :     /* We should never try to join two overlapping sets of rels. */
     692             :     Assert(!bms_overlap(rel1->relids, rel2->relids));
     693             : 
     694             :     /* Construct Relids set that identifies the joinrel. */
     695      150546 :     joinrelids = bms_union(rel1->relids, rel2->relids);
     696             : 
     697             :     /* Check validity and determine join type. */
     698      150546 :     if (!join_is_legal(root, rel1, rel2, joinrelids,
     699             :                        &sjinfo, &reversed))
     700             :     {
     701             :         /* invalid join path */
     702        6054 :         bms_free(joinrelids);
     703        6054 :         return NULL;
     704             :     }
     705             : 
     706             :     /* Swap rels if needed to match the join info. */
     707      144492 :     if (reversed)
     708             :     {
     709        2476 :         RelOptInfo *trel = rel1;
     710             : 
     711        2476 :         rel1 = rel2;
     712        2476 :         rel2 = trel;
     713             :     }
     714             : 
     715             :     /*
     716             :      * If it's a plain inner join, then we won't have found anything in
     717             :      * join_info_list.  Make up a SpecialJoinInfo so that selectivity
     718             :      * estimation functions will know what's being joined.
     719             :      */
     720      144492 :     if (sjinfo == NULL)
     721             :     {
     722       78962 :         sjinfo = &sjinfo_data;
     723       78962 :         sjinfo->type = T_SpecialJoinInfo;
     724       78962 :         sjinfo->min_lefthand = rel1->relids;
     725       78962 :         sjinfo->min_righthand = rel2->relids;
     726       78962 :         sjinfo->syn_lefthand = rel1->relids;
     727       78962 :         sjinfo->syn_righthand = rel2->relids;
     728       78962 :         sjinfo->jointype = JOIN_INNER;
     729             :         /* we don't bother trying to make the remaining fields valid */
     730       78962 :         sjinfo->lhs_strict = false;
     731       78962 :         sjinfo->delay_upper_joins = false;
     732       78962 :         sjinfo->semi_can_btree = false;
     733       78962 :         sjinfo->semi_can_hash = false;
     734       78962 :         sjinfo->semi_operators = NIL;
     735       78962 :         sjinfo->semi_rhs_exprs = NIL;
     736             :     }
     737             : 
     738             :     /*
     739             :      * Find or build the join RelOptInfo, and compute the restrictlist that
     740             :      * goes with this particular joining.
     741             :      */
     742      144492 :     joinrel = build_join_rel(root, joinrelids, rel1, rel2, sjinfo,
     743             :                              &restrictlist);
     744             : 
     745             :     /*
     746             :      * If we've already proven this join is empty, we needn't consider any
     747             :      * more paths for it.
     748             :      */
     749      144492 :     if (is_dummy_rel(joinrel))
     750             :     {
     751         232 :         bms_free(joinrelids);
     752         232 :         return joinrel;
     753             :     }
     754             : 
     755             :     /* Add paths to the join relation. */
     756      144260 :     populate_joinrel_with_paths(root, rel1, rel2, joinrel, sjinfo,
     757             :                                 restrictlist);
     758             : 
     759      144260 :     bms_free(joinrelids);
     760             : 
     761      144260 :     return joinrel;
     762             : }
     763             : 
     764             : /*
     765             :  * populate_joinrel_with_paths
     766             :  *    Add paths to the given joinrel for given pair of joining relations. The
     767             :  *    SpecialJoinInfo provides details about the join and the restrictlist
     768             :  *    contains the join clauses and the other clauses applicable for given pair
     769             :  *    of the joining relations.
     770             :  */
     771             : static void
     772      145892 : populate_joinrel_with_paths(PlannerInfo *root, RelOptInfo *rel1,
     773             :                             RelOptInfo *rel2, RelOptInfo *joinrel,
     774             :                             SpecialJoinInfo *sjinfo, List *restrictlist)
     775             : {
     776             :     /*
     777             :      * Consider paths using each rel as both outer and inner.  Depending on
     778             :      * the join type, a provably empty outer or inner rel might mean the join
     779             :      * is provably empty too; in which case throw away any previously computed
     780             :      * paths and mark the join as dummy.  (We do it this way since it's
     781             :      * conceivable that dummy-ness of a multi-element join might only be
     782             :      * noticeable for certain construction paths.)
     783             :      *
     784             :      * Also, a provably constant-false join restriction typically means that
     785             :      * we can skip evaluating one or both sides of the join.  We do this by
     786             :      * marking the appropriate rel as dummy.  For outer joins, a
     787             :      * constant-false restriction that is pushed down still means the whole
     788             :      * join is dummy, while a non-pushed-down one means that no inner rows
     789             :      * will join so we can treat the inner rel as dummy.
     790             :      *
     791             :      * We need only consider the jointypes that appear in join_info_list, plus
     792             :      * JOIN_INNER.
     793             :      */
     794      145892 :     switch (sjinfo->jointype)
     795             :     {
     796             :         case JOIN_INNER:
     797      159024 :             if (is_dummy_rel(rel1) || is_dummy_rel(rel2) ||
     798       79506 :                 restriction_is_constant_false(restrictlist, joinrel, false))
     799             :             {
     800          76 :                 mark_dummy_rel(joinrel);
     801          76 :                 break;
     802             :             }
     803       79442 :             add_paths_to_joinrel(root, joinrel, rel1, rel2,
     804             :                                  JOIN_INNER, sjinfo,
     805             :                                  restrictlist);
     806       79442 :             add_paths_to_joinrel(root, joinrel, rel2, rel1,
     807             :                                  JOIN_INNER, sjinfo,
     808             :                                  restrictlist);
     809       79442 :             break;
     810             :         case JOIN_LEFT:
     811      108312 :             if (is_dummy_rel(rel1) ||
     812       54152 :                 restriction_is_constant_false(restrictlist, joinrel, true))
     813             :             {
     814          20 :                 mark_dummy_rel(joinrel);
     815          20 :                 break;
     816             :             }
     817       54148 :             if (restriction_is_constant_false(restrictlist, joinrel, false) &&
     818           8 :                 bms_is_subset(rel2->relids, sjinfo->syn_righthand))
     819           8 :                 mark_dummy_rel(rel2);
     820       54140 :             add_paths_to_joinrel(root, joinrel, rel1, rel2,
     821             :                                  JOIN_LEFT, sjinfo,
     822             :                                  restrictlist);
     823       54140 :             add_paths_to_joinrel(root, joinrel, rel2, rel1,
     824             :                                  JOIN_RIGHT, sjinfo,
     825             :                                  restrictlist);
     826       54140 :             break;
     827             :         case JOIN_FULL:
     828        1296 :             if ((is_dummy_rel(rel1) && is_dummy_rel(rel2)) ||
     829         648 :                 restriction_is_constant_false(restrictlist, joinrel, true))
     830             :             {
     831           0 :                 mark_dummy_rel(joinrel);
     832           0 :                 break;
     833             :             }
     834         648 :             add_paths_to_joinrel(root, joinrel, rel1, rel2,
     835             :                                  JOIN_FULL, sjinfo,
     836             :                                  restrictlist);
     837         648 :             add_paths_to_joinrel(root, joinrel, rel2, rel1,
     838             :                                  JOIN_FULL, sjinfo,
     839             :                                  restrictlist);
     840             : 
     841             :             /*
     842             :              * If there are join quals that aren't mergeable or hashable, we
     843             :              * may not be able to build any valid plan.  Complain here so that
     844             :              * we can give a somewhat-useful error message.  (Since we have no
     845             :              * flexibility of planning for a full join, there's no chance of
     846             :              * succeeding later with another pair of input rels.)
     847             :              */
     848         648 :             if (joinrel->pathlist == NIL)
     849           0 :                 ereport(ERROR,
     850             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     851             :                          errmsg("FULL JOIN is only supported with merge-joinable or hash-joinable join conditions")));
     852         648 :             break;
     853             :         case JOIN_SEMI:
     854             : 
     855             :             /*
     856             :              * We might have a normal semijoin, or a case where we don't have
     857             :              * enough rels to do the semijoin but can unique-ify the RHS and
     858             :              * then do an innerjoin (see comments in join_is_legal).  In the
     859             :              * latter case we can't apply JOIN_SEMI joining.
     860             :              */
     861        3624 :             if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
     862        1806 :                 bms_is_subset(sjinfo->min_righthand, rel2->relids))
     863             :             {
     864        3608 :                 if (is_dummy_rel(rel1) || is_dummy_rel(rel2) ||
     865        1802 :                     restriction_is_constant_false(restrictlist, joinrel, false))
     866             :                 {
     867           8 :                     mark_dummy_rel(joinrel);
     868           8 :                     break;
     869             :                 }
     870        1798 :                 add_paths_to_joinrel(root, joinrel, rel1, rel2,
     871             :                                      JOIN_SEMI, sjinfo,
     872             :                                      restrictlist);
     873             :             }
     874             : 
     875             :             /*
     876             :              * If we know how to unique-ify the RHS and one input rel is
     877             :              * exactly the RHS (not a superset) we can consider unique-ifying
     878             :              * it and then doing a regular join.  (The create_unique_path
     879             :              * check here is probably redundant with what join_is_legal did,
     880             :              * but if so the check is cheap because it's cached.  So test
     881             :              * anyway to be sure.)
     882             :              */
     883        3620 :             if (bms_equal(sjinfo->syn_righthand, rel2->relids) &&
     884        1810 :                 create_unique_path(root, rel2, rel2->cheapest_total_path,
     885             :                                    sjinfo) != NULL)
     886             :             {
     887        3504 :                 if (is_dummy_rel(rel1) || is_dummy_rel(rel2) ||
     888        1752 :                     restriction_is_constant_false(restrictlist, joinrel, false))
     889             :                 {
     890           0 :                     mark_dummy_rel(joinrel);
     891           0 :                     break;
     892             :                 }
     893        1752 :                 add_paths_to_joinrel(root, joinrel, rel1, rel2,
     894             :                                      JOIN_UNIQUE_INNER, sjinfo,
     895             :                                      restrictlist);
     896        1752 :                 add_paths_to_joinrel(root, joinrel, rel2, rel1,
     897             :                                      JOIN_UNIQUE_OUTER, sjinfo,
     898             :                                      restrictlist);
     899             :             }
     900        1810 :             break;
     901             :         case JOIN_ANTI:
     902       19496 :             if (is_dummy_rel(rel1) ||
     903        9748 :                 restriction_is_constant_false(restrictlist, joinrel, true))
     904             :             {
     905           0 :                 mark_dummy_rel(joinrel);
     906           0 :                 break;
     907             :             }
     908        9748 :             if (restriction_is_constant_false(restrictlist, joinrel, false) &&
     909           0 :                 bms_is_subset(rel2->relids, sjinfo->syn_righthand))
     910           0 :                 mark_dummy_rel(rel2);
     911        9748 :             add_paths_to_joinrel(root, joinrel, rel1, rel2,
     912             :                                  JOIN_ANTI, sjinfo,
     913             :                                  restrictlist);
     914        9748 :             break;
     915             :         default:
     916             :             /* other values not expected here */
     917           0 :             elog(ERROR, "unrecognized join type: %d", (int) sjinfo->jointype);
     918             :             break;
     919             :     }
     920             : 
     921             :     /* Apply partitionwise join technique, if possible. */
     922      145892 :     try_partitionwise_join(root, rel1, rel2, joinrel, sjinfo, restrictlist);
     923      145892 : }
     924             : 
     925             : 
     926             : /*
     927             :  * have_join_order_restriction
     928             :  *      Detect whether the two relations should be joined to satisfy
     929             :  *      a join-order restriction arising from special or lateral joins.
     930             :  *
     931             :  * In practice this is always used with have_relevant_joinclause(), and so
     932             :  * could be merged with that function, but it seems clearer to separate the
     933             :  * two concerns.  We need this test because there are degenerate cases where
     934             :  * a clauseless join must be performed to satisfy join-order restrictions.
     935             :  * Also, if one rel has a lateral reference to the other, or both are needed
     936             :  * to compute some PHV, we should consider joining them even if the join would
     937             :  * be clauseless.
     938             :  *
     939             :  * Note: this is only a problem if one side of a degenerate outer join
     940             :  * contains multiple rels, or a clauseless join is required within an
     941             :  * IN/EXISTS RHS; else we will find a join path via the "last ditch" case in
     942             :  * join_search_one_level().  We could dispense with this test if we were
     943             :  * willing to try bushy plans in the "last ditch" case, but that seems much
     944             :  * less efficient.
     945             :  */
     946             : bool
     947       28520 : have_join_order_restriction(PlannerInfo *root,
     948             :                             RelOptInfo *rel1, RelOptInfo *rel2)
     949             : {
     950       28520 :     bool        result = false;
     951             :     ListCell   *l;
     952             : 
     953             :     /*
     954             :      * If either side has a direct lateral reference to the other, attempt the
     955             :      * join regardless of outer-join considerations.
     956             :      */
     957       56166 :     if (bms_overlap(rel1->relids, rel2->direct_lateral_relids) ||
     958       27646 :         bms_overlap(rel2->relids, rel1->direct_lateral_relids))
     959        1084 :         return true;
     960             : 
     961             :     /*
     962             :      * Likewise, if both rels are needed to compute some PlaceHolderVar,
     963             :      * attempt the join regardless of outer-join considerations.  (This is not
     964             :      * very desirable, because a PHV with a large eval_at set will cause a lot
     965             :      * of probably-useless joins to be considered, but failing to do this can
     966             :      * cause us to fail to construct a plan at all.)
     967             :      */
     968       28164 :     foreach(l, root->placeholder_list)
     969             :     {
     970         760 :         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
     971             : 
     972         932 :         if (bms_is_subset(rel1->relids, phinfo->ph_eval_at) &&
     973         172 :             bms_is_subset(rel2->relids, phinfo->ph_eval_at))
     974          32 :             return true;
     975             :     }
     976             : 
     977             :     /*
     978             :      * It's possible that the rels correspond to the left and right sides of a
     979             :      * degenerate outer join, that is, one with no joinclause mentioning the
     980             :      * non-nullable side; in which case we should force the join to occur.
     981             :      *
     982             :      * Also, the two rels could represent a clauseless join that has to be
     983             :      * completed to build up the LHS or RHS of an outer join.
     984             :      */
     985       77150 :     foreach(l, root->join_info_list)
     986             :     {
     987       49996 :         SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
     988             : 
     989             :         /* ignore full joins --- other mechanisms handle them */
     990       49996 :         if (sjinfo->jointype == JOIN_FULL)
     991           8 :             continue;
     992             : 
     993             :         /* Can we perform the SJ with these rels? */
     994       57732 :         if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
     995        7744 :             bms_is_subset(sjinfo->min_righthand, rel2->relids))
     996             :         {
     997         158 :             result = true;
     998         158 :             break;
     999             :         }
    1000       51600 :         if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
    1001        1770 :             bms_is_subset(sjinfo->min_righthand, rel1->relids))
    1002             :         {
    1003          36 :             result = true;
    1004          36 :             break;
    1005             :         }
    1006             : 
    1007             :         /*
    1008             :          * Might we need to join these rels to complete the RHS?  We have to
    1009             :          * use "overlap" tests since either rel might include a lower SJ that
    1010             :          * has been proven to commute with this one.
    1011             :          */
    1012       58440 :         if (bms_overlap(sjinfo->min_righthand, rel1->relids) &&
    1013        8646 :             bms_overlap(sjinfo->min_righthand, rel2->relids))
    1014             :         {
    1015          44 :             result = true;
    1016          44 :             break;
    1017             :         }
    1018             : 
    1019             :         /* Likewise for the LHS. */
    1020       59092 :         if (bms_overlap(sjinfo->min_lefthand, rel1->relids) &&
    1021        9342 :             bms_overlap(sjinfo->min_lefthand, rel2->relids))
    1022             :         {
    1023          12 :             result = true;
    1024          12 :             break;
    1025             :         }
    1026             :     }
    1027             : 
    1028             :     /*
    1029             :      * We do not force the join to occur if either input rel can legally be
    1030             :      * joined to anything else using joinclauses.  This essentially means that
    1031             :      * clauseless bushy joins are put off as long as possible. The reason is
    1032             :      * that when there is a join order restriction high up in the join tree
    1033             :      * (that is, with many rels inside the LHS or RHS), we would otherwise
    1034             :      * expend lots of effort considering very stupid join combinations within
    1035             :      * its LHS or RHS.
    1036             :      */
    1037       27404 :     if (result)
    1038             :     {
    1039         484 :         if (has_legal_joinclause(root, rel1) ||
    1040         234 :             has_legal_joinclause(root, rel2))
    1041          32 :             result = false;
    1042             :     }
    1043             : 
    1044       27404 :     return result;
    1045             : }
    1046             : 
    1047             : 
    1048             : /*
    1049             :  * has_join_restriction
    1050             :  *      Detect whether the specified relation has join-order restrictions,
    1051             :  *      due to being inside an outer join or an IN (sub-SELECT),
    1052             :  *      or participating in any LATERAL references or multi-rel PHVs.
    1053             :  *
    1054             :  * Essentially, this tests whether have_join_order_restriction() could
    1055             :  * succeed with this rel and some other one.  It's OK if we sometimes
    1056             :  * say "true" incorrectly.  (Therefore, we don't bother with the relatively
    1057             :  * expensive has_legal_joinclause test.)
    1058             :  */
    1059             : static bool
    1060        6050 : has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
    1061             : {
    1062             :     ListCell   *l;
    1063             : 
    1064        6050 :     if (rel->lateral_relids != NULL || rel->lateral_referencers != NULL)
    1065        1214 :         return true;
    1066             : 
    1067        5032 :     foreach(l, root->placeholder_list)
    1068             :     {
    1069         220 :         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
    1070             : 
    1071         264 :         if (bms_is_subset(rel->relids, phinfo->ph_eval_at) &&
    1072          44 :             !bms_equal(rel->relids, phinfo->ph_eval_at))
    1073          24 :             return true;
    1074             :     }
    1075             : 
    1076        4996 :     foreach(l, root->join_info_list)
    1077             :     {
    1078         574 :         SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
    1079             : 
    1080             :         /* ignore full joins --- other mechanisms preserve their ordering */
    1081         574 :         if (sjinfo->jointype == JOIN_FULL)
    1082          44 :             continue;
    1083             : 
    1084             :         /* ignore if SJ is already contained in rel */
    1085         790 :         if (bms_is_subset(sjinfo->min_lefthand, rel->relids) &&
    1086         260 :             bms_is_subset(sjinfo->min_righthand, rel->relids))
    1087          98 :             continue;
    1088             : 
    1089             :         /* restricted if it overlaps LHS or RHS, but doesn't contain SJ */
    1090         694 :         if (bms_overlap(sjinfo->min_lefthand, rel->relids) ||
    1091         262 :             bms_overlap(sjinfo->min_righthand, rel->relids))
    1092         390 :             return true;
    1093             :     }
    1094             : 
    1095        4422 :     return false;
    1096             : }
    1097             : 
    1098             : 
    1099             : /*
    1100             :  * has_legal_joinclause
    1101             :  *      Detect whether the specified relation can legally be joined
    1102             :  *      to any other rels using join clauses.
    1103             :  *
    1104             :  * We consider only joins to single other relations in the current
    1105             :  * initial_rels list.  This is sufficient to get a "true" result in most real
    1106             :  * queries, and an occasional erroneous "false" will only cost a bit more
    1107             :  * planning time.  The reason for this limitation is that considering joins to
    1108             :  * other joins would require proving that the other join rel can legally be
    1109             :  * formed, which seems like too much trouble for something that's only a
    1110             :  * heuristic to save planning time.  (Note: we must look at initial_rels
    1111             :  * and not all of the query, since when we are planning a sub-joinlist we
    1112             :  * may be forced to make clauseless joins within initial_rels even though
    1113             :  * there are join clauses linking to other parts of the query.)
    1114             :  */
    1115             : static bool
    1116         484 : has_legal_joinclause(PlannerInfo *root, RelOptInfo *rel)
    1117             : {
    1118             :     ListCell   *lc;
    1119             : 
    1120        1856 :     foreach(lc, root->initial_rels)
    1121             :     {
    1122        1404 :         RelOptInfo *rel2 = (RelOptInfo *) lfirst(lc);
    1123             : 
    1124             :         /* ignore rels that are already in "rel" */
    1125        1404 :         if (bms_overlap(rel->relids, rel2->relids))
    1126         562 :             continue;
    1127             : 
    1128         842 :         if (have_relevant_joinclause(root, rel, rel2))
    1129             :         {
    1130             :             Relids      joinrelids;
    1131             :             SpecialJoinInfo *sjinfo;
    1132             :             bool        reversed;
    1133             : 
    1134             :             /* join_is_legal needs relids of the union */
    1135          88 :             joinrelids = bms_union(rel->relids, rel2->relids);
    1136             : 
    1137          88 :             if (join_is_legal(root, rel, rel2, joinrelids,
    1138             :                               &sjinfo, &reversed))
    1139             :             {
    1140             :                 /* Yes, this will work */
    1141          32 :                 bms_free(joinrelids);
    1142          32 :                 return true;
    1143             :             }
    1144             : 
    1145          56 :             bms_free(joinrelids);
    1146             :         }
    1147             :     }
    1148             : 
    1149         452 :     return false;
    1150             : }
    1151             : 
    1152             : 
    1153             : /*
    1154             :  * There's a pitfall for creating parameterized nestloops: suppose the inner
    1155             :  * rel (call it A) has a parameter that is a PlaceHolderVar, and that PHV's
    1156             :  * minimum eval_at set includes the outer rel (B) and some third rel (C).
    1157             :  * We might think we could create a B/A nestloop join that's parameterized by
    1158             :  * C.  But we would end up with a plan in which the PHV's expression has to be
    1159             :  * evaluated as a nestloop parameter at the B/A join; and the executor is only
    1160             :  * set up to handle simple Vars as NestLoopParams.  Rather than add complexity
    1161             :  * and overhead to the executor for such corner cases, it seems better to
    1162             :  * forbid the join.  (Note that we can still make use of A's parameterized
    1163             :  * path with pre-joined B+C as the outer rel.  have_join_order_restriction()
    1164             :  * ensures that we will consider making such a join even if there are not
    1165             :  * other reasons to do so.)
    1166             :  *
    1167             :  * So we check whether any PHVs used in the query could pose such a hazard.
    1168             :  * We don't have any simple way of checking whether a risky PHV would actually
    1169             :  * be used in the inner plan, and the case is so unusual that it doesn't seem
    1170             :  * worth working very hard on it.
    1171             :  *
    1172             :  * This needs to be checked in two places.  If the inner rel's minimum
    1173             :  * parameterization would trigger the restriction, then join_is_legal() should
    1174             :  * reject the join altogether, because there will be no workable paths for it.
    1175             :  * But joinpath.c has to check again for every proposed nestloop path, because
    1176             :  * the inner path might have more than the minimum parameterization, causing
    1177             :  * some PHV to be dangerous for it that otherwise wouldn't be.
    1178             :  */
    1179             : bool
    1180        9374 : have_dangerous_phv(PlannerInfo *root,
    1181             :                    Relids outer_relids, Relids inner_params)
    1182             : {
    1183             :     ListCell   *lc;
    1184             : 
    1185       10758 :     foreach(lc, root->placeholder_list)
    1186             :     {
    1187        1552 :         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
    1188             : 
    1189        1552 :         if (!bms_is_subset(phinfo->ph_eval_at, inner_params))
    1190        1144 :             continue;           /* ignore, could not be a nestloop param */
    1191         408 :         if (!bms_overlap(phinfo->ph_eval_at, outer_relids))
    1192          88 :             continue;           /* ignore, not relevant to this join */
    1193         320 :         if (bms_is_subset(phinfo->ph_eval_at, outer_relids))
    1194         152 :             continue;           /* safe, it can be eval'd within outerrel */
    1195             :         /* Otherwise, it's potentially unsafe, so reject the join */
    1196         168 :         return true;
    1197             :     }
    1198             : 
    1199             :     /* OK to perform the join */
    1200        9206 :     return false;
    1201             : }
    1202             : 
    1203             : 
    1204             : /*
    1205             :  * is_dummy_rel --- has relation been proven empty?
    1206             :  */
    1207             : bool
    1208     1189256 : is_dummy_rel(RelOptInfo *rel)
    1209             : {
    1210             :     Path       *path;
    1211             : 
    1212             :     /*
    1213             :      * A rel that is known dummy will have just one path that is a childless
    1214             :      * Append.  (Even if somehow it has more paths, a childless Append will
    1215             :      * have cost zero and hence should be at the front of the pathlist.)
    1216             :      */
    1217     1189256 :     if (rel->pathlist == NIL)
    1218      714700 :         return false;
    1219      474556 :     path = (Path *) linitial(rel->pathlist);
    1220             : 
    1221             :     /*
    1222             :      * Initially, a dummy path will just be a childless Append.  But in later
    1223             :      * planning stages we might stick a ProjectSetPath and/or ProjectionPath
    1224             :      * on top, since Append can't project.  Rather than make assumptions about
    1225             :      * which combinations can occur, just descend through whatever we find.
    1226             :      */
    1227             :     for (;;)
    1228             :     {
    1229      498920 :         if (IsA(path, ProjectionPath))
    1230        9966 :             path = ((ProjectionPath *) path)->subpath;
    1231      476772 :         else if (IsA(path, ProjectSetPath))
    1232        2216 :             path = ((ProjectSetPath *) path)->subpath;
    1233             :         else
    1234      474556 :             break;
    1235             :     }
    1236      474556 :     if (IS_DUMMY_APPEND(path))
    1237        2020 :         return true;
    1238      472536 :     return false;
    1239             : }
    1240             : 
    1241             : /*
    1242             :  * Mark a relation as proven empty.
    1243             :  *
    1244             :  * During GEQO planning, this can get invoked more than once on the same
    1245             :  * baserel struct, so it's worth checking to see if the rel is already marked
    1246             :  * dummy.
    1247             :  *
    1248             :  * Also, when called during GEQO join planning, we are in a short-lived
    1249             :  * memory context.  We must make sure that the dummy path attached to a
    1250             :  * baserel survives the GEQO cycle, else the baserel is trashed for future
    1251             :  * GEQO cycles.  On the other hand, when we are marking a joinrel during GEQO,
    1252             :  * we don't want the dummy path to clutter the main planning context.  Upshot
    1253             :  * is that the best solution is to explicitly make the dummy path in the same
    1254             :  * context the given RelOptInfo is in.
    1255             :  */
    1256             : void
    1257         164 : mark_dummy_rel(RelOptInfo *rel)
    1258             : {
    1259             :     MemoryContext oldcontext;
    1260             : 
    1261             :     /* Already marked? */
    1262         164 :     if (is_dummy_rel(rel))
    1263           0 :         return;
    1264             : 
    1265             :     /* No, so choose correct context to make the dummy path in */
    1266         164 :     oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
    1267             : 
    1268             :     /* Set dummy size estimate */
    1269         164 :     rel->rows = 0;
    1270             : 
    1271             :     /* Evict any previously chosen paths */
    1272         164 :     rel->pathlist = NIL;
    1273         164 :     rel->partial_pathlist = NIL;
    1274             : 
    1275             :     /* Set up the dummy path */
    1276         164 :     add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
    1277             :                                               NIL, rel->lateral_relids,
    1278             :                                               0, false, NIL, -1));
    1279             : 
    1280             :     /* Set or update cheapest_total_path and related fields */
    1281         164 :     set_cheapest(rel);
    1282             : 
    1283         164 :     MemoryContextSwitchTo(oldcontext);
    1284             : }
    1285             : 
    1286             : 
    1287             : /*
    1288             :  * restriction_is_constant_false --- is a restrictlist just FALSE?
    1289             :  *
    1290             :  * In cases where a qual is provably constant FALSE, eval_const_expressions
    1291             :  * will generally have thrown away anything that's ANDed with it.  In outer
    1292             :  * join situations this will leave us computing cartesian products only to
    1293             :  * decide there's no match for an outer row, which is pretty stupid.  So,
    1294             :  * we need to detect the case.
    1295             :  *
    1296             :  * If only_pushed_down is true, then consider only quals that are pushed-down
    1297             :  * from the point of view of the joinrel.
    1298             :  */
    1299             : static bool
    1300      211496 : restriction_is_constant_false(List *restrictlist,
    1301             :                               RelOptInfo *joinrel,
    1302             :                               bool only_pushed_down)
    1303             : {
    1304             :     ListCell   *lc;
    1305             : 
    1306             :     /*
    1307             :      * Despite the above comment, the restriction list we see here might
    1308             :      * possibly have other members besides the FALSE constant, since other
    1309             :      * quals could get "pushed down" to the outer join level.  So we check
    1310             :      * each member of the list.
    1311             :      */
    1312      465306 :     foreach(lc, restrictlist)
    1313             :     {
    1314      253898 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    1315             : 
    1316      253898 :         if (only_pushed_down && !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
    1317       86474 :             continue;
    1318             : 
    1319      167424 :         if (rinfo->clause && IsA(rinfo->clause, Const))
    1320             :         {
    1321          88 :             Const      *con = (Const *) rinfo->clause;
    1322             : 
    1323             :             /* constant NULL is as good as constant FALSE for our purposes */
    1324          88 :             if (con->constisnull)
    1325          88 :                 return true;
    1326          88 :             if (!DatumGetBool(con->constvalue))
    1327          88 :                 return true;
    1328             :         }
    1329             :     }
    1330      211408 :     return false;
    1331             : }
    1332             : 
    1333             : /*
    1334             :  * Assess whether join between given two partitioned relations can be broken
    1335             :  * down into joins between matching partitions; a technique called
    1336             :  * "partitionwise join"
    1337             :  *
    1338             :  * Partitionwise join is possible when a. Joining relations have same
    1339             :  * partitioning scheme b. There exists an equi-join between the partition keys
    1340             :  * of the two relations.
    1341             :  *
    1342             :  * Partitionwise join is planned as follows (details: optimizer/README.)
    1343             :  *
    1344             :  * 1. Create the RelOptInfos for joins between matching partitions i.e
    1345             :  * child-joins and add paths to them.
    1346             :  *
    1347             :  * 2. Construct Append or MergeAppend paths across the set of child joins.
    1348             :  * This second phase is implemented by generate_partitionwise_join_paths().
    1349             :  *
    1350             :  * The RelOptInfo, SpecialJoinInfo and restrictlist for each child join are
    1351             :  * obtained by translating the respective parent join structures.
    1352             :  */
    1353             : static void
    1354      145892 : try_partitionwise_join(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
    1355             :                        RelOptInfo *joinrel, SpecialJoinInfo *parent_sjinfo,
    1356             :                        List *parent_restrictlist)
    1357             : {
    1358      145892 :     bool        rel1_is_simple = IS_SIMPLE_REL(rel1);
    1359      145892 :     bool        rel2_is_simple = IS_SIMPLE_REL(rel2);
    1360             :     int         nparts;
    1361             :     int         cnt_parts;
    1362             : 
    1363             :     /* Guard against stack overflow due to overly deep partition hierarchy. */
    1364      145892 :     check_stack_depth();
    1365             : 
    1366             :     /* Nothing to do, if the join relation is not partitioned. */
    1367      145892 :     if (!IS_PARTITIONED_REL(joinrel))
    1368      145276 :         return;
    1369             : 
    1370             :     /* The join relation should have consider_partitionwise_join set. */
    1371             :     Assert(joinrel->consider_partitionwise_join);
    1372             : 
    1373             :     /*
    1374             :      * Since this join relation is partitioned, all the base relations
    1375             :      * participating in this join must be partitioned and so are all the
    1376             :      * intermediate join relations.
    1377             :      */
    1378             :     Assert(IS_PARTITIONED_REL(rel1) && IS_PARTITIONED_REL(rel2));
    1379             :     Assert(REL_HAS_ALL_PART_PROPS(rel1) && REL_HAS_ALL_PART_PROPS(rel2));
    1380             : 
    1381             :     /* The joining relations should have consider_partitionwise_join set. */
    1382             :     Assert(rel1->consider_partitionwise_join &&
    1383             :            rel2->consider_partitionwise_join);
    1384             : 
    1385             :     /*
    1386             :      * The partition scheme of the join relation should match that of the
    1387             :      * joining relations.
    1388             :      */
    1389             :     Assert(joinrel->part_scheme == rel1->part_scheme &&
    1390             :            joinrel->part_scheme == rel2->part_scheme);
    1391             : 
    1392             :     /*
    1393             :      * Since we allow partitionwise join only when the partition bounds of the
    1394             :      * joining relations exactly match, the partition bounds of the join
    1395             :      * should match those of the joining relations.
    1396             :      */
    1397             :     Assert(partition_bounds_equal(joinrel->part_scheme->partnatts,
    1398             :                                   joinrel->part_scheme->parttyplen,
    1399             :                                   joinrel->part_scheme->parttypbyval,
    1400             :                                   joinrel->boundinfo, rel1->boundinfo));
    1401             :     Assert(partition_bounds_equal(joinrel->part_scheme->partnatts,
    1402             :                                   joinrel->part_scheme->parttyplen,
    1403             :                                   joinrel->part_scheme->parttypbyval,
    1404             :                                   joinrel->boundinfo, rel2->boundinfo));
    1405             : 
    1406         616 :     nparts = joinrel->nparts;
    1407             : 
    1408             :     /*
    1409             :      * Create child-join relations for this partitioned join, if those don't
    1410             :      * exist. Add paths to child-joins for a pair of child relations
    1411             :      * corresponding to the given pair of parent relations.
    1412             :      */
    1413        2268 :     for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
    1414             :     {
    1415        1692 :         RelOptInfo *child_rel1 = rel1->part_rels[cnt_parts];
    1416        1692 :         RelOptInfo *child_rel2 = rel2->part_rels[cnt_parts];
    1417        3372 :         bool        rel1_empty = (child_rel1 == NULL ||
    1418        1680 :                                   IS_DUMMY_REL(child_rel1));
    1419        3336 :         bool        rel2_empty = (child_rel2 == NULL ||
    1420        1644 :                                   IS_DUMMY_REL(child_rel2));
    1421             :         SpecialJoinInfo *child_sjinfo;
    1422             :         List       *child_restrictlist;
    1423             :         RelOptInfo *child_joinrel;
    1424             :         Relids      child_joinrelids;
    1425             :         AppendRelInfo **appinfos;
    1426             :         int         nappinfos;
    1427             : 
    1428             :         /*
    1429             :          * Check for cases where we can prove that this segment of the join
    1430             :          * returns no rows, due to one or both inputs being empty (including
    1431             :          * inputs that have been pruned away entirely).  If so just ignore it.
    1432             :          * These rules are equivalent to populate_joinrel_with_paths's rules
    1433             :          * for dummy input relations.
    1434             :          */
    1435        1692 :         switch (parent_sjinfo->jointype)
    1436             :         {
    1437             :             case JOIN_INNER:
    1438             :             case JOIN_SEMI:
    1439         948 :                 if (rel1_empty || rel2_empty)
    1440          36 :                     continue;   /* ignore this join segment */
    1441         932 :                 break;
    1442             :             case JOIN_LEFT:
    1443             :             case JOIN_ANTI:
    1444         560 :                 if (rel1_empty)
    1445           4 :                     continue;   /* ignore this join segment */
    1446         556 :                 break;
    1447             :             case JOIN_FULL:
    1448         184 :                 if (rel1_empty && rel2_empty)
    1449           0 :                     continue;   /* ignore this join segment */
    1450         184 :                 break;
    1451             :             default:
    1452             :                 /* other values not expected here */
    1453           0 :                 elog(ERROR, "unrecognized join type: %d",
    1454             :                      (int) parent_sjinfo->jointype);
    1455             :                 break;
    1456             :         }
    1457             : 
    1458             :         /*
    1459             :          * If a child has been pruned entirely then we can't generate paths
    1460             :          * for it, so we have to reject partitionwise joining unless we were
    1461             :          * able to eliminate this partition above.
    1462             :          */
    1463        1672 :         if (child_rel1 == NULL || child_rel2 == NULL)
    1464             :         {
    1465             :             /*
    1466             :              * Mark the joinrel as unpartitioned so that later functions treat
    1467             :              * it correctly.
    1468             :              */
    1469          40 :             joinrel->nparts = 0;
    1470          80 :             return;
    1471             :         }
    1472             : 
    1473             :         /*
    1474             :          * If a leaf relation has consider_partitionwise_join=false, it means
    1475             :          * that it's a dummy relation for which we skipped setting up tlist
    1476             :          * expressions and adding EC members in set_append_rel_size(), so
    1477             :          * again we have to fail here.
    1478             :          */
    1479        1632 :         if (rel1_is_simple && !child_rel1->consider_partitionwise_join)
    1480             :         {
    1481             :             Assert(child_rel1->reloptkind == RELOPT_OTHER_MEMBER_REL);
    1482             :             Assert(IS_DUMMY_REL(child_rel1));
    1483           0 :             joinrel->nparts = 0;
    1484           0 :             return;
    1485             :         }
    1486        1632 :         if (rel2_is_simple && !child_rel2->consider_partitionwise_join)
    1487             :         {
    1488             :             Assert(child_rel2->reloptkind == RELOPT_OTHER_MEMBER_REL);
    1489             :             Assert(IS_DUMMY_REL(child_rel2));
    1490           0 :             joinrel->nparts = 0;
    1491           0 :             return;
    1492             :         }
    1493             : 
    1494             :         /* We should never try to join two overlapping sets of rels. */
    1495             :         Assert(!bms_overlap(child_rel1->relids, child_rel2->relids));
    1496        1632 :         child_joinrelids = bms_union(child_rel1->relids, child_rel2->relids);
    1497        1632 :         appinfos = find_appinfos_by_relids(root, child_joinrelids, &nappinfos);
    1498             : 
    1499             :         /*
    1500             :          * Construct SpecialJoinInfo from parent join relations's
    1501             :          * SpecialJoinInfo.
    1502             :          */
    1503        1632 :         child_sjinfo = build_child_join_sjinfo(root, parent_sjinfo,
    1504             :                                                child_rel1->relids,
    1505             :                                                child_rel2->relids);
    1506             : 
    1507             :         /*
    1508             :          * Construct restrictions applicable to the child join from those
    1509             :          * applicable to the parent join.
    1510             :          */
    1511        1632 :         child_restrictlist =
    1512        1632 :             (List *) adjust_appendrel_attrs(root,
    1513             :                                             (Node *) parent_restrictlist,
    1514             :                                             nappinfos, appinfos);
    1515        1632 :         pfree(appinfos);
    1516             : 
    1517        1632 :         child_joinrel = joinrel->part_rels[cnt_parts];
    1518        1632 :         if (!child_joinrel)
    1519             :         {
    1520        1400 :             child_joinrel = build_child_join_rel(root, child_rel1, child_rel2,
    1521             :                                                  joinrel, child_restrictlist,
    1522             :                                                  child_sjinfo,
    1523             :                                                  child_sjinfo->jointype);
    1524        1400 :             joinrel->part_rels[cnt_parts] = child_joinrel;
    1525             :         }
    1526             : 
    1527             :         Assert(bms_equal(child_joinrel->relids, child_joinrelids));
    1528             : 
    1529        1632 :         populate_joinrel_with_paths(root, child_rel1, child_rel2,
    1530             :                                     child_joinrel, child_sjinfo,
    1531             :                                     child_restrictlist);
    1532             :     }
    1533             : }
    1534             : 
    1535             : /*
    1536             :  * Construct the SpecialJoinInfo for a child-join by translating
    1537             :  * SpecialJoinInfo for the join between parents. left_relids and right_relids
    1538             :  * are the relids of left and right side of the join respectively.
    1539             :  */
    1540             : static SpecialJoinInfo *
    1541        1632 : build_child_join_sjinfo(PlannerInfo *root, SpecialJoinInfo *parent_sjinfo,
    1542             :                         Relids left_relids, Relids right_relids)
    1543             : {
    1544        1632 :     SpecialJoinInfo *sjinfo = makeNode(SpecialJoinInfo);
    1545             :     AppendRelInfo **left_appinfos;
    1546             :     int         left_nappinfos;
    1547             :     AppendRelInfo **right_appinfos;
    1548             :     int         right_nappinfos;
    1549             : 
    1550        1632 :     memcpy(sjinfo, parent_sjinfo, sizeof(SpecialJoinInfo));
    1551        1632 :     left_appinfos = find_appinfos_by_relids(root, left_relids,
    1552             :                                             &left_nappinfos);
    1553        1632 :     right_appinfos = find_appinfos_by_relids(root, right_relids,
    1554             :                                              &right_nappinfos);
    1555             : 
    1556        1632 :     sjinfo->min_lefthand = adjust_child_relids(sjinfo->min_lefthand,
    1557             :                                                left_nappinfos, left_appinfos);
    1558        1632 :     sjinfo->min_righthand = adjust_child_relids(sjinfo->min_righthand,
    1559             :                                                 right_nappinfos,
    1560             :                                                 right_appinfos);
    1561        1632 :     sjinfo->syn_lefthand = adjust_child_relids(sjinfo->syn_lefthand,
    1562             :                                                left_nappinfos, left_appinfos);
    1563        1632 :     sjinfo->syn_righthand = adjust_child_relids(sjinfo->syn_righthand,
    1564             :                                                 right_nappinfos,
    1565             :                                                 right_appinfos);
    1566        3264 :     sjinfo->semi_rhs_exprs = (List *) adjust_appendrel_attrs(root,
    1567        1632 :                                                              (Node *) sjinfo->semi_rhs_exprs,
    1568             :                                                              right_nappinfos,
    1569             :                                                              right_appinfos);
    1570             : 
    1571        1632 :     pfree(left_appinfos);
    1572        1632 :     pfree(right_appinfos);
    1573             : 
    1574        1632 :     return sjinfo;
    1575             : }
    1576             : 
    1577             : /*
    1578             :  * Returns true if there exists an equi-join condition for each pair of
    1579             :  * partition keys from given relations being joined.
    1580             :  */
    1581             : bool
    1582         632 : have_partkey_equi_join(RelOptInfo *joinrel,
    1583             :                        RelOptInfo *rel1, RelOptInfo *rel2,
    1584             :                        JoinType jointype, List *restrictlist)
    1585             : {
    1586         632 :     PartitionScheme part_scheme = rel1->part_scheme;
    1587             :     ListCell   *lc;
    1588             :     int         cnt_pks;
    1589             :     bool        pk_has_clause[PARTITION_MAX_KEYS];
    1590             :     bool        strict_op;
    1591             : 
    1592             :     /*
    1593             :      * This function should be called when the joining relations have same
    1594             :      * partitioning scheme.
    1595             :      */
    1596             :     Assert(rel1->part_scheme == rel2->part_scheme);
    1597             :     Assert(part_scheme);
    1598             : 
    1599         632 :     memset(pk_has_clause, 0, sizeof(pk_has_clause));
    1600        1456 :     foreach(lc, restrictlist)
    1601             :     {
    1602         824 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    1603             :         OpExpr     *opexpr;
    1604             :         Expr       *expr1;
    1605             :         Expr       *expr2;
    1606             :         int         ipk1;
    1607             :         int         ipk2;
    1608             : 
    1609             :         /* If processing an outer join, only use its own join clauses. */
    1610        1280 :         if (IS_OUTER_JOIN(jointype) &&
    1611         864 :             RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
    1612          48 :             continue;
    1613             : 
    1614             :         /* Skip clauses which can not be used for a join. */
    1615         776 :         if (!rinfo->can_join)
    1616           4 :             continue;
    1617             : 
    1618             :         /* Skip clauses which are not equality conditions. */
    1619         772 :         if (!rinfo->mergeopfamilies && !OidIsValid(rinfo->hashjoinoperator))
    1620           4 :             continue;
    1621             : 
    1622         768 :         opexpr = castNode(OpExpr, rinfo->clause);
    1623             : 
    1624             :         /*
    1625             :          * The equi-join between partition keys is strict if equi-join between
    1626             :          * at least one partition key is using a strict operator. See
    1627             :          * explanation about outer join reordering identity 3 in
    1628             :          * optimizer/README
    1629             :          */
    1630         768 :         strict_op = op_strict(opexpr->opno);
    1631             : 
    1632             :         /* Match the operands to the relation. */
    1633        1448 :         if (bms_is_subset(rinfo->left_relids, rel1->relids) &&
    1634         680 :             bms_is_subset(rinfo->right_relids, rel2->relids))
    1635             :         {
    1636         680 :             expr1 = linitial(opexpr->args);
    1637         680 :             expr2 = lsecond(opexpr->args);
    1638             :         }
    1639         176 :         else if (bms_is_subset(rinfo->left_relids, rel2->relids) &&
    1640          88 :                  bms_is_subset(rinfo->right_relids, rel1->relids))
    1641             :         {
    1642          88 :             expr1 = lsecond(opexpr->args);
    1643          88 :             expr2 = linitial(opexpr->args);
    1644             :         }
    1645             :         else
    1646           0 :             continue;
    1647             : 
    1648             :         /*
    1649             :          * Only clauses referencing the partition keys are useful for
    1650             :          * partitionwise join.
    1651             :          */
    1652         768 :         ipk1 = match_expr_to_partition_keys(expr1, rel1, strict_op);
    1653         768 :         if (ipk1 < 0)
    1654         196 :             continue;
    1655         572 :         ipk2 = match_expr_to_partition_keys(expr2, rel2, strict_op);
    1656         572 :         if (ipk2 < 0)
    1657           0 :             continue;
    1658             : 
    1659             :         /*
    1660             :          * If the clause refers to keys at different ordinal positions, it can
    1661             :          * not be used for partitionwise join.
    1662             :          */
    1663         572 :         if (ipk1 != ipk2)
    1664           4 :             continue;
    1665             : 
    1666             :         /*
    1667             :          * The clause allows partitionwise join if only it uses the same
    1668             :          * operator family as that specified by the partition key.
    1669             :          */
    1670         568 :         if (rel1->part_scheme->strategy == PARTITION_STRATEGY_HASH)
    1671             :         {
    1672          32 :             if (!op_in_opfamily(rinfo->hashjoinoperator,
    1673          32 :                                 part_scheme->partopfamily[ipk1]))
    1674           0 :                 continue;
    1675             :         }
    1676         536 :         else if (!list_member_oid(rinfo->mergeopfamilies,
    1677         536 :                                   part_scheme->partopfamily[ipk1]))
    1678           0 :             continue;
    1679             : 
    1680             :         /* Mark the partition key as having an equi-join clause. */
    1681         568 :         pk_has_clause[ipk1] = true;
    1682             :     }
    1683             : 
    1684             :     /* Check whether every partition key has an equi-join condition. */
    1685        1200 :     for (cnt_pks = 0; cnt_pks < part_scheme->partnatts; cnt_pks++)
    1686             :     {
    1687         644 :         if (!pk_has_clause[cnt_pks])
    1688          76 :             return false;
    1689             :     }
    1690             : 
    1691         556 :     return true;
    1692             : }
    1693             : 
    1694             : /*
    1695             :  * Find the partition key from the given relation matching the given
    1696             :  * expression. If found, return the index of the partition key, else return -1.
    1697             :  */
    1698             : static int
    1699        1340 : match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
    1700             : {
    1701             :     int         cnt;
    1702             : 
    1703             :     /* This function should be called only for partitioned relations. */
    1704             :     Assert(rel->part_scheme);
    1705             : 
    1706             :     /* Remove any relabel decorations. */
    1707        2840 :     while (IsA(expr, RelabelType))
    1708         160 :         expr = (Expr *) (castNode(RelabelType, expr))->arg;
    1709             : 
    1710        1560 :     for (cnt = 0; cnt < rel->part_scheme->partnatts; cnt++)
    1711             :     {
    1712             :         ListCell   *lc;
    1713             : 
    1714             :         Assert(rel->partexprs);
    1715        1600 :         foreach(lc, rel->partexprs[cnt])
    1716             :         {
    1717        1356 :             if (equal(lfirst(lc), expr))
    1718        1120 :                 return cnt;
    1719             :         }
    1720             : 
    1721         244 :         if (!strict_op)
    1722           0 :             continue;
    1723             : 
    1724             :         /*
    1725             :          * If it's a strict equi-join a NULL partition key on one side will
    1726             :          * not join a NULL partition key on the other side. So, rows with NULL
    1727             :          * partition key from a partition on one side can not join with those
    1728             :          * from a non-matching partition on the other side. So, search the
    1729             :          * nullable partition keys as well.
    1730             :          */
    1731             :         Assert(rel->nullable_partexprs);
    1732         244 :         foreach(lc, rel->nullable_partexprs[cnt])
    1733             :         {
    1734          24 :             if (equal(lfirst(lc), expr))
    1735          24 :                 return cnt;
    1736             :         }
    1737             :     }
    1738             : 
    1739         196 :     return -1;
    1740             : }

Generated by: LCOV version 1.13