LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - equivclass.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 856 903 94.8 %
Date: 2021-01-26 02:06:48 Functions: 32 32 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * equivclass.c
       4             :  *    Routines for managing EquivalenceClasses
       5             :  *
       6             :  * See src/backend/optimizer/README for discussion of EquivalenceClasses.
       7             :  *
       8             :  *
       9             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
      10             :  * Portions Copyright (c) 1994, Regents of the University of California
      11             :  *
      12             :  * IDENTIFICATION
      13             :  *    src/backend/optimizer/path/equivclass.c
      14             :  *
      15             :  *-------------------------------------------------------------------------
      16             :  */
      17             : #include "postgres.h"
      18             : 
      19             : #include <limits.h>
      20             : 
      21             : #include "access/stratnum.h"
      22             : #include "catalog/pg_type.h"
      23             : #include "nodes/makefuncs.h"
      24             : #include "nodes/nodeFuncs.h"
      25             : #include "optimizer/appendinfo.h"
      26             : #include "optimizer/clauses.h"
      27             : #include "optimizer/optimizer.h"
      28             : #include "optimizer/pathnode.h"
      29             : #include "optimizer/paths.h"
      30             : #include "optimizer/planmain.h"
      31             : #include "optimizer/restrictinfo.h"
      32             : #include "utils/lsyscache.h"
      33             : 
      34             : 
      35             : static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
      36             :                                         Expr *expr, Relids relids, Relids nullable_relids,
      37             :                                         bool is_child, Oid datatype);
      38             : static void generate_base_implied_equalities_const(PlannerInfo *root,
      39             :                                                    EquivalenceClass *ec);
      40             : static void generate_base_implied_equalities_no_const(PlannerInfo *root,
      41             :                                                       EquivalenceClass *ec);
      42             : static void generate_base_implied_equalities_broken(PlannerInfo *root,
      43             :                                                     EquivalenceClass *ec);
      44             : static List *generate_join_implied_equalities_normal(PlannerInfo *root,
      45             :                                                      EquivalenceClass *ec,
      46             :                                                      Relids join_relids,
      47             :                                                      Relids outer_relids,
      48             :                                                      Relids inner_relids);
      49             : static List *generate_join_implied_equalities_broken(PlannerInfo *root,
      50             :                                                      EquivalenceClass *ec,
      51             :                                                      Relids nominal_join_relids,
      52             :                                                      Relids outer_relids,
      53             :                                                      Relids nominal_inner_relids,
      54             :                                                      RelOptInfo *inner_rel);
      55             : static Oid  select_equality_operator(EquivalenceClass *ec,
      56             :                                      Oid lefttype, Oid righttype);
      57             : static RestrictInfo *create_join_clause(PlannerInfo *root,
      58             :                                         EquivalenceClass *ec, Oid opno,
      59             :                                         EquivalenceMember *leftem,
      60             :                                         EquivalenceMember *rightem,
      61             :                                         EquivalenceClass *parent_ec);
      62             : static bool reconsider_outer_join_clause(PlannerInfo *root,
      63             :                                          RestrictInfo *rinfo,
      64             :                                          bool outer_on_left);
      65             : static bool reconsider_full_join_clause(PlannerInfo *root,
      66             :                                         RestrictInfo *rinfo);
      67             : static Bitmapset *get_eclass_indexes_for_relids(PlannerInfo *root,
      68             :                                                 Relids relids);
      69             : static Bitmapset *get_common_eclass_indexes(PlannerInfo *root, Relids relids1,
      70             :                                             Relids relids2);
      71             : 
      72             : 
      73             : /*
      74             :  * process_equivalence
      75             :  *    The given clause has a mergejoinable operator and can be applied without
      76             :  *    any delay by an outer join, so its two sides can be considered equal
      77             :  *    anywhere they are both computable; moreover that equality can be
      78             :  *    extended transitively.  Record this knowledge in the EquivalenceClass
      79             :  *    data structure, if applicable.  Returns true if successful, false if not
      80             :  *    (in which case caller should treat the clause as ordinary, not an
      81             :  *    equivalence).
      82             :  *
      83             :  * In some cases, although we cannot convert a clause into EquivalenceClass
      84             :  * knowledge, we can still modify it to a more useful form than the original.
      85             :  * Then, *p_restrictinfo will be replaced by a new RestrictInfo, which is what
      86             :  * the caller should use for further processing.
      87             :  *
      88             :  * If below_outer_join is true, then the clause was found below the nullable
      89             :  * side of an outer join, so its sides might validly be both NULL rather than
      90             :  * strictly equal.  We can still deduce equalities in such cases, but we take
      91             :  * care to mark an EquivalenceClass if it came from any such clauses.  Also,
      92             :  * we have to check that both sides are either pseudo-constants or strict
      93             :  * functions of Vars, else they might not both go to NULL above the outer
      94             :  * join.  (This is the main reason why we need a failure return.  It's more
      95             :  * convenient to check this case here than at the call sites...)
      96             :  *
      97             :  * We also reject proposed equivalence clauses if they contain leaky functions
      98             :  * and have security_level above zero.  The EC evaluation rules require us to
      99             :  * apply certain tests at certain joining levels, and we can't tolerate
     100             :  * delaying any test on security_level grounds.  By rejecting candidate clauses
     101             :  * that might require security delays, we ensure it's safe to apply an EC
     102             :  * clause as soon as it's supposed to be applied.
     103             :  *
     104             :  * On success return, we have also initialized the clause's left_ec/right_ec
     105             :  * fields to point to the EquivalenceClass representing it.  This saves lookup
     106             :  * effort later.
     107             :  *
     108             :  * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
     109             :  * problem, for which there exist better data structures than simple lists.
     110             :  * If this code ever proves to be a bottleneck then it could be sped up ---
     111             :  * but for now, simple is beautiful.
     112             :  *
     113             :  * Note: this is only called during planner startup, not during GEQO
     114             :  * exploration, so we need not worry about whether we're in the right
     115             :  * memory context.
     116             :  */
     117             : bool
     118      182066 : process_equivalence(PlannerInfo *root,
     119             :                     RestrictInfo **p_restrictinfo,
     120             :                     bool below_outer_join)
     121             : {
     122      182066 :     RestrictInfo *restrictinfo = *p_restrictinfo;
     123      182066 :     Expr       *clause = restrictinfo->clause;
     124             :     Oid         opno,
     125             :                 collation,
     126             :                 item1_type,
     127             :                 item2_type;
     128             :     Expr       *item1;
     129             :     Expr       *item2;
     130             :     Relids      item1_relids,
     131             :                 item2_relids,
     132             :                 item1_nullable_relids,
     133             :                 item2_nullable_relids;
     134             :     List       *opfamilies;
     135             :     EquivalenceClass *ec1,
     136             :                *ec2;
     137             :     EquivalenceMember *em1,
     138             :                *em2;
     139             :     ListCell   *lc1;
     140             :     int         ec2_idx;
     141             : 
     142             :     /* Should not already be marked as having generated an eclass */
     143             :     Assert(restrictinfo->left_ec == NULL);
     144             :     Assert(restrictinfo->right_ec == NULL);
     145             : 
     146             :     /* Reject if it is potentially postponable by security considerations */
     147      182066 :     if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
     148         120 :         return false;
     149             : 
     150             :     /* Extract info from given clause */
     151             :     Assert(is_opclause(clause));
     152      181946 :     opno = ((OpExpr *) clause)->opno;
     153      181946 :     collation = ((OpExpr *) clause)->inputcollid;
     154      181946 :     item1 = (Expr *) get_leftop(clause);
     155      181946 :     item2 = (Expr *) get_rightop(clause);
     156      181946 :     item1_relids = restrictinfo->left_relids;
     157      181946 :     item2_relids = restrictinfo->right_relids;
     158             : 
     159             :     /*
     160             :      * Ensure both input expressions expose the desired collation (their types
     161             :      * should be OK already); see comments for canonicalize_ec_expression.
     162             :      */
     163      181946 :     item1 = canonicalize_ec_expression(item1,
     164             :                                        exprType((Node *) item1),
     165             :                                        collation);
     166      181946 :     item2 = canonicalize_ec_expression(item2,
     167             :                                        exprType((Node *) item2),
     168             :                                        collation);
     169             : 
     170             :     /*
     171             :      * Clauses of the form X=X cannot be translated into EquivalenceClasses.
     172             :      * We'd either end up with a single-entry EC, losing the knowledge that
     173             :      * the clause was present at all, or else make an EC with duplicate
     174             :      * entries, causing other issues.
     175             :      */
     176      181946 :     if (equal(item1, item2))
     177             :     {
     178             :         /*
     179             :          * If the operator is strict, then the clause can be treated as just
     180             :          * "X IS NOT NULL".  (Since we know we are considering a top-level
     181             :          * qual, we can ignore the difference between FALSE and NULL results.)
     182             :          * It's worth making the conversion because we'll typically get a much
     183             :          * better selectivity estimate than we would for X=X.
     184             :          *
     185             :          * If the operator is not strict, we can't be sure what it will do
     186             :          * with NULLs, so don't attempt to optimize it.
     187             :          */
     188          28 :         set_opfuncid((OpExpr *) clause);
     189          28 :         if (func_strict(((OpExpr *) clause)->opfuncid))
     190             :         {
     191          28 :             NullTest   *ntest = makeNode(NullTest);
     192             : 
     193          28 :             ntest->arg = item1;
     194          28 :             ntest->nulltesttype = IS_NOT_NULL;
     195          28 :             ntest->argisrow = false; /* correct even if composite arg */
     196          28 :             ntest->location = -1;
     197             : 
     198          28 :             *p_restrictinfo =
     199         112 :                 make_restrictinfo(root,
     200             :                                   (Expr *) ntest,
     201          28 :                                   restrictinfo->is_pushed_down,
     202          28 :                                   restrictinfo->outerjoin_delayed,
     203          28 :                                   restrictinfo->pseudoconstant,
     204             :                                   restrictinfo->security_level,
     205             :                                   NULL,
     206             :                                   restrictinfo->outer_relids,
     207             :                                   restrictinfo->nullable_relids);
     208             :         }
     209          28 :         return false;
     210             :     }
     211             : 
     212             :     /*
     213             :      * If below outer join, check for strictness, else reject.
     214             :      */
     215      181918 :     if (below_outer_join)
     216             :     {
     217       47334 :         if (!bms_is_empty(item1_relids) &&
     218       23580 :             contain_nonstrict_functions((Node *) item1))
     219           0 :             return false;       /* LHS is non-strict but not constant */
     220       24800 :         if (!bms_is_empty(item2_relids) &&
     221        1046 :             contain_nonstrict_functions((Node *) item2))
     222           0 :             return false;       /* RHS is non-strict but not constant */
     223             :     }
     224             : 
     225             :     /* Calculate nullable-relid sets for each side of the clause */
     226      181918 :     item1_nullable_relids = bms_intersect(item1_relids,
     227      181918 :                                           restrictinfo->nullable_relids);
     228      181918 :     item2_nullable_relids = bms_intersect(item2_relids,
     229      181918 :                                           restrictinfo->nullable_relids);
     230             : 
     231             :     /*
     232             :      * We use the declared input types of the operator, not exprType() of the
     233             :      * inputs, as the nominal datatypes for opfamily lookup.  This presumes
     234             :      * that btree operators are always registered with amoplefttype and
     235             :      * amoprighttype equal to their declared input types.  We will need this
     236             :      * info anyway to build EquivalenceMember nodes, and by extracting it now
     237             :      * we can use type comparisons to short-circuit some equal() tests.
     238             :      */
     239      181918 :     op_input_types(opno, &item1_type, &item2_type);
     240             : 
     241      181918 :     opfamilies = restrictinfo->mergeopfamilies;
     242             : 
     243             :     /*
     244             :      * Sweep through the existing EquivalenceClasses looking for matches to
     245             :      * item1 and item2.  These are the possible outcomes:
     246             :      *
     247             :      * 1. We find both in the same EC.  The equivalence is already known, so
     248             :      * there's nothing to do.
     249             :      *
     250             :      * 2. We find both in different ECs.  Merge the two ECs together.
     251             :      *
     252             :      * 3. We find just one.  Add the other to its EC.
     253             :      *
     254             :      * 4. We find neither.  Make a new, two-entry EC.
     255             :      *
     256             :      * Note: since all ECs are built through this process or the similar
     257             :      * search in get_eclass_for_sort_expr(), it's impossible that we'd match
     258             :      * an item in more than one existing nonvolatile EC.  So it's okay to stop
     259             :      * at the first match.
     260             :      */
     261      181918 :     ec1 = ec2 = NULL;
     262      181918 :     em1 = em2 = NULL;
     263      181918 :     ec2_idx = -1;
     264      393142 :     foreach(lc1, root->eq_classes)
     265             :     {
     266      211668 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     267             :         ListCell   *lc2;
     268             : 
     269             :         /* Never match to a volatile EC */
     270      211668 :         if (cur_ec->ec_has_volatile)
     271           0 :             continue;
     272             : 
     273             :         /*
     274             :          * The collation has to match; check this first since it's cheaper
     275             :          * than the opfamily comparison.
     276             :          */
     277      211668 :         if (collation != cur_ec->ec_collation)
     278        9668 :             continue;
     279             : 
     280             :         /*
     281             :          * A "match" requires matching sets of btree opfamilies.  Use of
     282             :          * equal() for this test has implications discussed in the comments
     283             :          * for get_mergejoin_opfamilies().
     284             :          */
     285      202000 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     286       41744 :             continue;
     287             : 
     288      399660 :         foreach(lc2, cur_ec->ec_members)
     289             :         {
     290      239848 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
     291             : 
     292             :             Assert(!cur_em->em_is_child);    /* no children yet */
     293             : 
     294             :             /*
     295             :              * If below an outer join, don't match constants: they're not as
     296             :              * constant as they look.
     297             :              */
     298      239848 :             if ((below_outer_join || cur_ec->ec_below_outer_join) &&
     299       84952 :                 cur_em->em_is_const)
     300       16056 :                 continue;
     301             : 
     302      223792 :             if (!ec1 &&
     303      397852 :                 item1_type == cur_em->em_datatype &&
     304      198836 :                 equal(item1, cur_em->em_expr))
     305             :             {
     306       14166 :                 ec1 = cur_ec;
     307       14166 :                 em1 = cur_em;
     308       14166 :                 if (ec2)
     309         440 :                     break;
     310             :             }
     311             : 
     312      223352 :             if (!ec2 &&
     313      442520 :                 item2_type == cur_em->em_datatype &&
     314      221144 :                 equal(item2, cur_em->em_expr))
     315             :             {
     316        2080 :                 ec2 = cur_ec;
     317        2080 :                 ec2_idx = foreach_current_index(lc1);
     318        2080 :                 em2 = cur_em;
     319        2080 :                 if (ec1)
     320           4 :                     break;
     321             :             }
     322             :         }
     323             : 
     324      160256 :         if (ec1 && ec2)
     325         444 :             break;
     326             :     }
     327             : 
     328             :     /* Sweep finished, what did we find? */
     329             : 
     330      181918 :     if (ec1 && ec2)
     331             :     {
     332             :         /* If case 1, nothing to do, except add to sources */
     333         444 :         if (ec1 == ec2)
     334             :         {
     335           0 :             ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     336           0 :             ec1->ec_below_outer_join |= below_outer_join;
     337           0 :             ec1->ec_min_security = Min(ec1->ec_min_security,
     338             :                                        restrictinfo->security_level);
     339           0 :             ec1->ec_max_security = Max(ec1->ec_max_security,
     340             :                                        restrictinfo->security_level);
     341             :             /* mark the RI as associated with this eclass */
     342           0 :             restrictinfo->left_ec = ec1;
     343           0 :             restrictinfo->right_ec = ec1;
     344             :             /* mark the RI as usable with this pair of EMs */
     345           0 :             restrictinfo->left_em = em1;
     346           0 :             restrictinfo->right_em = em2;
     347           0 :             return true;
     348             :         }
     349             : 
     350             :         /*
     351             :          * Case 2: need to merge ec1 and ec2.  This should never happen after
     352             :          * the ECs have reached canonical state; otherwise, pathkeys could be
     353             :          * rendered non-canonical by the merge, and relation eclass indexes
     354             :          * would get broken by removal of an eq_classes list entry.
     355             :          */
     356         444 :         if (root->ec_merging_done)
     357           0 :             elog(ERROR, "too late to merge equivalence classes");
     358             : 
     359             :         /*
     360             :          * We add ec2's items to ec1, then set ec2's ec_merged link to point
     361             :          * to ec1 and remove ec2 from the eq_classes list.  We cannot simply
     362             :          * delete ec2 because that could leave dangling pointers in existing
     363             :          * PathKeys.  We leave it behind with a link so that the merged EC can
     364             :          * be found.
     365             :          */
     366         444 :         ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
     367         444 :         ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
     368         444 :         ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
     369         444 :         ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
     370         444 :         ec1->ec_has_const |= ec2->ec_has_const;
     371             :         /* can't need to set has_volatile */
     372         444 :         ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
     373         444 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     374             :                                    ec2->ec_min_security);
     375         444 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     376             :                                    ec2->ec_max_security);
     377         444 :         ec2->ec_merged = ec1;
     378         444 :         root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
     379             :         /* just to avoid debugging confusion w/ dangling pointers: */
     380         444 :         ec2->ec_members = NIL;
     381         444 :         ec2->ec_sources = NIL;
     382         444 :         ec2->ec_derives = NIL;
     383         444 :         ec2->ec_relids = NULL;
     384         444 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     385         444 :         ec1->ec_below_outer_join |= below_outer_join;
     386         444 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     387             :                                    restrictinfo->security_level);
     388         444 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     389             :                                    restrictinfo->security_level);
     390             :         /* mark the RI as associated with this eclass */
     391         444 :         restrictinfo->left_ec = ec1;
     392         444 :         restrictinfo->right_ec = ec1;
     393             :         /* mark the RI as usable with this pair of EMs */
     394         444 :         restrictinfo->left_em = em1;
     395         444 :         restrictinfo->right_em = em2;
     396             :     }
     397      181474 :     else if (ec1)
     398             :     {
     399             :         /* Case 3: add item2 to ec1 */
     400       13722 :         em2 = add_eq_member(ec1, item2, item2_relids, item2_nullable_relids,
     401             :                             false, item2_type);
     402       13722 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     403       13722 :         ec1->ec_below_outer_join |= below_outer_join;
     404       13722 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     405             :                                    restrictinfo->security_level);
     406       13722 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     407             :                                    restrictinfo->security_level);
     408             :         /* mark the RI as associated with this eclass */
     409       13722 :         restrictinfo->left_ec = ec1;
     410       13722 :         restrictinfo->right_ec = ec1;
     411             :         /* mark the RI as usable with this pair of EMs */
     412       13722 :         restrictinfo->left_em = em1;
     413       13722 :         restrictinfo->right_em = em2;
     414             :     }
     415      167752 :     else if (ec2)
     416             :     {
     417             :         /* Case 3: add item1 to ec2 */
     418        1636 :         em1 = add_eq_member(ec2, item1, item1_relids, item1_nullable_relids,
     419             :                             false, item1_type);
     420        1636 :         ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
     421        1636 :         ec2->ec_below_outer_join |= below_outer_join;
     422        1636 :         ec2->ec_min_security = Min(ec2->ec_min_security,
     423             :                                    restrictinfo->security_level);
     424        1636 :         ec2->ec_max_security = Max(ec2->ec_max_security,
     425             :                                    restrictinfo->security_level);
     426             :         /* mark the RI as associated with this eclass */
     427        1636 :         restrictinfo->left_ec = ec2;
     428        1636 :         restrictinfo->right_ec = ec2;
     429             :         /* mark the RI as usable with this pair of EMs */
     430        1636 :         restrictinfo->left_em = em1;
     431        1636 :         restrictinfo->right_em = em2;
     432             :     }
     433             :     else
     434             :     {
     435             :         /* Case 4: make a new, two-entry EC */
     436      166116 :         EquivalenceClass *ec = makeNode(EquivalenceClass);
     437             : 
     438      166116 :         ec->ec_opfamilies = opfamilies;
     439      166116 :         ec->ec_collation = collation;
     440      166116 :         ec->ec_members = NIL;
     441      166116 :         ec->ec_sources = list_make1(restrictinfo);
     442      166116 :         ec->ec_derives = NIL;
     443      166116 :         ec->ec_relids = NULL;
     444      166116 :         ec->ec_has_const = false;
     445      166116 :         ec->ec_has_volatile = false;
     446      166116 :         ec->ec_below_outer_join = below_outer_join;
     447      166116 :         ec->ec_broken = false;
     448      166116 :         ec->ec_sortref = 0;
     449      166116 :         ec->ec_min_security = restrictinfo->security_level;
     450      166116 :         ec->ec_max_security = restrictinfo->security_level;
     451      166116 :         ec->ec_merged = NULL;
     452      166116 :         em1 = add_eq_member(ec, item1, item1_relids, item1_nullable_relids,
     453             :                             false, item1_type);
     454      166116 :         em2 = add_eq_member(ec, item2, item2_relids, item2_nullable_relids,
     455             :                             false, item2_type);
     456             : 
     457      166116 :         root->eq_classes = lappend(root->eq_classes, ec);
     458             : 
     459             :         /* mark the RI as associated with this eclass */
     460      166116 :         restrictinfo->left_ec = ec;
     461      166116 :         restrictinfo->right_ec = ec;
     462             :         /* mark the RI as usable with this pair of EMs */
     463      166116 :         restrictinfo->left_em = em1;
     464      166116 :         restrictinfo->right_em = em2;
     465             :     }
     466             : 
     467      181918 :     return true;
     468             : }
     469             : 
     470             : /*
     471             :  * canonicalize_ec_expression
     472             :  *
     473             :  * This function ensures that the expression exposes the expected type and
     474             :  * collation, so that it will be equal() to other equivalence-class expressions
     475             :  * that it ought to be equal() to.
     476             :  *
     477             :  * The rule for datatypes is that the exposed type should match what it would
     478             :  * be for an input to an operator of the EC's opfamilies; which is usually
     479             :  * the declared input type of the operator, but in the case of polymorphic
     480             :  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
     481             :  * Expressions coming in from quals will generally have the right type
     482             :  * already, but expressions coming from indexkeys may not (because they are
     483             :  * represented without any explicit relabel in pg_index), and the same problem
     484             :  * occurs for sort expressions (because the parser is likewise cavalier about
     485             :  * putting relabels on them).  Such cases will be binary-compatible with the
     486             :  * real operators, so adding a RelabelType is sufficient.
     487             :  *
     488             :  * Also, the expression's exposed collation must match the EC's collation.
     489             :  * This is important because in comparisons like "foo < bar COLLATE baz",
     490             :  * only one of the expressions has the correct exposed collation as we receive
     491             :  * it from the parser.  Forcing both of them to have it ensures that all
     492             :  * variant spellings of such a construct behave the same.  Again, we can
     493             :  * stick on a RelabelType to force the right exposed collation.  (It might
     494             :  * work to not label the collation at all in EC members, but this is risky
     495             :  * since some parts of the system expect exprCollation() to deliver the
     496             :  * right answer for a sort key.)
     497             :  */
     498             : Expr *
     499     1263976 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
     500             : {
     501     1263976 :     Oid         expr_type = exprType((Node *) expr);
     502             : 
     503             :     /*
     504             :      * For a polymorphic-input-type opclass, just keep the same exposed type.
     505             :      * RECORD opclasses work like polymorphic-type ones for this purpose.
     506             :      */
     507     1263976 :     if (IsPolymorphicType(req_type) || req_type == RECORDOID)
     508         798 :         req_type = expr_type;
     509             : 
     510             :     /*
     511             :      * No work if the expression exposes the right type/collation already.
     512             :      */
     513     2523842 :     if (expr_type != req_type ||
     514     1259866 :         exprCollation((Node *) expr) != req_collation)
     515             :     {
     516             :         /*
     517             :          * If we have to change the type of the expression, set typmod to -1,
     518             :          * since the new type may not have the same typmod interpretation.
     519             :          * When we only have to change collation, preserve the exposed typmod.
     520             :          */
     521             :         int32       req_typmod;
     522             : 
     523        4922 :         if (expr_type != req_type)
     524        4110 :             req_typmod = -1;
     525             :         else
     526         812 :             req_typmod = exprTypmod((Node *) expr);
     527             : 
     528             :         /*
     529             :          * Use applyRelabelType so that we preserve const-flatness.  This is
     530             :          * important since eval_const_expressions has already been applied.
     531             :          */
     532        4922 :         expr = (Expr *) applyRelabelType((Node *) expr,
     533             :                                          req_type, req_typmod, req_collation,
     534             :                                          COERCE_IMPLICIT_CAST, -1, false);
     535             :     }
     536             : 
     537     1263976 :     return expr;
     538             : }
     539             : 
     540             : /*
     541             :  * add_eq_member - build a new EquivalenceMember and add it to an EC
     542             :  */
     543             : static EquivalenceMember *
     544      504892 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
     545             :               Relids nullable_relids, bool is_child, Oid datatype)
     546             : {
     547      504892 :     EquivalenceMember *em = makeNode(EquivalenceMember);
     548             : 
     549      504892 :     em->em_expr = expr;
     550      504892 :     em->em_relids = relids;
     551      504892 :     em->em_nullable_relids = nullable_relids;
     552      504892 :     em->em_is_const = false;
     553      504892 :     em->em_is_child = is_child;
     554      504892 :     em->em_datatype = datatype;
     555             : 
     556      504892 :     if (bms_is_empty(relids))
     557             :     {
     558             :         /*
     559             :          * No Vars, assume it's a pseudoconstant.  This is correct for entries
     560             :          * generated from process_equivalence(), because a WHERE clause can't
     561             :          * contain aggregates or SRFs, and non-volatility was checked before
     562             :          * process_equivalence() ever got called.  But
     563             :          * get_eclass_for_sort_expr() has to work harder.  We put the tests
     564             :          * there not here to save cycles in the equivalence case.
     565             :          */
     566             :         Assert(!is_child);
     567      152912 :         em->em_is_const = true;
     568      152912 :         ec->ec_has_const = true;
     569             :         /* it can't affect ec_relids */
     570             :     }
     571      351980 :     else if (!is_child)         /* child members don't add to ec_relids */
     572             :     {
     573      324366 :         ec->ec_relids = bms_add_members(ec->ec_relids, relids);
     574             :     }
     575      504892 :     ec->ec_members = lappend(ec->ec_members, em);
     576             : 
     577      504892 :     return em;
     578             : }
     579             : 
     580             : 
     581             : /*
     582             :  * get_eclass_for_sort_expr
     583             :  *    Given an expression and opfamily/collation info, find an existing
     584             :  *    equivalence class it is a member of; if none, optionally build a new
     585             :  *    single-member EquivalenceClass for it.
     586             :  *
     587             :  * expr is the expression, and nullable_relids is the set of base relids
     588             :  * that are potentially nullable below it.  We actually only care about
     589             :  * the set of such relids that are used in the expression; but for caller
     590             :  * convenience, we perform that intersection step here.  The caller need
     591             :  * only be sure that nullable_relids doesn't omit any nullable rels that
     592             :  * might appear in the expr.
     593             :  *
     594             :  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
     595             :  * or zero if not.  (It should never be zero if the expression is volatile!)
     596             :  *
     597             :  * If rel is not NULL, it identifies a specific relation we're considering
     598             :  * a path for, and indicates that child EC members for that relation can be
     599             :  * considered.  Otherwise child members are ignored.  (Note: since child EC
     600             :  * members aren't guaranteed unique, a non-NULL value means that there could
     601             :  * be more than one EC that matches the expression; if so it's order-dependent
     602             :  * which one you get.  This is annoying but it only happens in corner cases,
     603             :  * so for now we live with just reporting the first match.  See also
     604             :  * generate_implied_equalities_for_column and match_pathkeys_to_index.)
     605             :  *
     606             :  * If create_it is true, we'll build a new EquivalenceClass when there is no
     607             :  * match.  If create_it is false, we just return NULL when no match.
     608             :  *
     609             :  * This can be used safely both before and after EquivalenceClass merging;
     610             :  * since it never causes merging it does not invalidate any existing ECs
     611             :  * or PathKeys.  However, ECs added after path generation has begun are
     612             :  * of limited usefulness, so usually it's best to create them beforehand.
     613             :  *
     614             :  * Note: opfamilies must be chosen consistently with the way
     615             :  * process_equivalence() would do; that is, generated from a mergejoinable
     616             :  * equality operator.  Else we might fail to detect valid equivalences,
     617             :  * generating poor (but not incorrect) plans.
     618             :  */
     619             : EquivalenceClass *
     620      897400 : get_eclass_for_sort_expr(PlannerInfo *root,
     621             :                          Expr *expr,
     622             :                          Relids nullable_relids,
     623             :                          List *opfamilies,
     624             :                          Oid opcintype,
     625             :                          Oid collation,
     626             :                          Index sortref,
     627             :                          Relids rel,
     628             :                          bool create_it)
     629             : {
     630             :     Relids      expr_relids;
     631             :     EquivalenceClass *newec;
     632             :     EquivalenceMember *newem;
     633             :     ListCell   *lc1;
     634             :     MemoryContext oldcontext;
     635             : 
     636             :     /*
     637             :      * Ensure the expression exposes the correct type and collation.
     638             :      */
     639      897400 :     expr = canonicalize_ec_expression(expr, opcintype, collation);
     640             : 
     641             :     /*
     642             :      * Scan through the existing EquivalenceClasses for a match
     643             :      */
     644     3017022 :     foreach(lc1, root->eq_classes)
     645             :     {
     646     2610186 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     647             :         ListCell   *lc2;
     648             : 
     649             :         /*
     650             :          * Never match to a volatile EC, except when we are looking at another
     651             :          * reference to the same volatile SortGroupClause.
     652             :          */
     653     2610186 :         if (cur_ec->ec_has_volatile &&
     654          18 :             (sortref == 0 || sortref != cur_ec->ec_sortref))
     655         232 :             continue;
     656             : 
     657     2609954 :         if (collation != cur_ec->ec_collation)
     658      692940 :             continue;
     659     1917014 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     660      421698 :             continue;
     661             : 
     662     3286790 :         foreach(lc2, cur_ec->ec_members)
     663             :         {
     664     2282038 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
     665             : 
     666             :             /*
     667             :              * Ignore child members unless they match the request.
     668             :              */
     669     2282038 :             if (cur_em->em_is_child &&
     670      129188 :                 !bms_equal(cur_em->em_relids, rel))
     671      105952 :                 continue;
     672             : 
     673             :             /*
     674             :              * If below an outer join, don't match constants: they're not as
     675             :              * constant as they look.
     676             :              */
     677     2176086 :             if (cur_ec->ec_below_outer_join &&
     678      203114 :                 cur_em->em_is_const)
     679       70060 :                 continue;
     680             : 
     681     4197326 :             if (opcintype == cur_em->em_datatype &&
     682     2091300 :                 equal(expr, cur_em->em_expr))
     683      490564 :                 return cur_ec;  /* Match! */
     684             :         }
     685             :     }
     686             : 
     687             :     /* No match; does caller want a NULL result? */
     688      406836 :     if (!create_it)
     689      277148 :         return NULL;
     690             : 
     691             :     /*
     692             :      * OK, build a new single-member EC
     693             :      *
     694             :      * Here, we must be sure that we construct the EC in the right context.
     695             :      */
     696      129688 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
     697             : 
     698      129688 :     newec = makeNode(EquivalenceClass);
     699      129688 :     newec->ec_opfamilies = list_copy(opfamilies);
     700      129688 :     newec->ec_collation = collation;
     701      129688 :     newec->ec_members = NIL;
     702      129688 :     newec->ec_sources = NIL;
     703      129688 :     newec->ec_derives = NIL;
     704      129688 :     newec->ec_relids = NULL;
     705      129688 :     newec->ec_has_const = false;
     706      129688 :     newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
     707      129688 :     newec->ec_below_outer_join = false;
     708      129688 :     newec->ec_broken = false;
     709      129688 :     newec->ec_sortref = sortref;
     710      129688 :     newec->ec_min_security = UINT_MAX;
     711      129688 :     newec->ec_max_security = 0;
     712      129688 :     newec->ec_merged = NULL;
     713             : 
     714      129688 :     if (newec->ec_has_volatile && sortref == 0) /* should not happen */
     715           0 :         elog(ERROR, "volatile EquivalenceClass has no sortref");
     716             : 
     717             :     /*
     718             :      * Get the precise set of nullable relids appearing in the expression.
     719             :      */
     720      129688 :     expr_relids = pull_varnos(root, (Node *) expr);
     721      129688 :     nullable_relids = bms_intersect(nullable_relids, expr_relids);
     722             : 
     723      129688 :     newem = add_eq_member(newec, copyObject(expr), expr_relids,
     724             :                           nullable_relids, false, opcintype);
     725             : 
     726             :     /*
     727             :      * add_eq_member doesn't check for volatile functions, set-returning
     728             :      * functions, aggregates, or window functions, but such could appear in
     729             :      * sort expressions; so we have to check whether its const-marking was
     730             :      * correct.
     731             :      */
     732      129688 :     if (newec->ec_has_const)
     733             :     {
     734        1610 :         if (newec->ec_has_volatile ||
     735        1484 :             expression_returns_set((Node *) expr) ||
     736        1276 :             contain_agg_clause((Node *) expr) ||
     737         580 :             contain_window_function((Node *) expr))
     738             :         {
     739         246 :             newec->ec_has_const = false;
     740         246 :             newem->em_is_const = false;
     741             :         }
     742             :     }
     743             : 
     744      129688 :     root->eq_classes = lappend(root->eq_classes, newec);
     745             : 
     746             :     /*
     747             :      * If EC merging is already complete, we have to mop up by adding the new
     748             :      * EC to the eclass_indexes of the relation(s) mentioned in it.
     749             :      */
     750      129688 :     if (root->ec_merging_done)
     751             :     {
     752       51292 :         int         ec_index = list_length(root->eq_classes) - 1;
     753       51292 :         int         i = -1;
     754             : 
     755      101602 :         while ((i = bms_next_member(newec->ec_relids, i)) > 0)
     756             :         {
     757       50310 :             RelOptInfo *rel = root->simple_rel_array[i];
     758             : 
     759             :             Assert(rel->reloptkind == RELOPT_BASEREL ||
     760             :                    rel->reloptkind == RELOPT_DEADREL);
     761             : 
     762       50310 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
     763             :                                                  ec_index);
     764             :         }
     765             :     }
     766             : 
     767      129688 :     MemoryContextSwitchTo(oldcontext);
     768             : 
     769      129688 :     return newec;
     770             : }
     771             : 
     772             : /*
     773             :  * Find an equivalence class member expression, all of whose Vars, come from
     774             :  * the indicated relation.
     775             :  */
     776             : Expr *
     777        2506 : find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel)
     778             : {
     779             :     ListCell   *lc_em;
     780             : 
     781        4982 :     foreach(lc_em, ec->ec_members)
     782             :     {
     783        4666 :         EquivalenceMember *em = lfirst(lc_em);
     784             : 
     785        4666 :         if (bms_is_subset(em->em_relids, rel->relids) &&
     786        2190 :             !bms_is_empty(em->em_relids))
     787             :         {
     788             :             /*
     789             :              * If there is more than one equivalence member whose Vars are
     790             :              * taken entirely from this relation, we'll be content to choose
     791             :              * any one of those.
     792             :              */
     793        2190 :             return em->em_expr;
     794             :         }
     795             :     }
     796             : 
     797             :     /* We didn't find any suitable equivalence class expression */
     798         316 :     return NULL;
     799             : }
     800             : 
     801             : /*
     802             :  * Find an equivalence class member expression that can be safely used to build
     803             :  * a sort node using the provided relation. The rules are a subset of those
     804             :  * applied in prepare_sort_from_pathkeys since that function deals with sorts
     805             :  * that must be delayed until the last stages of query execution, while here
     806             :  * we only care about proactive sorts.
     807             :  */
     808             : Expr *
     809        6804 : find_em_expr_usable_for_sorting_rel(PlannerInfo *root, EquivalenceClass *ec,
     810             :                                     RelOptInfo *rel, bool require_parallel_safe)
     811             : {
     812             :     ListCell   *lc_em;
     813             : 
     814             :     /*
     815             :      * If there is more than one equivalence member matching these
     816             :      * requirements we'll be content to choose any one of them.
     817             :      */
     818       14364 :     foreach(lc_em, ec->ec_members)
     819             :     {
     820       13164 :         EquivalenceMember *em = lfirst(lc_em);
     821       13164 :         Expr       *em_expr = em->em_expr;
     822             : 
     823             :         /*
     824             :          * We shouldn't be trying to sort by an equivalence class that
     825             :          * contains a constant, so no need to consider such cases any further.
     826             :          */
     827       13164 :         if (em->em_is_const)
     828           8 :             continue;
     829             : 
     830             :         /*
     831             :          * Any Vars in the equivalence class member need to come from this
     832             :          * relation. This is a superset of prepare_sort_from_pathkeys ignoring
     833             :          * child members unless they belong to the rel being sorted.
     834             :          */
     835       13156 :         if (!bms_is_subset(em->em_relids, rel->relids))
     836        7508 :             continue;
     837             : 
     838             :         /*
     839             :          * If requested, reject expressions that are not parallel-safe.
     840             :          */
     841        5648 :         if (require_parallel_safe && !is_parallel_safe(root, (Node *) em_expr))
     842          40 :             continue;
     843             : 
     844             :         /*
     845             :          * Disallow SRFs so that all of them can be evaluated at the correct
     846             :          * time as determined by make_sort_input_target.
     847             :          */
     848        5608 :         if (IS_SRF_CALL((Node *) em_expr))
     849           4 :             continue;
     850             : 
     851             :         /*
     852             :          * As long as the expression isn't volatile then
     853             :          * prepare_sort_from_pathkeys is able to generate a new target entry,
     854             :          * so there's no need to verify that one already exists.
     855             :          *
     856             :          * While prepare_sort_from_pathkeys has to be concerned about matching
     857             :          * up a volatile expression to the proper tlist entry, it doesn't seem
     858             :          * valuable here to expend the work trying to find a match in the
     859             :          * target's exprs since such a sort will have to be postponed anyway.
     860             :          */
     861        5604 :         if (!ec->ec_has_volatile)
     862        5604 :             return em->em_expr;
     863             :     }
     864             : 
     865             :     /* We didn't find any suitable equivalence class expression */
     866        1200 :     return NULL;
     867             : }
     868             : 
     869             : /*
     870             :  * generate_base_implied_equalities
     871             :  *    Generate any restriction clauses that we can deduce from equivalence
     872             :  *    classes.
     873             :  *
     874             :  * When an EC contains pseudoconstants, our strategy is to generate
     875             :  * "member = const1" clauses where const1 is the first constant member, for
     876             :  * every other member (including other constants).  If we are able to do this
     877             :  * then we don't need any "var = var" comparisons because we've successfully
     878             :  * constrained all the vars at their points of creation.  If we fail to
     879             :  * generate any of these clauses due to lack of cross-type operators, we fall
     880             :  * back to the "ec_broken" strategy described below.  (XXX if there are
     881             :  * multiple constants of different types, it's possible that we might succeed
     882             :  * in forming all the required clauses if we started from a different const
     883             :  * member; but this seems a sufficiently hokey corner case to not be worth
     884             :  * spending lots of cycles on.)
     885             :  *
     886             :  * For ECs that contain no pseudoconstants, we generate derived clauses
     887             :  * "member1 = member2" for each pair of members belonging to the same base
     888             :  * relation (actually, if there are more than two for the same base relation,
     889             :  * we only need enough clauses to link each to each other).  This provides
     890             :  * the base case for the recursion: each row emitted by a base relation scan
     891             :  * will constrain all computable members of the EC to be equal.  As each
     892             :  * join path is formed, we'll add additional derived clauses on-the-fly
     893             :  * to maintain this invariant (see generate_join_implied_equalities).
     894             :  *
     895             :  * If the opfamilies used by the EC do not provide complete sets of cross-type
     896             :  * equality operators, it is possible that we will fail to generate a clause
     897             :  * that must be generated to maintain the invariant.  (An example: given
     898             :  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
     899             :  * generate "a.x = a.z" as a restriction clause for A.)  In this case we mark
     900             :  * the EC "ec_broken" and fall back to regurgitating its original source
     901             :  * RestrictInfos at appropriate times.  We do not try to retract any derived
     902             :  * clauses already generated from the broken EC, so the resulting plan could
     903             :  * be poor due to bad selectivity estimates caused by redundant clauses.  But
     904             :  * the correct solution to that is to fix the opfamilies ...
     905             :  *
     906             :  * Equality clauses derived by this function are passed off to
     907             :  * process_implied_equality (in plan/initsplan.c) to be inserted into the
     908             :  * restrictinfo datastructures.  Note that this must be called after initial
     909             :  * scanning of the quals and before Path construction begins.
     910             :  *
     911             :  * We make no attempt to avoid generating duplicate RestrictInfos here: we
     912             :  * don't search ec_sources or ec_derives for matches.  It doesn't really
     913             :  * seem worth the trouble to do so.
     914             :  */
     915             : void
     916      209864 : generate_base_implied_equalities(PlannerInfo *root)
     917             : {
     918             :     int         ec_index;
     919             :     ListCell   *lc;
     920             : 
     921             :     /*
     922             :      * At this point, we're done absorbing knowledge of equivalences in the
     923             :      * query, so no further EC merging should happen, and ECs remaining in the
     924             :      * eq_classes list can be considered canonical.  (But note that it's still
     925             :      * possible for new single-member ECs to be added through
     926             :      * get_eclass_for_sort_expr().)
     927             :      */
     928      209864 :     root->ec_merging_done = true;
     929             : 
     930      209864 :     ec_index = 0;
     931      453932 :     foreach(lc, root->eq_classes)
     932             :     {
     933      244068 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
     934      244068 :         bool        can_generate_joinclause = false;
     935             :         int         i;
     936             : 
     937             :         Assert(ec->ec_merged == NULL);   /* else shouldn't be in list */
     938             :         Assert(!ec->ec_broken); /* not yet anyway... */
     939             : 
     940             :         /*
     941             :          * Generate implied equalities that are restriction clauses.
     942             :          * Single-member ECs won't generate any deductions, either here or at
     943             :          * the join level.
     944             :          */
     945      244068 :         if (list_length(ec->ec_members) > 1)
     946             :         {
     947      176284 :             if (ec->ec_has_const)
     948      152006 :                 generate_base_implied_equalities_const(root, ec);
     949             :             else
     950       24278 :                 generate_base_implied_equalities_no_const(root, ec);
     951             : 
     952             :             /* Recover if we failed to generate required derived clauses */
     953      176284 :             if (ec->ec_broken)
     954          20 :                 generate_base_implied_equalities_broken(root, ec);
     955             : 
     956             :             /* Detect whether this EC might generate join clauses */
     957      176284 :             can_generate_joinclause =
     958      176284 :                 (bms_membership(ec->ec_relids) == BMS_MULTIPLE);
     959             :         }
     960             : 
     961             :         /*
     962             :          * Mark the base rels cited in each eclass (which should all exist by
     963             :          * now) with the eq_classes indexes of all eclasses mentioning them.
     964             :          * This will let us avoid searching in subsequent lookups.  While
     965             :          * we're at it, we can mark base rels that have pending eclass joins;
     966             :          * this is a cheap version of has_relevant_eclass_joinclause().
     967             :          */
     968      244068 :         i = -1;
     969      516682 :         while ((i = bms_next_member(ec->ec_relids, i)) > 0)
     970             :         {
     971      272614 :             RelOptInfo *rel = root->simple_rel_array[i];
     972             : 
     973             :             Assert(rel->reloptkind == RELOPT_BASEREL);
     974             : 
     975      272614 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
     976             :                                                  ec_index);
     977             : 
     978      272614 :             if (can_generate_joinclause)
     979       57172 :                 rel->has_eclass_joins = true;
     980             :         }
     981             : 
     982      244068 :         ec_index++;
     983             :     }
     984      209864 : }
     985             : 
     986             : /*
     987             :  * generate_base_implied_equalities when EC contains pseudoconstant(s)
     988             :  */
     989             : static void
     990      152006 : generate_base_implied_equalities_const(PlannerInfo *root,
     991             :                                        EquivalenceClass *ec)
     992             : {
     993      152006 :     EquivalenceMember *const_em = NULL;
     994             :     ListCell   *lc;
     995             : 
     996             :     /*
     997             :      * In the trivial case where we just had one "var = const" clause, push
     998             :      * the original clause back into the main planner machinery.  There is
     999             :      * nothing to be gained by doing it differently, and we save the effort to
    1000             :      * re-build and re-analyze an equality clause that will be exactly
    1001             :      * equivalent to the old one.
    1002             :      */
    1003      299018 :     if (list_length(ec->ec_members) == 2 &&
    1004      147012 :         list_length(ec->ec_sources) == 1)
    1005             :     {
    1006      147012 :         RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
    1007             : 
    1008      147012 :         if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
    1009             :         {
    1010      146970 :             distribute_restrictinfo_to_rels(root, restrictinfo);
    1011      146970 :             return;
    1012             :         }
    1013             :     }
    1014             : 
    1015             :     /*
    1016             :      * Find the constant member to use.  We prefer an actual constant to
    1017             :      * pseudo-constants (such as Params), because the constraint exclusion
    1018             :      * machinery might be able to exclude relations on the basis of generated
    1019             :      * "var = const" equalities, but "var = param" won't work for that.
    1020             :      */
    1021       13158 :     foreach(lc, ec->ec_members)
    1022             :     {
    1023       13150 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1024             : 
    1025       13150 :         if (cur_em->em_is_const)
    1026             :         {
    1027        5036 :             const_em = cur_em;
    1028        5036 :             if (IsA(cur_em->em_expr, Const))
    1029        5028 :                 break;
    1030             :         }
    1031             :     }
    1032             :     Assert(const_em != NULL);
    1033             : 
    1034             :     /* Generate a derived equality against each other member */
    1035       20162 :     foreach(lc, ec->ec_members)
    1036             :     {
    1037       15146 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1038             :         Oid         eq_op;
    1039             :         RestrictInfo *rinfo;
    1040             : 
    1041             :         Assert(!cur_em->em_is_child);    /* no children yet */
    1042       15146 :         if (cur_em == const_em)
    1043        5020 :             continue;
    1044       10126 :         eq_op = select_equality_operator(ec,
    1045             :                                          cur_em->em_datatype,
    1046             :                                          const_em->em_datatype);
    1047       10126 :         if (!OidIsValid(eq_op))
    1048             :         {
    1049             :             /* failed... */
    1050          20 :             ec->ec_broken = true;
    1051          20 :             break;
    1052             :         }
    1053       10106 :         rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
    1054             :                                          cur_em->em_expr, const_em->em_expr,
    1055       10106 :                                          bms_copy(ec->ec_relids),
    1056       10106 :                                          bms_union(cur_em->em_nullable_relids,
    1057       10106 :                                                    const_em->em_nullable_relids),
    1058             :                                          ec->ec_min_security,
    1059       10106 :                                          ec->ec_below_outer_join,
    1060       10106 :                                          cur_em->em_is_const);
    1061             : 
    1062             :         /*
    1063             :          * If the clause didn't degenerate to a constant, fill in the correct
    1064             :          * markings for a mergejoinable clause, and save it in ec_derives. (We
    1065             :          * will not re-use such clauses directly, but selectivity estimation
    1066             :          * may consult the list later.  Note that this use of ec_derives does
    1067             :          * not overlap with its use for join clauses, since we never generate
    1068             :          * join clauses from an ec_has_const eclass.)
    1069             :          */
    1070       10106 :         if (rinfo && rinfo->mergeopfamilies)
    1071             :         {
    1072             :             /* it's not redundant, so don't set parent_ec */
    1073       10026 :             rinfo->left_ec = rinfo->right_ec = ec;
    1074       10026 :             rinfo->left_em = cur_em;
    1075       10026 :             rinfo->right_em = const_em;
    1076       10026 :             ec->ec_derives = lappend(ec->ec_derives, rinfo);
    1077             :         }
    1078             :     }
    1079             : }
    1080             : 
    1081             : /*
    1082             :  * generate_base_implied_equalities when EC contains no pseudoconstants
    1083             :  */
    1084             : static void
    1085       24278 : generate_base_implied_equalities_no_const(PlannerInfo *root,
    1086             :                                           EquivalenceClass *ec)
    1087             : {
    1088             :     EquivalenceMember **prev_ems;
    1089             :     ListCell   *lc;
    1090             : 
    1091             :     /*
    1092             :      * We scan the EC members once and track the last-seen member for each
    1093             :      * base relation.  When we see another member of the same base relation,
    1094             :      * we generate "prev_em = cur_em".  This results in the minimum number of
    1095             :      * derived clauses, but it's possible that it will fail when a different
    1096             :      * ordering would succeed.  XXX FIXME: use a UNION-FIND algorithm similar
    1097             :      * to the way we build merged ECs.  (Use a list-of-lists for each rel.)
    1098             :      */
    1099             :     prev_ems = (EquivalenceMember **)
    1100       24278 :         palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
    1101             : 
    1102       73366 :     foreach(lc, ec->ec_members)
    1103             :     {
    1104       49088 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1105             :         int         relid;
    1106             : 
    1107             :         Assert(!cur_em->em_is_child);    /* no children yet */
    1108       49088 :         if (!bms_get_singleton_member(cur_em->em_relids, &relid))
    1109          48 :             continue;
    1110             :         Assert(relid < root->simple_rel_array_size);
    1111             : 
    1112       49040 :         if (prev_ems[relid] != NULL)
    1113             :         {
    1114         188 :             EquivalenceMember *prev_em = prev_ems[relid];
    1115             :             Oid         eq_op;
    1116             :             RestrictInfo *rinfo;
    1117             : 
    1118         188 :             eq_op = select_equality_operator(ec,
    1119             :                                              prev_em->em_datatype,
    1120             :                                              cur_em->em_datatype);
    1121         188 :             if (!OidIsValid(eq_op))
    1122             :             {
    1123             :                 /* failed... */
    1124           0 :                 ec->ec_broken = true;
    1125           0 :                 break;
    1126             :             }
    1127         188 :             rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
    1128             :                                              prev_em->em_expr, cur_em->em_expr,
    1129         188 :                                              bms_copy(ec->ec_relids),
    1130         188 :                                              bms_union(prev_em->em_nullable_relids,
    1131         188 :                                                        cur_em->em_nullable_relids),
    1132             :                                              ec->ec_min_security,
    1133         188 :                                              ec->ec_below_outer_join,
    1134             :                                              false);
    1135             : 
    1136             :             /*
    1137             :              * If the clause didn't degenerate to a constant, fill in the
    1138             :              * correct markings for a mergejoinable clause.  We don't put it
    1139             :              * in ec_derives however; we don't currently need to re-find such
    1140             :              * clauses, and we don't want to clutter that list with non-join
    1141             :              * clauses.
    1142             :              */
    1143         188 :             if (rinfo && rinfo->mergeopfamilies)
    1144             :             {
    1145             :                 /* it's not redundant, so don't set parent_ec */
    1146         188 :                 rinfo->left_ec = rinfo->right_ec = ec;
    1147         188 :                 rinfo->left_em = prev_em;
    1148         188 :                 rinfo->right_em = cur_em;
    1149             :             }
    1150             :         }
    1151       49040 :         prev_ems[relid] = cur_em;
    1152             :     }
    1153             : 
    1154       24278 :     pfree(prev_ems);
    1155             : 
    1156             :     /*
    1157             :      * We also have to make sure that all the Vars used in the member clauses
    1158             :      * will be available at any join node we might try to reference them at.
    1159             :      * For the moment we force all the Vars to be available at all join nodes
    1160             :      * for this eclass.  Perhaps this could be improved by doing some
    1161             :      * pre-analysis of which members we prefer to join, but it's no worse than
    1162             :      * what happened in the pre-8.3 code.
    1163             :      */
    1164       73366 :     foreach(lc, ec->ec_members)
    1165             :     {
    1166       49088 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1167       49088 :         List       *vars = pull_var_clause((Node *) cur_em->em_expr,
    1168             :                                            PVC_RECURSE_AGGREGATES |
    1169             :                                            PVC_RECURSE_WINDOWFUNCS |
    1170             :                                            PVC_INCLUDE_PLACEHOLDERS);
    1171             : 
    1172       49088 :         add_vars_to_targetlist(root, vars, ec->ec_relids, false);
    1173       49088 :         list_free(vars);
    1174             :     }
    1175       24278 : }
    1176             : 
    1177             : /*
    1178             :  * generate_base_implied_equalities cleanup after failure
    1179             :  *
    1180             :  * What we must do here is push any zero- or one-relation source RestrictInfos
    1181             :  * of the EC back into the main restrictinfo datastructures.  Multi-relation
    1182             :  * clauses will be regurgitated later by generate_join_implied_equalities().
    1183             :  * (We do it this way to maintain continuity with the case that ec_broken
    1184             :  * becomes set only after we've gone up a join level or two.)  However, for
    1185             :  * an EC that contains constants, we can adopt a simpler strategy and just
    1186             :  * throw back all the source RestrictInfos immediately; that works because
    1187             :  * we know that such an EC can't become broken later.  (This rule justifies
    1188             :  * ignoring ec_has_const ECs in generate_join_implied_equalities, even when
    1189             :  * they are broken.)
    1190             :  */
    1191             : static void
    1192          20 : generate_base_implied_equalities_broken(PlannerInfo *root,
    1193             :                                         EquivalenceClass *ec)
    1194             : {
    1195             :     ListCell   *lc;
    1196             : 
    1197          64 :     foreach(lc, ec->ec_sources)
    1198             :     {
    1199          44 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1200             : 
    1201          44 :         if (ec->ec_has_const ||
    1202           0 :             bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
    1203          44 :             distribute_restrictinfo_to_rels(root, restrictinfo);
    1204             :     }
    1205          20 : }
    1206             : 
    1207             : 
    1208             : /*
    1209             :  * generate_join_implied_equalities
    1210             :  *    Generate any join clauses that we can deduce from equivalence classes.
    1211             :  *
    1212             :  * At a join node, we must enforce restriction clauses sufficient to ensure
    1213             :  * that all equivalence-class members computable at that node are equal.
    1214             :  * Since the set of clauses to enforce can vary depending on which subset
    1215             :  * relations are the inputs, we have to compute this afresh for each join
    1216             :  * relation pair.  Hence a fresh List of RestrictInfo nodes is built and
    1217             :  * passed back on each call.
    1218             :  *
    1219             :  * In addition to its use at join nodes, this can be applied to generate
    1220             :  * eclass-based join clauses for use in a parameterized scan of a base rel.
    1221             :  * The reason for the asymmetry of specifying the inner rel as a RelOptInfo
    1222             :  * and the outer rel by Relids is that this usage occurs before we have
    1223             :  * built any join RelOptInfos.
    1224             :  *
    1225             :  * An annoying special case for parameterized scans is that the inner rel can
    1226             :  * be an appendrel child (an "other rel").  In this case we must generate
    1227             :  * appropriate clauses using child EC members.  add_child_rel_equivalences
    1228             :  * must already have been done for the child rel.
    1229             :  *
    1230             :  * The results are sufficient for use in merge, hash, and plain nestloop join
    1231             :  * methods.  We do not worry here about selecting clauses that are optimal
    1232             :  * for use in a parameterized indexscan.  indxpath.c makes its own selections
    1233             :  * of clauses to use, and if the ones we pick here are redundant with those,
    1234             :  * the extras will be eliminated at createplan time, using the parent_ec
    1235             :  * markers that we provide (see is_redundant_derived_clause()).
    1236             :  *
    1237             :  * Because the same join clauses are likely to be needed multiple times as
    1238             :  * we consider different join paths, we avoid generating multiple copies:
    1239             :  * whenever we select a particular pair of EquivalenceMembers to join,
    1240             :  * we check to see if the pair matches any original clause (in ec_sources)
    1241             :  * or previously-built clause (in ec_derives).  This saves memory and allows
    1242             :  * re-use of information cached in RestrictInfos.
    1243             :  *
    1244             :  * join_relids should always equal bms_union(outer_relids, inner_rel->relids).
    1245             :  * We could simplify this function's API by computing it internally, but in
    1246             :  * most current uses, the caller has the value at hand anyway.
    1247             :  */
    1248             : List *
    1249      228890 : generate_join_implied_equalities(PlannerInfo *root,
    1250             :                                  Relids join_relids,
    1251             :                                  Relids outer_relids,
    1252             :                                  RelOptInfo *inner_rel)
    1253             : {
    1254      228890 :     List       *result = NIL;
    1255      228890 :     Relids      inner_relids = inner_rel->relids;
    1256             :     Relids      nominal_inner_relids;
    1257             :     Relids      nominal_join_relids;
    1258             :     Bitmapset  *matching_ecs;
    1259             :     int         i;
    1260             : 
    1261             :     /* If inner rel is a child, extra setup work is needed */
    1262      228890 :     if (IS_OTHER_REL(inner_rel))
    1263             :     {
    1264             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1265             : 
    1266             :         /* Fetch relid set for the topmost parent rel */
    1267        4128 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1268             :         /* ECs will be marked with the parent's relid, not the child's */
    1269        4128 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1270             :     }
    1271             :     else
    1272             :     {
    1273      224762 :         nominal_inner_relids = inner_relids;
    1274      224762 :         nominal_join_relids = join_relids;
    1275             :     }
    1276             : 
    1277             :     /*
    1278             :      * Get all eclasses that mention both inner and outer sides of the join
    1279             :      */
    1280      228890 :     matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
    1281             :                                              outer_relids);
    1282             : 
    1283      228890 :     i = -1;
    1284      358788 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    1285             :     {
    1286      129898 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    1287      129898 :         List       *sublist = NIL;
    1288             : 
    1289             :         /* ECs containing consts do not need any further enforcement */
    1290      129898 :         if (ec->ec_has_const)
    1291       20084 :             continue;
    1292             : 
    1293             :         /* Single-member ECs won't generate any deductions */
    1294      109814 :         if (list_length(ec->ec_members) <= 1)
    1295         614 :             continue;
    1296             : 
    1297             :         /* Sanity check that this eclass overlaps the join */
    1298             :         Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
    1299             : 
    1300      109200 :         if (!ec->ec_broken)
    1301      109028 :             sublist = generate_join_implied_equalities_normal(root,
    1302             :                                                               ec,
    1303             :                                                               join_relids,
    1304             :                                                               outer_relids,
    1305             :                                                               inner_relids);
    1306             : 
    1307             :         /* Recover if we failed to generate required derived clauses */
    1308      109200 :         if (ec->ec_broken)
    1309         192 :             sublist = generate_join_implied_equalities_broken(root,
    1310             :                                                               ec,
    1311             :                                                               nominal_join_relids,
    1312             :                                                               outer_relids,
    1313             :                                                               nominal_inner_relids,
    1314             :                                                               inner_rel);
    1315             : 
    1316      109200 :         result = list_concat(result, sublist);
    1317             :     }
    1318             : 
    1319      228890 :     return result;
    1320             : }
    1321             : 
    1322             : /*
    1323             :  * generate_join_implied_equalities_for_ecs
    1324             :  *    As above, but consider only the listed ECs.
    1325             :  */
    1326             : List *
    1327         458 : generate_join_implied_equalities_for_ecs(PlannerInfo *root,
    1328             :                                          List *eclasses,
    1329             :                                          Relids join_relids,
    1330             :                                          Relids outer_relids,
    1331             :                                          RelOptInfo *inner_rel)
    1332             : {
    1333         458 :     List       *result = NIL;
    1334         458 :     Relids      inner_relids = inner_rel->relids;
    1335             :     Relids      nominal_inner_relids;
    1336             :     Relids      nominal_join_relids;
    1337             :     ListCell   *lc;
    1338             : 
    1339             :     /* If inner rel is a child, extra setup work is needed */
    1340         458 :     if (IS_OTHER_REL(inner_rel))
    1341             :     {
    1342             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1343             : 
    1344             :         /* Fetch relid set for the topmost parent rel */
    1345           0 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1346             :         /* ECs will be marked with the parent's relid, not the child's */
    1347           0 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1348             :     }
    1349             :     else
    1350             :     {
    1351         458 :         nominal_inner_relids = inner_relids;
    1352         458 :         nominal_join_relids = join_relids;
    1353             :     }
    1354             : 
    1355         936 :     foreach(lc, eclasses)
    1356             :     {
    1357         478 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
    1358         478 :         List       *sublist = NIL;
    1359             : 
    1360             :         /* ECs containing consts do not need any further enforcement */
    1361         478 :         if (ec->ec_has_const)
    1362           0 :             continue;
    1363             : 
    1364             :         /* Single-member ECs won't generate any deductions */
    1365         478 :         if (list_length(ec->ec_members) <= 1)
    1366           0 :             continue;
    1367             : 
    1368             :         /* We can quickly ignore any that don't overlap the join, too */
    1369         478 :         if (!bms_overlap(ec->ec_relids, nominal_join_relids))
    1370           0 :             continue;
    1371             : 
    1372         478 :         if (!ec->ec_broken)
    1373         478 :             sublist = generate_join_implied_equalities_normal(root,
    1374             :                                                               ec,
    1375             :                                                               join_relids,
    1376             :                                                               outer_relids,
    1377             :                                                               inner_relids);
    1378             : 
    1379             :         /* Recover if we failed to generate required derived clauses */
    1380         478 :         if (ec->ec_broken)
    1381           0 :             sublist = generate_join_implied_equalities_broken(root,
    1382             :                                                               ec,
    1383             :                                                               nominal_join_relids,
    1384             :                                                               outer_relids,
    1385             :                                                               nominal_inner_relids,
    1386             :                                                               inner_rel);
    1387             : 
    1388         478 :         result = list_concat(result, sublist);
    1389             :     }
    1390             : 
    1391         458 :     return result;
    1392             : }
    1393             : 
    1394             : /*
    1395             :  * generate_join_implied_equalities for a still-valid EC
    1396             :  */
    1397             : static List *
    1398      109506 : generate_join_implied_equalities_normal(PlannerInfo *root,
    1399             :                                         EquivalenceClass *ec,
    1400             :                                         Relids join_relids,
    1401             :                                         Relids outer_relids,
    1402             :                                         Relids inner_relids)
    1403             : {
    1404      109506 :     List       *result = NIL;
    1405      109506 :     List       *new_members = NIL;
    1406      109506 :     List       *outer_members = NIL;
    1407      109506 :     List       *inner_members = NIL;
    1408             :     ListCell   *lc1;
    1409             : 
    1410             :     /*
    1411             :      * First, scan the EC to identify member values that are computable at the
    1412             :      * outer rel, at the inner rel, or at this relation but not in either
    1413             :      * input rel.  The outer-rel members should already be enforced equal,
    1414             :      * likewise for the inner-rel members.  We'll need to create clauses to
    1415             :      * enforce that any newly computable members are all equal to each other
    1416             :      * as well as to at least one input member, plus enforce at least one
    1417             :      * outer-rel member equal to at least one inner-rel member.
    1418             :      */
    1419      374190 :     foreach(lc1, ec->ec_members)
    1420             :     {
    1421      264684 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
    1422             : 
    1423             :         /*
    1424             :          * We don't need to check explicitly for child EC members.  This test
    1425             :          * against join_relids will cause them to be ignored except when
    1426             :          * considering a child inner rel, which is what we want.
    1427             :          */
    1428      264684 :         if (!bms_is_subset(cur_em->em_relids, join_relids))
    1429       41634 :             continue;           /* not computable yet, or wrong child */
    1430             : 
    1431      223050 :         if (bms_is_subset(cur_em->em_relids, outer_relids))
    1432      112552 :             outer_members = lappend(outer_members, cur_em);
    1433      110498 :         else if (bms_is_subset(cur_em->em_relids, inner_relids))
    1434      109714 :             inner_members = lappend(inner_members, cur_em);
    1435             :         else
    1436         784 :             new_members = lappend(new_members, cur_em);
    1437             :     }
    1438             : 
    1439             :     /*
    1440             :      * First, select the joinclause if needed.  We can equate any one outer
    1441             :      * member to any one inner member, but we have to find a datatype
    1442             :      * combination for which an opfamily member operator exists.  If we have
    1443             :      * choices, we prefer simple Var members (possibly with RelabelType) since
    1444             :      * these are (a) cheapest to compute at runtime and (b) most likely to
    1445             :      * have useful statistics. Also, prefer operators that are also
    1446             :      * hashjoinable.
    1447             :      */
    1448      109506 :     if (outer_members && inner_members)
    1449             :     {
    1450      108080 :         EquivalenceMember *best_outer_em = NULL;
    1451      108080 :         EquivalenceMember *best_inner_em = NULL;
    1452      108080 :         Oid         best_eq_op = InvalidOid;
    1453      108080 :         int         best_score = -1;
    1454             :         RestrictInfo *rinfo;
    1455             : 
    1456      110918 :         foreach(lc1, outer_members)
    1457             :         {
    1458      108128 :             EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
    1459             :             ListCell   *lc2;
    1460             : 
    1461      110974 :             foreach(lc2, inner_members)
    1462             :             {
    1463      108136 :                 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
    1464             :                 Oid         eq_op;
    1465             :                 int         score;
    1466             : 
    1467      108136 :                 eq_op = select_equality_operator(ec,
    1468             :                                                  outer_em->em_datatype,
    1469             :                                                  inner_em->em_datatype);
    1470      108136 :                 if (!OidIsValid(eq_op))
    1471          20 :                     continue;
    1472      108116 :                 score = 0;
    1473      108116 :                 if (IsA(outer_em->em_expr, Var) ||
    1474        4022 :                     (IsA(outer_em->em_expr, RelabelType) &&
    1475        2476 :                      IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
    1476      106538 :                     score++;
    1477      108116 :                 if (IsA(inner_em->em_expr, Var) ||
    1478        4182 :                     (IsA(inner_em->em_expr, RelabelType) &&
    1479        2676 :                      IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
    1480      106598 :                     score++;
    1481      108116 :                 if (op_hashjoinable(eq_op,
    1482      108116 :                                     exprType((Node *) outer_em->em_expr)))
    1483      108090 :                     score++;
    1484      108116 :                 if (score > best_score)
    1485             :                 {
    1486      108060 :                     best_outer_em = outer_em;
    1487      108060 :                     best_inner_em = inner_em;
    1488      108060 :                     best_eq_op = eq_op;
    1489      108060 :                     best_score = score;
    1490      108060 :                     if (best_score == 3)
    1491      105290 :                         break;  /* no need to look further */
    1492             :                 }
    1493             :             }
    1494      108128 :             if (best_score == 3)
    1495      105290 :                 break;          /* no need to look further */
    1496             :         }
    1497      108080 :         if (best_score < 0)
    1498             :         {
    1499             :             /* failed... */
    1500          20 :             ec->ec_broken = true;
    1501          20 :             return NIL;
    1502             :         }
    1503             : 
    1504             :         /*
    1505             :          * Create clause, setting parent_ec to mark it as redundant with other
    1506             :          * joinclauses
    1507             :          */
    1508      108060 :         rinfo = create_join_clause(root, ec, best_eq_op,
    1509             :                                    best_outer_em, best_inner_em,
    1510             :                                    ec);
    1511             : 
    1512      108060 :         result = lappend(result, rinfo);
    1513             :     }
    1514             : 
    1515             :     /*
    1516             :      * Now deal with building restrictions for any expressions that involve
    1517             :      * Vars from both sides of the join.  We have to equate all of these to
    1518             :      * each other as well as to at least one old member (if any).
    1519             :      *
    1520             :      * XXX as in generate_base_implied_equalities_no_const, we could be a lot
    1521             :      * smarter here to avoid unnecessary failures in cross-type situations.
    1522             :      * For now, use the same left-to-right method used there.
    1523             :      */
    1524      109486 :     if (new_members)
    1525             :     {
    1526         784 :         List       *old_members = list_concat(outer_members, inner_members);
    1527         784 :         EquivalenceMember *prev_em = NULL;
    1528             :         RestrictInfo *rinfo;
    1529             : 
    1530             :         /* For now, arbitrarily take the first old_member as the one to use */
    1531         784 :         if (old_members)
    1532         596 :             new_members = lappend(new_members, linitial(old_members));
    1533             : 
    1534        2164 :         foreach(lc1, new_members)
    1535             :         {
    1536        1380 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
    1537             : 
    1538        1380 :             if (prev_em != NULL)
    1539             :             {
    1540             :                 Oid         eq_op;
    1541             : 
    1542         596 :                 eq_op = select_equality_operator(ec,
    1543             :                                                  prev_em->em_datatype,
    1544             :                                                  cur_em->em_datatype);
    1545         596 :                 if (!OidIsValid(eq_op))
    1546             :                 {
    1547             :                     /* failed... */
    1548           0 :                     ec->ec_broken = true;
    1549           0 :                     return NIL;
    1550             :                 }
    1551             :                 /* do NOT set parent_ec, this qual is not redundant! */
    1552         596 :                 rinfo = create_join_clause(root, ec, eq_op,
    1553             :                                            prev_em, cur_em,
    1554             :                                            NULL);
    1555             : 
    1556         596 :                 result = lappend(result, rinfo);
    1557             :             }
    1558        1380 :             prev_em = cur_em;
    1559             :         }
    1560             :     }
    1561             : 
    1562      109486 :     return result;
    1563             : }
    1564             : 
    1565             : /*
    1566             :  * generate_join_implied_equalities cleanup after failure
    1567             :  *
    1568             :  * Return any original RestrictInfos that are enforceable at this join.
    1569             :  *
    1570             :  * In the case of a child inner relation, we have to translate the
    1571             :  * original RestrictInfos from parent to child Vars.
    1572             :  */
    1573             : static List *
    1574         192 : generate_join_implied_equalities_broken(PlannerInfo *root,
    1575             :                                         EquivalenceClass *ec,
    1576             :                                         Relids nominal_join_relids,
    1577             :                                         Relids outer_relids,
    1578             :                                         Relids nominal_inner_relids,
    1579             :                                         RelOptInfo *inner_rel)
    1580             : {
    1581         192 :     List       *result = NIL;
    1582             :     ListCell   *lc;
    1583             : 
    1584         528 :     foreach(lc, ec->ec_sources)
    1585             :     {
    1586         336 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1587         336 :         Relids      clause_relids = restrictinfo->required_relids;
    1588             : 
    1589         336 :         if (bms_is_subset(clause_relids, nominal_join_relids) &&
    1590         184 :             !bms_is_subset(clause_relids, outer_relids) &&
    1591         168 :             !bms_is_subset(clause_relids, nominal_inner_relids))
    1592         168 :             result = lappend(result, restrictinfo);
    1593             :     }
    1594             : 
    1595             :     /*
    1596             :      * If we have to translate, just brute-force apply adjust_appendrel_attrs
    1597             :      * to all the RestrictInfos at once.  This will result in returning
    1598             :      * RestrictInfos that are not listed in ec_derives, but there shouldn't be
    1599             :      * any duplication, and it's a sufficiently narrow corner case that we
    1600             :      * shouldn't sweat too much over it anyway.
    1601             :      *
    1602             :      * Since inner_rel might be an indirect descendant of the baserel
    1603             :      * mentioned in the ec_sources clauses, we have to be prepared to apply
    1604             :      * multiple levels of Var translation.
    1605             :      */
    1606         192 :     if (IS_OTHER_REL(inner_rel) && result != NIL)
    1607         108 :         result = (List *) adjust_appendrel_attrs_multilevel(root,
    1608             :                                                             (Node *) result,
    1609             :                                                             inner_rel->relids,
    1610             :                                                             inner_rel->top_parent_relids);
    1611             : 
    1612         192 :     return result;
    1613             : }
    1614             : 
    1615             : 
    1616             : /*
    1617             :  * select_equality_operator
    1618             :  *    Select a suitable equality operator for comparing two EC members
    1619             :  *
    1620             :  * Returns InvalidOid if no operator can be found for this datatype combination
    1621             :  */
    1622             : static Oid
    1623      165742 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
    1624             : {
    1625             :     ListCell   *lc;
    1626             : 
    1627      165782 :     foreach(lc, ec->ec_opfamilies)
    1628             :     {
    1629      165742 :         Oid         opfamily = lfirst_oid(lc);
    1630             :         Oid         opno;
    1631             : 
    1632      165742 :         opno = get_opfamily_member(opfamily, lefttype, righttype,
    1633             :                                    BTEqualStrategyNumber);
    1634      165742 :         if (!OidIsValid(opno))
    1635          40 :             continue;
    1636             :         /* If no barrier quals in query, don't worry about leaky operators */
    1637      165702 :         if (ec->ec_max_security == 0)
    1638      165702 :             return opno;
    1639             :         /* Otherwise, insist that selected operators be leakproof */
    1640         384 :         if (get_func_leakproof(get_opcode(opno)))
    1641         384 :             return opno;
    1642             :     }
    1643          40 :     return InvalidOid;
    1644             : }
    1645             : 
    1646             : 
    1647             : /*
    1648             :  * create_join_clause
    1649             :  *    Find or make a RestrictInfo comparing the two given EC members
    1650             :  *    with the given operator.
    1651             :  *
    1652             :  * parent_ec is either equal to ec (if the clause is a potentially-redundant
    1653             :  * join clause) or NULL (if not).  We have to treat this as part of the
    1654             :  * match requirements --- it's possible that a clause comparing the same two
    1655             :  * EMs is a join clause in one join path and a restriction clause in another.
    1656             :  */
    1657             : static RestrictInfo *
    1658      149318 : create_join_clause(PlannerInfo *root,
    1659             :                    EquivalenceClass *ec, Oid opno,
    1660             :                    EquivalenceMember *leftem,
    1661             :                    EquivalenceMember *rightem,
    1662             :                    EquivalenceClass *parent_ec)
    1663             : {
    1664             :     RestrictInfo *rinfo;
    1665             :     ListCell   *lc;
    1666             :     MemoryContext oldcontext;
    1667             : 
    1668             :     /*
    1669             :      * Search to see if we already built a RestrictInfo for this pair of
    1670             :      * EquivalenceMembers.  We can use either original source clauses or
    1671             :      * previously-derived clauses.  The check on opno is probably redundant,
    1672             :      * but be safe ...
    1673             :      */
    1674      313672 :     foreach(lc, ec->ec_sources)
    1675             :     {
    1676      164402 :         rinfo = (RestrictInfo *) lfirst(lc);
    1677      164402 :         if (rinfo->left_em == leftem &&
    1678       75744 :             rinfo->right_em == rightem &&
    1679       69614 :             rinfo->parent_ec == parent_ec &&
    1680          48 :             opno == ((OpExpr *) rinfo->clause)->opno)
    1681          48 :             return rinfo;
    1682             :     }
    1683             : 
    1684      297674 :     foreach(lc, ec->ec_derives)
    1685             :     {
    1686      246260 :         rinfo = (RestrictInfo *) lfirst(lc);
    1687      246260 :         if (rinfo->left_em == leftem &&
    1688      113254 :             rinfo->right_em == rightem &&
    1689       98288 :             rinfo->parent_ec == parent_ec &&
    1690       97856 :             opno == ((OpExpr *) rinfo->clause)->opno)
    1691       97856 :             return rinfo;
    1692             :     }
    1693             : 
    1694             :     /*
    1695             :      * Not there, so build it, in planner context so we can re-use it. (Not
    1696             :      * important in normal planning, but definitely so in GEQO.)
    1697             :      */
    1698       51414 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    1699             : 
    1700       51414 :     rinfo = build_implied_join_equality(root,
    1701             :                                         opno,
    1702             :                                         ec->ec_collation,
    1703             :                                         leftem->em_expr,
    1704             :                                         rightem->em_expr,
    1705       51414 :                                         bms_union(leftem->em_relids,
    1706       51414 :                                                   rightem->em_relids),
    1707       51414 :                                         bms_union(leftem->em_nullable_relids,
    1708       51414 :                                                   rightem->em_nullable_relids),
    1709             :                                         ec->ec_min_security);
    1710             : 
    1711             :     /* Mark the clause as redundant, or not */
    1712       51414 :     rinfo->parent_ec = parent_ec;
    1713             : 
    1714             :     /*
    1715             :      * We know the correct values for left_ec/right_ec, ie this particular EC,
    1716             :      * so we can just set them directly instead of forcing another lookup.
    1717             :      */
    1718       51414 :     rinfo->left_ec = ec;
    1719       51414 :     rinfo->right_ec = ec;
    1720             : 
    1721             :     /* Mark it as usable with these EMs */
    1722       51414 :     rinfo->left_em = leftem;
    1723       51414 :     rinfo->right_em = rightem;
    1724             :     /* and save it for possible re-use */
    1725       51414 :     ec->ec_derives = lappend(ec->ec_derives, rinfo);
    1726             : 
    1727       51414 :     MemoryContextSwitchTo(oldcontext);
    1728             : 
    1729       51414 :     return rinfo;
    1730             : }
    1731             : 
    1732             : 
    1733             : /*
    1734             :  * reconsider_outer_join_clauses
    1735             :  *    Re-examine any outer-join clauses that were set aside by
    1736             :  *    distribute_qual_to_rels(), and see if we can derive any
    1737             :  *    EquivalenceClasses from them.  Then, if they were not made
    1738             :  *    redundant, push them out into the regular join-clause lists.
    1739             :  *
    1740             :  * When we have mergejoinable clauses A = B that are outer-join clauses,
    1741             :  * we can't blindly combine them with other clauses A = C to deduce B = C,
    1742             :  * since in fact the "equality" A = B won't necessarily hold above the
    1743             :  * outer join (one of the variables might be NULL instead).  Nonetheless
    1744             :  * there are cases where we can add qual clauses using transitivity.
    1745             :  *
    1746             :  * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
    1747             :  * for which there is also an equivalence clause OUTERVAR = CONSTANT.
    1748             :  * It is safe and useful to push a clause INNERVAR = CONSTANT into the
    1749             :  * evaluation of the inner (nullable) relation, because any inner rows not
    1750             :  * meeting this condition will not contribute to the outer-join result anyway.
    1751             :  * (Any outer rows they could join to will be eliminated by the pushed-down
    1752             :  * equivalence clause.)
    1753             :  *
    1754             :  * Note that the above rule does not work for full outer joins; nor is it
    1755             :  * very interesting to consider cases where the generated equivalence clause
    1756             :  * would involve relations outside the outer join, since such clauses couldn't
    1757             :  * be pushed into the inner side's scan anyway.  So the restriction to
    1758             :  * outervar = pseudoconstant is not really giving up anything.
    1759             :  *
    1760             :  * For full-join cases, we can only do something useful if it's a FULL JOIN
    1761             :  * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
    1762             :  * By the time it gets here, the merged column will look like
    1763             :  *      COALESCE(LEFTVAR, RIGHTVAR)
    1764             :  * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
    1765             :  * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
    1766             :  * and RIGHTVAR = CONSTANT into the input relations, since any rows not
    1767             :  * meeting these conditions cannot contribute to the join result.
    1768             :  *
    1769             :  * Again, there isn't any traction to be gained by trying to deal with
    1770             :  * clauses comparing a mergedvar to a non-pseudoconstant.  So we can make
    1771             :  * use of the EquivalenceClasses to search for matching variables that were
    1772             :  * equivalenced to constants.  The interesting outer-join clauses were
    1773             :  * accumulated for us by distribute_qual_to_rels.
    1774             :  *
    1775             :  * When we find one of these cases, we implement the changes we want by
    1776             :  * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
    1777             :  * and pushing it into the EquivalenceClass structures.  This is because we
    1778             :  * may already know that INNERVAR is equivalenced to some other var(s), and
    1779             :  * we'd like the constant to propagate to them too.  Note that it would be
    1780             :  * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
    1781             :  * that could result in propagating constant restrictions from
    1782             :  * INNERVAR to OUTERVAR, which would be very wrong.
    1783             :  *
    1784             :  * It's possible that the INNERVAR is also an OUTERVAR for some other
    1785             :  * outer-join clause, in which case the process can be repeated.  So we repeat
    1786             :  * looping over the lists of clauses until no further deductions can be made.
    1787             :  * Whenever we do make a deduction, we remove the generating clause from the
    1788             :  * lists, since we don't want to make the same deduction twice.
    1789             :  *
    1790             :  * If we don't find any match for a set-aside outer join clause, we must
    1791             :  * throw it back into the regular joinclause processing by passing it to
    1792             :  * distribute_restrictinfo_to_rels().  If we do generate a derived clause,
    1793             :  * however, the outer-join clause is redundant.  We still throw it back,
    1794             :  * because otherwise the join will be seen as a clauseless join and avoided
    1795             :  * during join order searching; but we mark it as redundant to keep from
    1796             :  * messing up the joinrel's size estimate.  (This behavior means that the
    1797             :  * API for this routine is uselessly complex: we could have just put all
    1798             :  * the clauses into the regular processing initially.  We keep it because
    1799             :  * someday we might want to do something else, such as inserting "dummy"
    1800             :  * joinclauses instead of real ones.)
    1801             :  *
    1802             :  * Outer join clauses that are marked outerjoin_delayed are special: this
    1803             :  * condition means that one or both VARs might go to null due to a lower
    1804             :  * outer join.  We can still push a constant through the clause, but only
    1805             :  * if its operator is strict; and we *have to* throw the clause back into
    1806             :  * regular joinclause processing.  By keeping the strict join clause,
    1807             :  * we ensure that any null-extended rows that are mistakenly generated due
    1808             :  * to suppressing rows not matching the constant will be rejected at the
    1809             :  * upper outer join.  (This doesn't work for full-join clauses.)
    1810             :  */
    1811             : void
    1812      215858 : reconsider_outer_join_clauses(PlannerInfo *root)
    1813             : {
    1814             :     bool        found;
    1815             :     ListCell   *cell;
    1816             : 
    1817             :     /* Outer loop repeats until we find no more deductions */
    1818             :     do
    1819             :     {
    1820      215858 :         found = false;
    1821             : 
    1822             :         /* Process the LEFT JOIN clauses */
    1823      249276 :         foreach(cell, root->left_join_clauses)
    1824             :         {
    1825       33418 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1826             : 
    1827       33418 :             if (reconsider_outer_join_clause(root, rinfo, true))
    1828             :             {
    1829        5566 :                 found = true;
    1830             :                 /* remove it from the list */
    1831        5566 :                 root->left_join_clauses =
    1832        5566 :                     foreach_delete_current(root->left_join_clauses, cell);
    1833             :                 /* we throw it back anyway (see notes above) */
    1834             :                 /* but the thrown-back clause has no extra selectivity */
    1835        5566 :                 rinfo->norm_selec = 2.0;
    1836        5566 :                 rinfo->outer_selec = 1.0;
    1837        5566 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1838             :             }
    1839             :         }
    1840             : 
    1841             :         /* Process the RIGHT JOIN clauses */
    1842      227688 :         foreach(cell, root->right_join_clauses)
    1843             :         {
    1844       11830 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1845             : 
    1846       11830 :             if (reconsider_outer_join_clause(root, rinfo, false))
    1847             :             {
    1848         432 :                 found = true;
    1849             :                 /* remove it from the list */
    1850         432 :                 root->right_join_clauses =
    1851         432 :                     foreach_delete_current(root->right_join_clauses, cell);
    1852             :                 /* we throw it back anyway (see notes above) */
    1853             :                 /* but the thrown-back clause has no extra selectivity */
    1854         432 :                 rinfo->norm_selec = 2.0;
    1855         432 :                 rinfo->outer_selec = 1.0;
    1856         432 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1857             :             }
    1858             :         }
    1859             : 
    1860             :         /* Process the FULL JOIN clauses */
    1861      216572 :         foreach(cell, root->full_join_clauses)
    1862             :         {
    1863         714 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1864             : 
    1865         714 :             if (reconsider_full_join_clause(root, rinfo))
    1866             :             {
    1867           4 :                 found = true;
    1868             :                 /* remove it from the list */
    1869           4 :                 root->full_join_clauses =
    1870           4 :                     foreach_delete_current(root->full_join_clauses, cell);
    1871             :                 /* we throw it back anyway (see notes above) */
    1872             :                 /* but the thrown-back clause has no extra selectivity */
    1873           4 :                 rinfo->norm_selec = 2.0;
    1874           4 :                 rinfo->outer_selec = 1.0;
    1875           4 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1876             :             }
    1877             :         }
    1878      215858 :     } while (found);
    1879             : 
    1880             :     /* Now, any remaining clauses have to be thrown back */
    1881      235728 :     foreach(cell, root->left_join_clauses)
    1882             :     {
    1883       25864 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1884             : 
    1885       25864 :         distribute_restrictinfo_to_rels(root, rinfo);
    1886             :     }
    1887      219332 :     foreach(cell, root->right_join_clauses)
    1888             :     {
    1889        9468 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1890             : 
    1891        9468 :         distribute_restrictinfo_to_rels(root, rinfo);
    1892             :     }
    1893      210574 :     foreach(cell, root->full_join_clauses)
    1894             :     {
    1895         710 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1896             : 
    1897         710 :         distribute_restrictinfo_to_rels(root, rinfo);
    1898             :     }
    1899      209864 : }
    1900             : 
    1901             : /*
    1902             :  * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
    1903             :  *
    1904             :  * Returns true if we were able to propagate a constant through the clause.
    1905             :  */
    1906             : static bool
    1907       45248 : reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo,
    1908             :                              bool outer_on_left)
    1909             : {
    1910             :     Expr       *outervar,
    1911             :                *innervar;
    1912             :     Oid         opno,
    1913             :                 collation,
    1914             :                 left_type,
    1915             :                 right_type,
    1916             :                 inner_datatype;
    1917             :     Relids      inner_relids,
    1918             :                 inner_nullable_relids;
    1919             :     ListCell   *lc1;
    1920             : 
    1921             :     Assert(is_opclause(rinfo->clause));
    1922       45248 :     opno = ((OpExpr *) rinfo->clause)->opno;
    1923       45248 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    1924             : 
    1925             :     /* If clause is outerjoin_delayed, operator must be strict */
    1926       45248 :     if (rinfo->outerjoin_delayed && !op_strict(opno))
    1927           0 :         return false;
    1928             : 
    1929             :     /* Extract needed info from the clause */
    1930       45248 :     op_input_types(opno, &left_type, &right_type);
    1931       45248 :     if (outer_on_left)
    1932             :     {
    1933       33418 :         outervar = (Expr *) get_leftop(rinfo->clause);
    1934       33418 :         innervar = (Expr *) get_rightop(rinfo->clause);
    1935       33418 :         inner_datatype = right_type;
    1936       33418 :         inner_relids = rinfo->right_relids;
    1937             :     }
    1938             :     else
    1939             :     {
    1940       11830 :         outervar = (Expr *) get_rightop(rinfo->clause);
    1941       11830 :         innervar = (Expr *) get_leftop(rinfo->clause);
    1942       11830 :         inner_datatype = left_type;
    1943       11830 :         inner_relids = rinfo->left_relids;
    1944             :     }
    1945       45248 :     inner_nullable_relids = bms_intersect(inner_relids,
    1946       45248 :                                           rinfo->nullable_relids);
    1947             : 
    1948             :     /* Scan EquivalenceClasses for a match to outervar */
    1949      223544 :     foreach(lc1, root->eq_classes)
    1950             :     {
    1951      184294 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    1952             :         bool        match;
    1953             :         ListCell   *lc2;
    1954             : 
    1955             :         /* Ignore EC unless it contains pseudoconstants */
    1956      184294 :         if (!cur_ec->ec_has_const)
    1957      126028 :             continue;
    1958             :         /* Never match to a volatile EC */
    1959       58266 :         if (cur_ec->ec_has_volatile)
    1960           0 :             continue;
    1961             :         /* It has to match the outer-join clause as to semantics, too */
    1962       58266 :         if (collation != cur_ec->ec_collation)
    1963        1724 :             continue;
    1964       56542 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    1965       10156 :             continue;
    1966             :         /* Does it contain a match to outervar? */
    1967       46386 :         match = false;
    1968      136638 :         foreach(lc2, cur_ec->ec_members)
    1969             :         {
    1970       96250 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    1971             : 
    1972             :             Assert(!cur_em->em_is_child);    /* no children yet */
    1973       96250 :             if (equal(outervar, cur_em->em_expr))
    1974             :             {
    1975        5998 :                 match = true;
    1976        5998 :                 break;
    1977             :             }
    1978             :         }
    1979       46386 :         if (!match)
    1980       40388 :             continue;           /* no match, so ignore this EC */
    1981             : 
    1982             :         /*
    1983             :          * Yes it does!  Try to generate a clause INNERVAR = CONSTANT for each
    1984             :          * CONSTANT in the EC.  Note that we must succeed with at least one
    1985             :          * constant before we can decide to throw away the outer-join clause.
    1986             :          */
    1987        5998 :         match = false;
    1988       20454 :         foreach(lc2, cur_ec->ec_members)
    1989             :         {
    1990       14456 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    1991             :             Oid         eq_op;
    1992             :             RestrictInfo *newrinfo;
    1993             : 
    1994       14456 :             if (!cur_em->em_is_const)
    1995        8430 :                 continue;       /* ignore non-const members */
    1996        6026 :             eq_op = select_equality_operator(cur_ec,
    1997             :                                              inner_datatype,
    1998             :                                              cur_em->em_datatype);
    1999        6026 :             if (!OidIsValid(eq_op))
    2000           0 :                 continue;       /* can't generate equality */
    2001        6026 :             newrinfo = build_implied_join_equality(root,
    2002             :                                                    eq_op,
    2003             :                                                    cur_ec->ec_collation,
    2004             :                                                    innervar,
    2005             :                                                    cur_em->em_expr,
    2006             :                                                    bms_copy(inner_relids),
    2007             :                                                    bms_copy(inner_nullable_relids),
    2008             :                                                    cur_ec->ec_min_security);
    2009        6026 :             if (process_equivalence(root, &newrinfo, true))
    2010        6026 :                 match = true;
    2011             :         }
    2012             : 
    2013             :         /*
    2014             :          * If we were able to equate INNERVAR to any constant, report success.
    2015             :          * Otherwise, fall out of the search loop, since we know the OUTERVAR
    2016             :          * appears in at most one EC.
    2017             :          */
    2018        5998 :         if (match)
    2019        5998 :             return true;
    2020             :         else
    2021           0 :             break;
    2022             :     }
    2023             : 
    2024       39250 :     return false;               /* failed to make any deduction */
    2025             : }
    2026             : 
    2027             : /*
    2028             :  * reconsider_outer_join_clauses for a single FULL JOIN clause
    2029             :  *
    2030             :  * Returns true if we were able to propagate a constant through the clause.
    2031             :  */
    2032             : static bool
    2033         714 : reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
    2034             : {
    2035             :     Expr       *leftvar;
    2036             :     Expr       *rightvar;
    2037             :     Oid         opno,
    2038             :                 collation,
    2039             :                 left_type,
    2040             :                 right_type;
    2041             :     Relids      left_relids,
    2042             :                 right_relids,
    2043             :                 left_nullable_relids,
    2044             :                 right_nullable_relids;
    2045             :     ListCell   *lc1;
    2046             : 
    2047             :     /* Can't use an outerjoin_delayed clause here */
    2048         714 :     if (rinfo->outerjoin_delayed)
    2049          38 :         return false;
    2050             : 
    2051             :     /* Extract needed info from the clause */
    2052             :     Assert(is_opclause(rinfo->clause));
    2053         676 :     opno = ((OpExpr *) rinfo->clause)->opno;
    2054         676 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    2055         676 :     op_input_types(opno, &left_type, &right_type);
    2056         676 :     leftvar = (Expr *) get_leftop(rinfo->clause);
    2057         676 :     rightvar = (Expr *) get_rightop(rinfo->clause);
    2058         676 :     left_relids = rinfo->left_relids;
    2059         676 :     right_relids = rinfo->right_relids;
    2060         676 :     left_nullable_relids = bms_intersect(left_relids,
    2061         676 :                                          rinfo->nullable_relids);
    2062         676 :     right_nullable_relids = bms_intersect(right_relids,
    2063         676 :                                           rinfo->nullable_relids);
    2064             : 
    2065        3508 :     foreach(lc1, root->eq_classes)
    2066             :     {
    2067        2836 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    2068        2836 :         EquivalenceMember *coal_em = NULL;
    2069             :         bool        match;
    2070             :         bool        matchleft;
    2071             :         bool        matchright;
    2072             :         ListCell   *lc2;
    2073        2836 :         int         coal_idx = -1;
    2074             : 
    2075             :         /* Ignore EC unless it contains pseudoconstants */
    2076        2836 :         if (!cur_ec->ec_has_const)
    2077        2660 :             continue;
    2078             :         /* Never match to a volatile EC */
    2079         176 :         if (cur_ec->ec_has_volatile)
    2080           0 :             continue;
    2081             :         /* It has to match the outer-join clause as to semantics, too */
    2082         176 :         if (collation != cur_ec->ec_collation)
    2083          24 :             continue;
    2084         152 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    2085           0 :             continue;
    2086             : 
    2087             :         /*
    2088             :          * Does it contain a COALESCE(leftvar, rightvar) construct?
    2089             :          *
    2090             :          * We can assume the COALESCE() inputs are in the same order as the
    2091             :          * join clause, since both were automatically generated in the cases
    2092             :          * we care about.
    2093             :          *
    2094             :          * XXX currently this may fail to match in cross-type cases because
    2095             :          * the COALESCE will contain typecast operations while the join clause
    2096             :          * may not (if there is a cross-type mergejoin operator available for
    2097             :          * the two column types). Is it OK to strip implicit coercions from
    2098             :          * the COALESCE arguments?
    2099             :          */
    2100         152 :         match = false;
    2101         440 :         foreach(lc2, cur_ec->ec_members)
    2102             :         {
    2103         292 :             coal_em = (EquivalenceMember *) lfirst(lc2);
    2104             :             Assert(!coal_em->em_is_child);   /* no children yet */
    2105         292 :             if (IsA(coal_em->em_expr, CoalesceExpr))
    2106             :             {
    2107           4 :                 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
    2108             :                 Node       *cfirst;
    2109             :                 Node       *csecond;
    2110             : 
    2111           4 :                 if (list_length(cexpr->args) != 2)
    2112           0 :                     continue;
    2113           4 :                 cfirst = (Node *) linitial(cexpr->args);
    2114           4 :                 csecond = (Node *) lsecond(cexpr->args);
    2115             : 
    2116           4 :                 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
    2117             :                 {
    2118           4 :                     coal_idx = foreach_current_index(lc2);
    2119           4 :                     match = true;
    2120           4 :                     break;
    2121             :                 }
    2122             :             }
    2123             :         }
    2124         152 :         if (!match)
    2125         148 :             continue;           /* no match, so ignore this EC */
    2126             : 
    2127             :         /*
    2128             :          * Yes it does!  Try to generate clauses LEFTVAR = CONSTANT and
    2129             :          * RIGHTVAR = CONSTANT for each CONSTANT in the EC.  Note that we must
    2130             :          * succeed with at least one constant for each var before we can
    2131             :          * decide to throw away the outer-join clause.
    2132             :          */
    2133           4 :         matchleft = matchright = false;
    2134          12 :         foreach(lc2, cur_ec->ec_members)
    2135             :         {
    2136           8 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    2137             :             Oid         eq_op;
    2138             :             RestrictInfo *newrinfo;
    2139             : 
    2140           8 :             if (!cur_em->em_is_const)
    2141           4 :                 continue;       /* ignore non-const members */
    2142           4 :             eq_op = select_equality_operator(cur_ec,
    2143             :                                              left_type,
    2144             :                                              cur_em->em_datatype);
    2145           4 :             if (OidIsValid(eq_op))
    2146             :             {
    2147           4 :                 newrinfo = build_implied_join_equality(root,
    2148             :                                                        eq_op,
    2149             :                                                        cur_ec->ec_collation,
    2150             :                                                        leftvar,
    2151             :                                                        cur_em->em_expr,
    2152             :                                                        bms_copy(left_relids),
    2153             :                                                        bms_copy(left_nullable_relids),
    2154             :                                                        cur_ec->ec_min_security);
    2155           4 :                 if (process_equivalence(root, &newrinfo, true))
    2156           4 :                     matchleft = true;
    2157             :             }
    2158           4 :             eq_op = select_equality_operator(cur_ec,
    2159             :                                              right_type,
    2160             :                                              cur_em->em_datatype);
    2161           4 :             if (OidIsValid(eq_op))
    2162             :             {
    2163           4 :                 newrinfo = build_implied_join_equality(root,
    2164             :                                                        eq_op,
    2165             :                                                        cur_ec->ec_collation,
    2166             :                                                        rightvar,
    2167             :                                                        cur_em->em_expr,
    2168             :                                                        bms_copy(right_relids),
    2169             :                                                        bms_copy(right_nullable_relids),
    2170             :                                                        cur_ec->ec_min_security);
    2171           4 :                 if (process_equivalence(root, &newrinfo, true))
    2172           4 :                     matchright = true;
    2173             :             }
    2174             :         }
    2175             : 
    2176             :         /*
    2177             :          * If we were able to equate both vars to constants, we're done, and
    2178             :          * we can throw away the full-join clause as redundant.  Moreover, we
    2179             :          * can remove the COALESCE entry from the EC, since the added
    2180             :          * restrictions ensure it will always have the expected value. (We
    2181             :          * don't bother trying to update ec_relids or ec_sources.)
    2182             :          */
    2183           4 :         if (matchleft && matchright)
    2184             :         {
    2185           4 :             cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
    2186           4 :             return true;
    2187             :         }
    2188             : 
    2189             :         /*
    2190             :          * Otherwise, fall out of the search loop, since we know the COALESCE
    2191             :          * appears in at most one EC (XXX might stop being true if we allow
    2192             :          * stripping of coercions above?)
    2193             :          */
    2194           0 :         break;
    2195             :     }
    2196             : 
    2197         672 :     return false;               /* failed to make any deduction */
    2198             : }
    2199             : 
    2200             : 
    2201             : /*
    2202             :  * exprs_known_equal
    2203             :  *    Detect whether two expressions are known equal due to equivalence
    2204             :  *    relationships.
    2205             :  *
    2206             :  * Actually, this only shows that the expressions are equal according
    2207             :  * to some opfamily's notion of equality --- but we only use it for
    2208             :  * selectivity estimation, so a fuzzy idea of equality is OK.
    2209             :  *
    2210             :  * Note: does not bother to check for "equal(item1, item2)"; caller must
    2211             :  * check that case if it's possible to pass identical items.
    2212             :  */
    2213             : bool
    2214         566 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
    2215             : {
    2216             :     ListCell   *lc1;
    2217             : 
    2218        3366 :     foreach(lc1, root->eq_classes)
    2219             :     {
    2220        2856 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
    2221        2856 :         bool        item1member = false;
    2222        2856 :         bool        item2member = false;
    2223             :         ListCell   *lc2;
    2224             : 
    2225             :         /* Never match to a volatile EC */
    2226        2856 :         if (ec->ec_has_volatile)
    2227           0 :             continue;
    2228             : 
    2229       12136 :         foreach(lc2, ec->ec_members)
    2230             :         {
    2231        9336 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2232             : 
    2233        9336 :             if (em->em_is_child)
    2234        5632 :                 continue;       /* ignore children here */
    2235        3704 :             if (equal(item1, em->em_expr))
    2236         426 :                 item1member = true;
    2237        3278 :             else if (equal(item2, em->em_expr))
    2238         414 :                 item2member = true;
    2239             :             /* Exit as soon as equality is proven */
    2240        3704 :             if (item1member && item2member)
    2241          56 :                 return true;
    2242             :         }
    2243             :     }
    2244         510 :     return false;
    2245             : }
    2246             : 
    2247             : 
    2248             : /*
    2249             :  * match_eclasses_to_foreign_key_col
    2250             :  *    See whether a foreign key column match is proven by any eclass.
    2251             :  *
    2252             :  * If the referenced and referencing Vars of the fkey's colno'th column are
    2253             :  * known equal due to any eclass, return that eclass; otherwise return NULL.
    2254             :  * (In principle there might be more than one matching eclass if multiple
    2255             :  * collations are involved, but since collation doesn't matter for equality,
    2256             :  * we ignore that fine point here.)  This is much like exprs_known_equal,
    2257             :  * except that we insist on the comparison operator matching the eclass, so
    2258             :  * that the result is definite not approximate.
    2259             :  *
    2260             :  * On success, we also set fkinfo->eclass[colno] to the matching eclass,
    2261             :  * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
    2262             :  * referencing Var.
    2263             :  */
    2264             : EquivalenceClass *
    2265        1440 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
    2266             :                                   ForeignKeyOptInfo *fkinfo,
    2267             :                                   int colno)
    2268             : {
    2269        1440 :     Index       var1varno = fkinfo->con_relid;
    2270        1440 :     AttrNumber  var1attno = fkinfo->conkey[colno];
    2271        1440 :     Index       var2varno = fkinfo->ref_relid;
    2272        1440 :     AttrNumber  var2attno = fkinfo->confkey[colno];
    2273        1440 :     Oid         eqop = fkinfo->conpfeqop[colno];
    2274        1440 :     RelOptInfo *rel1 = root->simple_rel_array[var1varno];
    2275        1440 :     RelOptInfo *rel2 = root->simple_rel_array[var2varno];
    2276        1440 :     List       *opfamilies = NIL;   /* compute only if needed */
    2277             :     Bitmapset  *matching_ecs;
    2278             :     int         i;
    2279             : 
    2280             :     /* Consider only eclasses mentioning both relations */
    2281             :     Assert(root->ec_merging_done);
    2282             :     Assert(IS_SIMPLE_REL(rel1));
    2283             :     Assert(IS_SIMPLE_REL(rel2));
    2284        1440 :     matching_ecs = bms_intersect(rel1->eclass_indexes,
    2285        1440 :                                  rel2->eclass_indexes);
    2286             : 
    2287        1440 :     i = -1;
    2288        1504 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2289             :     {
    2290         266 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2291             :                                                              i);
    2292         266 :         EquivalenceMember *item1_em = NULL;
    2293         266 :         EquivalenceMember *item2_em = NULL;
    2294             :         ListCell   *lc2;
    2295             : 
    2296             :         /* Never match to a volatile EC */
    2297         266 :         if (ec->ec_has_volatile)
    2298           0 :             continue;
    2299             :         /* Note: it seems okay to match to "broken" eclasses here */
    2300             : 
    2301         664 :         foreach(lc2, ec->ec_members)
    2302             :         {
    2303         600 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2304             :             Var        *var;
    2305             : 
    2306         600 :             if (em->em_is_child)
    2307           0 :                 continue;       /* ignore children here */
    2308             : 
    2309             :             /* EM must be a Var, possibly with RelabelType */
    2310         600 :             var = (Var *) em->em_expr;
    2311         600 :             while (var && IsA(var, RelabelType))
    2312           0 :                 var = (Var *) ((RelabelType *) var)->arg;
    2313         600 :             if (!(var && IsA(var, Var)))
    2314           4 :                 continue;
    2315             : 
    2316             :             /* Match? */
    2317         596 :             if (var->varno == var1varno && var->varattno == var1attno)
    2318         202 :                 item1_em = em;
    2319         394 :             else if (var->varno == var2varno && var->varattno == var2attno)
    2320         202 :                 item2_em = em;
    2321             : 
    2322             :             /* Have we found both PK and FK column in this EC? */
    2323         596 :             if (item1_em && item2_em)
    2324             :             {
    2325             :                 /*
    2326             :                  * Succeed if eqop matches EC's opfamilies.  We could test
    2327             :                  * this before scanning the members, but it's probably cheaper
    2328             :                  * to test for member matches first.
    2329             :                  */
    2330         202 :                 if (opfamilies == NIL)  /* compute if we didn't already */
    2331         202 :                     opfamilies = get_mergejoin_opfamilies(eqop);
    2332         202 :                 if (equal(opfamilies, ec->ec_opfamilies))
    2333             :                 {
    2334         202 :                     fkinfo->eclass[colno] = ec;
    2335         202 :                     fkinfo->fk_eclass_member[colno] = item2_em;
    2336         202 :                     return ec;
    2337             :                 }
    2338             :                 /* Otherwise, done with this EC, move on to the next */
    2339           0 :                 break;
    2340             :             }
    2341             :         }
    2342             :     }
    2343        1238 :     return NULL;
    2344             : }
    2345             : 
    2346             : /*
    2347             :  * find_derived_clause_for_ec_member
    2348             :  *    Search for a previously-derived clause mentioning the given EM.
    2349             :  *
    2350             :  * The eclass should be an ec_has_const EC, of which the EM is a non-const
    2351             :  * member.  This should ensure there is just one derived clause mentioning
    2352             :  * the EM (and equating it to a constant).
    2353             :  * Returns NULL if no such clause can be found.
    2354             :  */
    2355             : RestrictInfo *
    2356           4 : find_derived_clause_for_ec_member(EquivalenceClass *ec,
    2357             :                                   EquivalenceMember *em)
    2358             : {
    2359             :     ListCell   *lc;
    2360             : 
    2361             :     Assert(ec->ec_has_const);
    2362             :     Assert(!em->em_is_const);
    2363           4 :     foreach(lc, ec->ec_derives)
    2364             :     {
    2365           4 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    2366             : 
    2367             :         /*
    2368             :          * generate_base_implied_equalities_const will have put non-const
    2369             :          * members on the left side of derived clauses.
    2370             :          */
    2371           4 :         if (rinfo->left_em == em)
    2372           4 :             return rinfo;
    2373             :     }
    2374           0 :     return NULL;
    2375             : }
    2376             : 
    2377             : 
    2378             : /*
    2379             :  * add_child_rel_equivalences
    2380             :  *    Search for EC members that reference the root parent of child_rel, and
    2381             :  *    add transformed members referencing the child_rel.
    2382             :  *
    2383             :  * Note that this function won't be called at all unless we have at least some
    2384             :  * reason to believe that the EC members it generates will be useful.
    2385             :  *
    2386             :  * parent_rel and child_rel could be derived from appinfo, but since the
    2387             :  * caller has already computed them, we might as well just pass them in.
    2388             :  *
    2389             :  * The passed-in AppendRelInfo is not used when the parent_rel is not a
    2390             :  * top-level baserel, since it shows the mapping from the parent_rel but
    2391             :  * we need to translate EC expressions that refer to the top-level parent.
    2392             :  * Using it is faster than using adjust_appendrel_attrs_multilevel(), though,
    2393             :  * so we prefer it when we can.
    2394             :  */
    2395             : void
    2396       15728 : add_child_rel_equivalences(PlannerInfo *root,
    2397             :                            AppendRelInfo *appinfo,
    2398             :                            RelOptInfo *parent_rel,
    2399             :                            RelOptInfo *child_rel)
    2400             : {
    2401       15728 :     Relids      top_parent_relids = child_rel->top_parent_relids;
    2402       15728 :     Relids      child_relids = child_rel->relids;
    2403             :     int         i;
    2404             : 
    2405             :     /*
    2406             :      * EC merging should be complete already, so we can use the parent rel's
    2407             :      * eclass_indexes to avoid searching all of root->eq_classes.
    2408             :      */
    2409             :     Assert(root->ec_merging_done);
    2410             :     Assert(IS_SIMPLE_REL(parent_rel));
    2411             : 
    2412       15728 :     i = -1;
    2413       43006 :     while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
    2414             :     {
    2415       27278 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2416             :         int         num_members;
    2417             : 
    2418             :         /*
    2419             :          * If this EC contains a volatile expression, then generating child
    2420             :          * EMs would be downright dangerous, so skip it.  We rely on a
    2421             :          * volatile EC having only one EM.
    2422             :          */
    2423       27278 :         if (cur_ec->ec_has_volatile)
    2424           0 :             continue;
    2425             : 
    2426             :         /* Sanity check eclass_indexes only contain ECs for parent_rel */
    2427             :         Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
    2428             : 
    2429             :         /*
    2430             :          * We don't use foreach() here because there's no point in scanning
    2431             :          * newly-added child members, so we can stop after the last
    2432             :          * pre-existing EC member.
    2433             :          */
    2434       27278 :         num_members = list_length(cur_ec->ec_members);
    2435      126694 :         for (int pos = 0; pos < num_members; pos++)
    2436             :         {
    2437       99416 :             EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
    2438             : 
    2439       99416 :             if (cur_em->em_is_const)
    2440        2268 :                 continue;       /* ignore consts here */
    2441             : 
    2442             :             /*
    2443             :              * We consider only original EC members here, not
    2444             :              * already-transformed child members.  Otherwise, if some original
    2445             :              * member expression references more than one appendrel, we'd get
    2446             :              * an O(N^2) explosion of useless derived expressions for
    2447             :              * combinations of children.  (But add_child_join_rel_equivalences
    2448             :              * may add targeted combinations for partitionwise-join purposes.)
    2449             :              */
    2450       97148 :             if (cur_em->em_is_child)
    2451       61742 :                 continue;       /* ignore children here */
    2452             : 
    2453             :             /* Does this member reference child's topmost parent rel? */
    2454       35406 :             if (bms_overlap(cur_em->em_relids, top_parent_relids))
    2455             :             {
    2456             :                 /* Yes, generate transformed child version */
    2457             :                 Expr       *child_expr;
    2458             :                 Relids      new_relids;
    2459             :                 Relids      new_nullable_relids;
    2460             : 
    2461       27302 :                 if (parent_rel->reloptkind == RELOPT_BASEREL)
    2462             :                 {
    2463             :                     /* Simple single-level transformation */
    2464             :                     child_expr = (Expr *)
    2465       22514 :                         adjust_appendrel_attrs(root,
    2466       22514 :                                                (Node *) cur_em->em_expr,
    2467             :                                                1, &appinfo);
    2468             :                 }
    2469             :                 else
    2470             :                 {
    2471             :                     /* Must do multi-level transformation */
    2472             :                     child_expr = (Expr *)
    2473        4788 :                         adjust_appendrel_attrs_multilevel(root,
    2474        4788 :                                                           (Node *) cur_em->em_expr,
    2475             :                                                           child_relids,
    2476             :                                                           top_parent_relids);
    2477             :                 }
    2478             : 
    2479             :                 /*
    2480             :                  * Transform em_relids to match.  Note we do *not* do
    2481             :                  * pull_varnos(child_expr) here, as for example the
    2482             :                  * transformation might have substituted a constant, but we
    2483             :                  * don't want the child member to be marked as constant.
    2484             :                  */
    2485       27302 :                 new_relids = bms_difference(cur_em->em_relids,
    2486             :                                             top_parent_relids);
    2487       27302 :                 new_relids = bms_add_members(new_relids, child_relids);
    2488             : 
    2489             :                 /*
    2490             :                  * And likewise for nullable_relids.  Note this code assumes
    2491             :                  * parent and child relids are singletons.
    2492             :                  */
    2493       27302 :                 new_nullable_relids = cur_em->em_nullable_relids;
    2494       27302 :                 if (bms_overlap(new_nullable_relids, top_parent_relids))
    2495             :                 {
    2496         576 :                     new_nullable_relids = bms_difference(new_nullable_relids,
    2497             :                                                          top_parent_relids);
    2498         576 :                     new_nullable_relids = bms_add_members(new_nullable_relids,
    2499             :                                                           child_relids);
    2500             :                 }
    2501             : 
    2502       27302 :                 (void) add_eq_member(cur_ec, child_expr,
    2503             :                                      new_relids, new_nullable_relids,
    2504             :                                      true, cur_em->em_datatype);
    2505             : 
    2506             :                 /* Record this EC index for the child rel */
    2507       27302 :                 child_rel->eclass_indexes = bms_add_member(child_rel->eclass_indexes, i);
    2508             :             }
    2509             :         }
    2510             :     }
    2511       15728 : }
    2512             : 
    2513             : /*
    2514             :  * add_child_join_rel_equivalences
    2515             :  *    Like add_child_rel_equivalences(), but for joinrels
    2516             :  *
    2517             :  * Here we find the ECs relevant to the top parent joinrel and add transformed
    2518             :  * member expressions that refer to this child joinrel.
    2519             :  *
    2520             :  * Note that this function won't be called at all unless we have at least some
    2521             :  * reason to believe that the EC members it generates will be useful.
    2522             :  */
    2523             : void
    2524        2740 : add_child_join_rel_equivalences(PlannerInfo *root,
    2525             :                                 int nappinfos, AppendRelInfo **appinfos,
    2526             :                                 RelOptInfo *parent_joinrel,
    2527             :                                 RelOptInfo *child_joinrel)
    2528             : {
    2529        2740 :     Relids      top_parent_relids = child_joinrel->top_parent_relids;
    2530        2740 :     Relids      child_relids = child_joinrel->relids;
    2531             :     Bitmapset  *matching_ecs;
    2532             :     MemoryContext oldcontext;
    2533             :     int         i;
    2534             : 
    2535             :     Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
    2536             : 
    2537             :     /* We need consider only ECs that mention the parent joinrel */
    2538        2740 :     matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
    2539             : 
    2540             :     /*
    2541             :      * If we're being called during GEQO join planning, we still have to
    2542             :      * create any new EC members in the main planner context, to avoid having
    2543             :      * a corrupt EC data structure after the GEQO context is reset.  This is
    2544             :      * problematic since we'll leak memory across repeated GEQO cycles.  For
    2545             :      * now, though, bloat is better than crash.  If it becomes a real issue
    2546             :      * we'll have to do something to avoid generating duplicate EC members.
    2547             :      */
    2548        2740 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    2549             : 
    2550        2740 :     i = -1;
    2551       11720 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2552             :     {
    2553        8980 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2554             :         int         num_members;
    2555             : 
    2556             :         /*
    2557             :          * If this EC contains a volatile expression, then generating child
    2558             :          * EMs would be downright dangerous, so skip it.  We rely on a
    2559             :          * volatile EC having only one EM.
    2560             :          */
    2561        8980 :         if (cur_ec->ec_has_volatile)
    2562           0 :             continue;
    2563             : 
    2564             :         /* Sanity check on get_eclass_indexes_for_relids result */
    2565             :         Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
    2566             : 
    2567             :         /*
    2568             :          * We don't use foreach() here because there's no point in scanning
    2569             :          * newly-added child members, so we can stop after the last
    2570             :          * pre-existing EC member.
    2571             :          */
    2572        8980 :         num_members = list_length(cur_ec->ec_members);
    2573       65840 :         for (int pos = 0; pos < num_members; pos++)
    2574             :         {
    2575       56860 :             EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
    2576             : 
    2577       56860 :             if (cur_em->em_is_const)
    2578        1480 :                 continue;       /* ignore consts here */
    2579             : 
    2580             :             /*
    2581             :              * We consider only original EC members here, not
    2582             :              * already-transformed child members.
    2583             :              */
    2584       55380 :             if (cur_em->em_is_child)
    2585       43624 :                 continue;       /* ignore children here */
    2586             : 
    2587             :             /*
    2588             :              * We may ignore expressions that reference a single baserel,
    2589             :              * because add_child_rel_equivalences should have handled them.
    2590             :              */
    2591       11756 :             if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
    2592       11444 :                 continue;
    2593             : 
    2594             :             /* Does this member reference child's topmost parent rel? */
    2595         312 :             if (bms_overlap(cur_em->em_relids, top_parent_relids))
    2596             :             {
    2597             :                 /* Yes, generate transformed child version */
    2598             :                 Expr       *child_expr;
    2599             :                 Relids      new_relids;
    2600             :                 Relids      new_nullable_relids;
    2601             : 
    2602         312 :                 if (parent_joinrel->reloptkind == RELOPT_JOINREL)
    2603             :                 {
    2604             :                     /* Simple single-level transformation */
    2605             :                     child_expr = (Expr *)
    2606         312 :                         adjust_appendrel_attrs(root,
    2607         312 :                                                (Node *) cur_em->em_expr,
    2608             :                                                nappinfos, appinfos);
    2609             :                 }
    2610             :                 else
    2611             :                 {
    2612             :                     /* Must do multi-level transformation */
    2613             :                     Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
    2614             :                     child_expr = (Expr *)
    2615           0 :                         adjust_appendrel_attrs_multilevel(root,
    2616           0 :                                                           (Node *) cur_em->em_expr,
    2617             :                                                           child_relids,
    2618             :                                                           top_parent_relids);
    2619             :                 }
    2620             : 
    2621             :                 /*
    2622             :                  * Transform em_relids to match.  Note we do *not* do
    2623             :                  * pull_varnos(child_expr) here, as for example the
    2624             :                  * transformation might have substituted a constant, but we
    2625             :                  * don't want the child member to be marked as constant.
    2626             :                  */
    2627         312 :                 new_relids = bms_difference(cur_em->em_relids,
    2628             :                                             top_parent_relids);
    2629         312 :                 new_relids = bms_add_members(new_relids, child_relids);
    2630             : 
    2631             :                 /*
    2632             :                  * For nullable_relids, we must selectively replace parent
    2633             :                  * nullable relids with child ones.
    2634             :                  */
    2635         312 :                 new_nullable_relids = cur_em->em_nullable_relids;
    2636         312 :                 if (bms_overlap(new_nullable_relids, top_parent_relids))
    2637             :                     new_nullable_relids =
    2638         312 :                         adjust_child_relids_multilevel(root,
    2639             :                                                        new_nullable_relids,
    2640             :                                                        child_relids,
    2641             :                                                        top_parent_relids);
    2642             : 
    2643         312 :                 (void) add_eq_member(cur_ec, child_expr,
    2644             :                                      new_relids, new_nullable_relids,
    2645             :                                      true, cur_em->em_datatype);
    2646             :             }
    2647             :         }
    2648             :     }
    2649             : 
    2650        2740 :     MemoryContextSwitchTo(oldcontext);
    2651        2740 : }
    2652             : 
    2653             : 
    2654             : /*
    2655             :  * generate_implied_equalities_for_column
    2656             :  *    Create EC-derived joinclauses usable with a specific column.
    2657             :  *
    2658             :  * This is used by indxpath.c to extract potentially indexable joinclauses
    2659             :  * from ECs, and can be used by foreign data wrappers for similar purposes.
    2660             :  * We assume that only expressions in Vars of a single table are of interest,
    2661             :  * but the caller provides a callback function to identify exactly which
    2662             :  * such expressions it would like to know about.
    2663             :  *
    2664             :  * We assume that any given table/index column could appear in only one EC.
    2665             :  * (This should be true in all but the most pathological cases, and if it
    2666             :  * isn't, we stop on the first match anyway.)  Therefore, what we return
    2667             :  * is a redundant list of clauses equating the table/index column to each of
    2668             :  * the other-relation values it is known to be equal to.  Any one of
    2669             :  * these clauses can be used to create a parameterized path, and there
    2670             :  * is no value in using more than one.  (But it *is* worthwhile to create
    2671             :  * a separate parameterized path for each one, since that leads to different
    2672             :  * join orders.)
    2673             :  *
    2674             :  * The caller can pass a Relids set of rels we aren't interested in joining
    2675             :  * to, so as to save the work of creating useless clauses.
    2676             :  */
    2677             : List *
    2678      203866 : generate_implied_equalities_for_column(PlannerInfo *root,
    2679             :                                        RelOptInfo *rel,
    2680             :                                        ec_matches_callback_type callback,
    2681             :                                        void *callback_arg,
    2682             :                                        Relids prohibited_rels)
    2683             : {
    2684      203866 :     List       *result = NIL;
    2685      203866 :     bool        is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
    2686             :     Relids      parent_relids;
    2687             :     int         i;
    2688             : 
    2689             :     /* Should be OK to rely on eclass_indexes */
    2690             :     Assert(root->ec_merging_done);
    2691             : 
    2692             :     /* Indexes are available only on base or "other" member relations. */
    2693             :     Assert(IS_SIMPLE_REL(rel));
    2694             : 
    2695             :     /* If it's a child rel, we'll need to know what its parent(s) are */
    2696      203866 :     if (is_child_rel)
    2697        6936 :         parent_relids = find_childrel_parents(root, rel);
    2698             :     else
    2699      196930 :         parent_relids = NULL;   /* not used, but keep compiler quiet */
    2700             : 
    2701      203866 :     i = -1;
    2702      558996 :     while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
    2703             :     {
    2704      394206 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2705             :         EquivalenceMember *cur_em;
    2706             :         ListCell   *lc2;
    2707             : 
    2708             :         /* Sanity check eclass_indexes only contain ECs for rel */
    2709             :         Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
    2710             : 
    2711             :         /*
    2712             :          * Won't generate joinclauses if const or single-member (the latter
    2713             :          * test covers the volatile case too)
    2714             :          */
    2715      394206 :         if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
    2716      198598 :             continue;
    2717             : 
    2718             :         /*
    2719             :          * Scan members, looking for a match to the target column.  Note that
    2720             :          * child EC members are considered, but only when they belong to the
    2721             :          * target relation.  (Unlike regular members, the same expression
    2722             :          * could be a child member of more than one EC.  Therefore, it's
    2723             :          * potentially order-dependent which EC a child relation's target
    2724             :          * column gets matched to.  This is annoying but it only happens in
    2725             :          * corner cases, so for now we live with just reporting the first
    2726             :          * match.  See also get_eclass_for_sort_expr.)
    2727             :          */
    2728      195608 :         cur_em = NULL;
    2729      593108 :         foreach(lc2, cur_ec->ec_members)
    2730             :         {
    2731      436620 :             cur_em = (EquivalenceMember *) lfirst(lc2);
    2732      632220 :             if (bms_equal(cur_em->em_relids, rel->relids) &&
    2733      195600 :                 callback(root, rel, cur_ec, cur_em, callback_arg))
    2734       39120 :                 break;
    2735      397500 :             cur_em = NULL;
    2736             :         }
    2737             : 
    2738      195608 :         if (!cur_em)
    2739      156488 :             continue;
    2740             : 
    2741             :         /*
    2742             :          * Found our match.  Scan the other EC members and attempt to generate
    2743             :          * joinclauses.
    2744             :          */
    2745      131330 :         foreach(lc2, cur_ec->ec_members)
    2746             :         {
    2747       92210 :             EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
    2748             :             Oid         eq_op;
    2749             :             RestrictInfo *rinfo;
    2750             : 
    2751       92210 :             if (other_em->em_is_child)
    2752       12376 :                 continue;       /* ignore children here */
    2753             : 
    2754             :             /* Make sure it'll be a join to a different rel */
    2755      122312 :             if (other_em == cur_em ||
    2756       42478 :                 bms_overlap(other_em->em_relids, rel->relids))
    2757       37396 :                 continue;
    2758             : 
    2759             :             /* Forget it if caller doesn't want joins to this rel */
    2760       42438 :             if (bms_overlap(other_em->em_relids, prohibited_rels))
    2761           4 :                 continue;
    2762             : 
    2763             :             /*
    2764             :              * Also, if this is a child rel, avoid generating a useless join
    2765             :              * to its parent rel(s).
    2766             :              */
    2767       46330 :             if (is_child_rel &&
    2768        3896 :                 bms_overlap(parent_relids, other_em->em_relids))
    2769        1772 :                 continue;
    2770             : 
    2771       40662 :             eq_op = select_equality_operator(cur_ec,
    2772             :                                              cur_em->em_datatype,
    2773             :                                              other_em->em_datatype);
    2774       40662 :             if (!OidIsValid(eq_op))
    2775           0 :                 continue;
    2776             : 
    2777             :             /* set parent_ec to mark as redundant with other joinclauses */
    2778       40662 :             rinfo = create_join_clause(root, cur_ec, eq_op,
    2779             :                                        cur_em, other_em,
    2780             :                                        cur_ec);
    2781             : 
    2782       40662 :             result = lappend(result, rinfo);
    2783             :         }
    2784             : 
    2785             :         /*
    2786             :          * If somehow we failed to create any join clauses, we might as well
    2787             :          * keep scanning the ECs for another match.  But if we did make any,
    2788             :          * we're done, because we don't want to return non-redundant clauses.
    2789             :          */
    2790       39120 :         if (result)
    2791       39076 :             break;
    2792             :     }
    2793             : 
    2794      203866 :     return result;
    2795             : }
    2796             : 
    2797             : /*
    2798             :  * have_relevant_eclass_joinclause
    2799             :  *      Detect whether there is an EquivalenceClass that could produce
    2800             :  *      a joinclause involving the two given relations.
    2801             :  *
    2802             :  * This is essentially a very cut-down version of
    2803             :  * generate_join_implied_equalities().  Note it's OK to occasionally say "yes"
    2804             :  * incorrectly.  Hence we don't bother with details like whether the lack of a
    2805             :  * cross-type operator might prevent the clause from actually being generated.
    2806             :  */
    2807             : bool
    2808       75224 : have_relevant_eclass_joinclause(PlannerInfo *root,
    2809             :                                 RelOptInfo *rel1, RelOptInfo *rel2)
    2810             : {
    2811             :     Bitmapset  *matching_ecs;
    2812             :     int         i;
    2813             : 
    2814             :     /* Examine only eclasses mentioning both rel1 and rel2 */
    2815       75224 :     matching_ecs = get_common_eclass_indexes(root, rel1->relids,
    2816             :                                              rel2->relids);
    2817             : 
    2818       75224 :     i = -1;
    2819       75224 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2820             :     {
    2821       61980 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2822             :                                                              i);
    2823             : 
    2824             :         /*
    2825             :          * Sanity check that get_common_eclass_indexes gave only ECs
    2826             :          * containing both rels.
    2827             :          */
    2828             :         Assert(bms_overlap(rel1->relids, ec->ec_relids));
    2829             :         Assert(bms_overlap(rel2->relids, ec->ec_relids));
    2830             : 
    2831             :         /*
    2832             :          * Won't generate joinclauses if single-member (this test covers the
    2833             :          * volatile case too)
    2834             :          */
    2835       61980 :         if (list_length(ec->ec_members) <= 1)
    2836           0 :             continue;
    2837             : 
    2838             :         /*
    2839             :          * We do not need to examine the individual members of the EC, because
    2840             :          * all that we care about is whether each rel overlaps the relids of
    2841             :          * at least one member, and get_common_eclass_indexes() and the single
    2842             :          * member check above are sufficient to prove that.  (As with
    2843             :          * have_relevant_joinclause(), it is not necessary that the EC be able
    2844             :          * to form a joinclause relating exactly the two given rels, only that
    2845             :          * it be able to form a joinclause mentioning both, and this will
    2846             :          * surely be true if both of them overlap ec_relids.)
    2847             :          *
    2848             :          * Note we don't test ec_broken; if we did, we'd need a separate code
    2849             :          * path to look through ec_sources.  Checking the membership anyway is
    2850             :          * OK as a possibly-overoptimistic heuristic.
    2851             :          *
    2852             :          * We don't test ec_has_const either, even though a const eclass won't
    2853             :          * generate real join clauses.  This is because if we had "WHERE a.x =
    2854             :          * b.y and a.x = 42", it is worth considering a join between a and b,
    2855             :          * since the join result is likely to be small even though it'll end
    2856             :          * up being an unqualified nestloop.
    2857             :          */
    2858             : 
    2859       61980 :         return true;
    2860             :     }
    2861             : 
    2862       13244 :     return false;
    2863             : }
    2864             : 
    2865             : 
    2866             : /*
    2867             :  * has_relevant_eclass_joinclause
    2868             :  *      Detect whether there is an EquivalenceClass that could produce
    2869             :  *      a joinclause involving the given relation and anything else.
    2870             :  *
    2871             :  * This is the same as have_relevant_eclass_joinclause with the other rel
    2872             :  * implicitly defined as "everything else in the query".
    2873             :  */
    2874             : bool
    2875      100702 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
    2876             : {
    2877             :     Bitmapset  *matched_ecs;
    2878             :     int         i;
    2879             : 
    2880             :     /* Examine only eclasses mentioning rel1 */
    2881      100702 :     matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
    2882             : 
    2883      100702 :     i = -1;
    2884      340096 :     while ((i = bms_next_member(matched_ecs, i)) >= 0)
    2885             :     {
    2886      276894 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2887             :                                                              i);
    2888             : 
    2889             :         /*
    2890             :          * Won't generate joinclauses if single-member (this test covers the
    2891             :          * volatile case too)
    2892             :          */
    2893      276894 :         if (list_length(ec->ec_members) <= 1)
    2894      122474 :             continue;
    2895             : 
    2896             :         /*
    2897             :          * Per the comment in have_relevant_eclass_joinclause, it's sufficient
    2898             :          * to find an EC that mentions both this rel and some other rel.
    2899             :          */
    2900      154420 :         if (!bms_is_subset(ec->ec_relids, rel1->relids))
    2901       37500 :             return true;
    2902             :     }
    2903             : 
    2904       63202 :     return false;
    2905             : }
    2906             : 
    2907             : 
    2908             : /*
    2909             :  * eclass_useful_for_merging
    2910             :  *    Detect whether the EC could produce any mergejoinable join clauses
    2911             :  *    against the specified relation.
    2912             :  *
    2913             :  * This is just a heuristic test and doesn't have to be exact; it's better
    2914             :  * to say "yes" incorrectly than "no".  Hence we don't bother with details
    2915             :  * like whether the lack of a cross-type operator might prevent the clause
    2916             :  * from actually being generated.
    2917             :  */
    2918             : bool
    2919      304000 : eclass_useful_for_merging(PlannerInfo *root,
    2920             :                           EquivalenceClass *eclass,
    2921             :                           RelOptInfo *rel)
    2922             : {
    2923             :     Relids      relids;
    2924             :     ListCell   *lc;
    2925             : 
    2926             :     Assert(!eclass->ec_merged);
    2927             : 
    2928             :     /*
    2929             :      * Won't generate joinclauses if const or single-member (the latter test
    2930             :      * covers the volatile case too)
    2931             :      */
    2932      304000 :     if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
    2933       35442 :         return false;
    2934             : 
    2935             :     /*
    2936             :      * Note we don't test ec_broken; if we did, we'd need a separate code path
    2937             :      * to look through ec_sources.  Checking the members anyway is OK as a
    2938             :      * possibly-overoptimistic heuristic.
    2939             :      */
    2940             : 
    2941             :     /* If specified rel is a child, we must consider the topmost parent rel */
    2942      268558 :     if (IS_OTHER_REL(rel))
    2943             :     {
    2944             :         Assert(!bms_is_empty(rel->top_parent_relids));
    2945        6428 :         relids = rel->top_parent_relids;
    2946             :     }
    2947             :     else
    2948      262130 :         relids = rel->relids;
    2949             : 
    2950             :     /* If rel already includes all members of eclass, no point in searching */
    2951      268558 :     if (bms_is_subset(eclass->ec_relids, relids))
    2952      112830 :         return false;
    2953             : 
    2954             :     /* To join, we need a member not in the given rel */
    2955      229362 :     foreach(lc, eclass->ec_members)
    2956             :     {
    2957      229074 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    2958             : 
    2959      229074 :         if (cur_em->em_is_child)
    2960           0 :             continue;           /* ignore children here */
    2961             : 
    2962      229074 :         if (!bms_overlap(cur_em->em_relids, relids))
    2963      155440 :             return true;
    2964             :     }
    2965             : 
    2966         288 :     return false;
    2967             : }
    2968             : 
    2969             : 
    2970             : /*
    2971             :  * is_redundant_derived_clause
    2972             :  *      Test whether rinfo is derived from same EC as any clause in clauselist;
    2973             :  *      if so, it can be presumed to represent a condition that's redundant
    2974             :  *      with that member of the list.
    2975             :  */
    2976             : bool
    2977          56 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
    2978             : {
    2979          56 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    2980             :     ListCell   *lc;
    2981             : 
    2982             :     /* Fail if it's not a potentially-redundant clause from some EC */
    2983          56 :     if (parent_ec == NULL)
    2984          48 :         return false;
    2985             : 
    2986           8 :     foreach(lc, clauselist)
    2987             :     {
    2988           8 :         RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
    2989             : 
    2990           8 :         if (otherrinfo->parent_ec == parent_ec)
    2991           8 :             return true;
    2992             :     }
    2993             : 
    2994           0 :     return false;
    2995             : }
    2996             : 
    2997             : /*
    2998             :  * is_redundant_with_indexclauses
    2999             :  *      Test whether rinfo is redundant with any clause in the IndexClause
    3000             :  *      list.  Here, for convenience, we test both simple identity and
    3001             :  *      whether it is derived from the same EC as any member of the list.
    3002             :  */
    3003             : bool
    3004      741734 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
    3005             : {
    3006      741734 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    3007             :     ListCell   *lc;
    3008             : 
    3009     1066422 :     foreach(lc, indexclauses)
    3010             :     {
    3011      843592 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    3012      843592 :         RestrictInfo *otherrinfo = iclause->rinfo;
    3013             : 
    3014             :         /* If indexclause is lossy, it won't enforce the condition exactly */
    3015      843592 :         if (iclause->lossy)
    3016       16266 :             continue;
    3017             : 
    3018             :         /* Match if it's same clause (pointer equality should be enough) */
    3019      827326 :         if (rinfo == otherrinfo)
    3020      518904 :             return true;
    3021             :         /* Match if derived from same EC */
    3022      418126 :         if (parent_ec && otherrinfo->parent_ec == parent_ec)
    3023      109704 :             return true;
    3024             : 
    3025             :         /*
    3026             :          * No need to look at the derived clauses in iclause->indexquals; they
    3027             :          * couldn't match if the parent clause didn't.
    3028             :          */
    3029             :     }
    3030             : 
    3031      222830 :     return false;
    3032             : }
    3033             : 
    3034             : /*
    3035             :  * get_eclass_indexes_for_relids
    3036             :  *      Build and return a Bitmapset containing the indexes into root's
    3037             :  *      eq_classes list for all eclasses that mention any of these relids
    3038             :  */
    3039             : static Bitmapset *
    3040      501876 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
    3041             : {
    3042      501876 :     Bitmapset  *ec_indexes = NULL;
    3043      501876 :     int         i = -1;
    3044             : 
    3045             :     /* Should be OK to rely on eclass_indexes */
    3046             :     Assert(root->ec_merging_done);
    3047             : 
    3048     1393386 :     while ((i = bms_next_member(relids, i)) > 0)
    3049             :     {
    3050      891510 :         RelOptInfo *rel = root->simple_rel_array[i];
    3051             : 
    3052      891510 :         ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
    3053             :     }
    3054      501876 :     return ec_indexes;
    3055             : }
    3056             : 
    3057             : /*
    3058             :  * get_common_eclass_indexes
    3059             :  *      Build and return a Bitmapset containing the indexes into root's
    3060             :  *      eq_classes list for all eclasses that mention rels in both
    3061             :  *      relids1 and relids2.
    3062             :  */
    3063             : static Bitmapset *
    3064      304114 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
    3065             : {
    3066             :     Bitmapset  *rel1ecs;
    3067             :     Bitmapset  *rel2ecs;
    3068             :     int         relid;
    3069             : 
    3070      304114 :     rel1ecs = get_eclass_indexes_for_relids(root, relids1);
    3071             : 
    3072             :     /*
    3073             :      * We can get away with just using the relation's eclass_indexes directly
    3074             :      * when relids2 is a singleton set.
    3075             :      */
    3076      304114 :     if (bms_get_singleton_member(relids2, &relid))
    3077      209794 :         rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
    3078             :     else
    3079       94320 :         rel2ecs = get_eclass_indexes_for_relids(root, relids2);
    3080             : 
    3081             :     /* Calculate and return the common EC indexes, recycling the left input. */
    3082      304114 :     return bms_int_members(rel1ecs, rel2ecs);
    3083             : }

Generated by: LCOV version 1.13