LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - equivclass.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 789 833 94.7 %
Date: 2019-09-19 23:07:04 Functions: 28 28 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-2019, 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      157346 : process_equivalence(PlannerInfo *root,
     119             :                     RestrictInfo **p_restrictinfo,
     120             :                     bool below_outer_join)
     121             : {
     122      157346 :     RestrictInfo *restrictinfo = *p_restrictinfo;
     123      157346 :     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             : 
     141             :     /* Should not already be marked as having generated an eclass */
     142             :     Assert(restrictinfo->left_ec == NULL);
     143             :     Assert(restrictinfo->right_ec == NULL);
     144             : 
     145             :     /* Reject if it is potentially postponable by security considerations */
     146      157346 :     if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
     147         120 :         return false;
     148             : 
     149             :     /* Extract info from given clause */
     150             :     Assert(is_opclause(clause));
     151      157226 :     opno = ((OpExpr *) clause)->opno;
     152      157226 :     collation = ((OpExpr *) clause)->inputcollid;
     153      157226 :     item1 = (Expr *) get_leftop(clause);
     154      157226 :     item2 = (Expr *) get_rightop(clause);
     155      157226 :     item1_relids = restrictinfo->left_relids;
     156      157226 :     item2_relids = restrictinfo->right_relids;
     157             : 
     158             :     /*
     159             :      * Ensure both input expressions expose the desired collation (their types
     160             :      * should be OK already); see comments for canonicalize_ec_expression.
     161             :      */
     162      157226 :     item1 = canonicalize_ec_expression(item1,
     163             :                                        exprType((Node *) item1),
     164             :                                        collation);
     165      157226 :     item2 = canonicalize_ec_expression(item2,
     166             :                                        exprType((Node *) item2),
     167             :                                        collation);
     168             : 
     169             :     /*
     170             :      * Clauses of the form X=X cannot be translated into EquivalenceClasses.
     171             :      * We'd either end up with a single-entry EC, losing the knowledge that
     172             :      * the clause was present at all, or else make an EC with duplicate
     173             :      * entries, causing other issues.
     174             :      */
     175      157226 :     if (equal(item1, item2))
     176             :     {
     177             :         /*
     178             :          * If the operator is strict, then the clause can be treated as just
     179             :          * "X IS NOT NULL".  (Since we know we are considering a top-level
     180             :          * qual, we can ignore the difference between FALSE and NULL results.)
     181             :          * It's worth making the conversion because we'll typically get a much
     182             :          * better selectivity estimate than we would for X=X.
     183             :          *
     184             :          * If the operator is not strict, we can't be sure what it will do
     185             :          * with NULLs, so don't attempt to optimize it.
     186             :          */
     187          28 :         set_opfuncid((OpExpr *) clause);
     188          28 :         if (func_strict(((OpExpr *) clause)->opfuncid))
     189             :         {
     190          28 :             NullTest   *ntest = makeNode(NullTest);
     191             : 
     192          28 :             ntest->arg = item1;
     193          28 :             ntest->nulltesttype = IS_NOT_NULL;
     194          28 :             ntest->argisrow = false; /* correct even if composite arg */
     195          28 :             ntest->location = -1;
     196             : 
     197          28 :             *p_restrictinfo =
     198         112 :                 make_restrictinfo((Expr *) ntest,
     199          28 :                                   restrictinfo->is_pushed_down,
     200          28 :                                   restrictinfo->outerjoin_delayed,
     201          28 :                                   restrictinfo->pseudoconstant,
     202             :                                   restrictinfo->security_level,
     203             :                                   NULL,
     204             :                                   restrictinfo->outer_relids,
     205             :                                   restrictinfo->nullable_relids);
     206             :         }
     207          28 :         return false;
     208             :     }
     209             : 
     210             :     /*
     211             :      * If below outer join, check for strictness, else reject.
     212             :      */
     213      157198 :     if (below_outer_join)
     214             :     {
     215       43826 :         if (!bms_is_empty(item1_relids) &&
     216       21830 :             contain_nonstrict_functions((Node *) item1))
     217           0 :             return false;       /* LHS is non-strict but not constant */
     218       22950 :         if (!bms_is_empty(item2_relids) &&
     219         954 :             contain_nonstrict_functions((Node *) item2))
     220           0 :             return false;       /* RHS is non-strict but not constant */
     221             :     }
     222             : 
     223             :     /* Calculate nullable-relid sets for each side of the clause */
     224      157198 :     item1_nullable_relids = bms_intersect(item1_relids,
     225      157198 :                                           restrictinfo->nullable_relids);
     226      157198 :     item2_nullable_relids = bms_intersect(item2_relids,
     227      157198 :                                           restrictinfo->nullable_relids);
     228             : 
     229             :     /*
     230             :      * We use the declared input types of the operator, not exprType() of the
     231             :      * inputs, as the nominal datatypes for opfamily lookup.  This presumes
     232             :      * that btree operators are always registered with amoplefttype and
     233             :      * amoprighttype equal to their declared input types.  We will need this
     234             :      * info anyway to build EquivalenceMember nodes, and by extracting it now
     235             :      * we can use type comparisons to short-circuit some equal() tests.
     236             :      */
     237      157198 :     op_input_types(opno, &item1_type, &item2_type);
     238             : 
     239      157198 :     opfamilies = restrictinfo->mergeopfamilies;
     240             : 
     241             :     /*
     242             :      * Sweep through the existing EquivalenceClasses looking for matches to
     243             :      * item1 and item2.  These are the possible outcomes:
     244             :      *
     245             :      * 1. We find both in the same EC.  The equivalence is already known, so
     246             :      * there's nothing to do.
     247             :      *
     248             :      * 2. We find both in different ECs.  Merge the two ECs together.
     249             :      *
     250             :      * 3. We find just one.  Add the other to its EC.
     251             :      *
     252             :      * 4. We find neither.  Make a new, two-entry EC.
     253             :      *
     254             :      * Note: since all ECs are built through this process or the similar
     255             :      * search in get_eclass_for_sort_expr(), it's impossible that we'd match
     256             :      * an item in more than one existing nonvolatile EC.  So it's okay to stop
     257             :      * at the first match.
     258             :      */
     259      157198 :     ec1 = ec2 = NULL;
     260      157198 :     em1 = em2 = NULL;
     261      326978 :     foreach(lc1, root->eq_classes)
     262             :     {
     263      170104 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     264             :         ListCell   *lc2;
     265             : 
     266             :         /* Never match to a volatile EC */
     267      170104 :         if (cur_ec->ec_has_volatile)
     268           0 :             continue;
     269             : 
     270             :         /*
     271             :          * The collation has to match; check this first since it's cheaper
     272             :          * than the opfamily comparison.
     273             :          */
     274      170104 :         if (collation != cur_ec->ec_collation)
     275        7282 :             continue;
     276             : 
     277             :         /*
     278             :          * A "match" requires matching sets of btree opfamilies.  Use of
     279             :          * equal() for this test has implications discussed in the comments
     280             :          * for get_mergejoin_opfamilies().
     281             :          */
     282      162822 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     283       27396 :             continue;
     284             : 
     285      328602 :         foreach(lc2, cur_ec->ec_members)
     286             :         {
     287      193500 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
     288             : 
     289             :             Assert(!cur_em->em_is_child);    /* no children yet */
     290             : 
     291             :             /*
     292             :              * If below an outer join, don't match constants: they're not as
     293             :              * constant as they look.
     294             :              */
     295      272448 :             if ((below_outer_join || cur_ec->ec_below_outer_join) &&
     296       78948 :                 cur_em->em_is_const)
     297       15024 :                 continue;
     298             : 
     299      334348 :             if (!ec1 &&
     300      311604 :                 item1_type == cur_em->em_datatype &&
     301      155732 :                 equal(item1, cur_em->em_expr))
     302             :             {
     303       13122 :                 ec1 = cur_ec;
     304       13122 :                 em1 = cur_em;
     305       13122 :                 if (ec2)
     306         320 :                     break;
     307             :             }
     308             : 
     309      354752 :             if (!ec2 &&
     310      352960 :                 item2_type == cur_em->em_datatype &&
     311      176364 :                 equal(item2, cur_em->em_expr))
     312             :             {
     313        1698 :                 ec2 = cur_ec;
     314        1698 :                 em2 = cur_em;
     315        1698 :                 if (ec1)
     316           4 :                     break;
     317             :             }
     318             :         }
     319             : 
     320      135426 :         if (ec1 && ec2)
     321         324 :             break;
     322             :     }
     323             : 
     324             :     /* Sweep finished, what did we find? */
     325             : 
     326      157198 :     if (ec1 && ec2)
     327             :     {
     328             :         /* If case 1, nothing to do, except add to sources */
     329         324 :         if (ec1 == ec2)
     330             :         {
     331           0 :             ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     332           0 :             ec1->ec_below_outer_join |= below_outer_join;
     333           0 :             ec1->ec_min_security = Min(ec1->ec_min_security,
     334             :                                        restrictinfo->security_level);
     335           0 :             ec1->ec_max_security = Max(ec1->ec_max_security,
     336             :                                        restrictinfo->security_level);
     337             :             /* mark the RI as associated with this eclass */
     338           0 :             restrictinfo->left_ec = ec1;
     339           0 :             restrictinfo->right_ec = ec1;
     340             :             /* mark the RI as usable with this pair of EMs */
     341           0 :             restrictinfo->left_em = em1;
     342           0 :             restrictinfo->right_em = em2;
     343           0 :             return true;
     344             :         }
     345             : 
     346             :         /*
     347             :          * Case 2: need to merge ec1 and ec2.  This should never happen after
     348             :          * the ECs have reached canonical state; otherwise, pathkeys could be
     349             :          * rendered non-canonical by the merge, and relation eclass indexes
     350             :          * would get broken by removal of an eq_classes list entry.
     351             :          */
     352         324 :         if (root->ec_merging_done)
     353           0 :             elog(ERROR, "too late to merge equivalence classes");
     354             : 
     355             :         /*
     356             :          * We add ec2's items to ec1, then set ec2's ec_merged link to point
     357             :          * to ec1 and remove ec2 from the eq_classes list.  We cannot simply
     358             :          * delete ec2 because that could leave dangling pointers in existing
     359             :          * PathKeys.  We leave it behind with a link so that the merged EC can
     360             :          * be found.
     361             :          */
     362         324 :         ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
     363         324 :         ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
     364         324 :         ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
     365         324 :         ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
     366         324 :         ec1->ec_has_const |= ec2->ec_has_const;
     367             :         /* can't need to set has_volatile */
     368         324 :         ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
     369         324 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     370             :                                    ec2->ec_min_security);
     371         324 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     372             :                                    ec2->ec_max_security);
     373         324 :         ec2->ec_merged = ec1;
     374         324 :         root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
     375             :         /* just to avoid debugging confusion w/ dangling pointers: */
     376         324 :         ec2->ec_members = NIL;
     377         324 :         ec2->ec_sources = NIL;
     378         324 :         ec2->ec_derives = NIL;
     379         324 :         ec2->ec_relids = NULL;
     380         324 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     381         324 :         ec1->ec_below_outer_join |= below_outer_join;
     382         324 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     383             :                                    restrictinfo->security_level);
     384         324 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     385             :                                    restrictinfo->security_level);
     386             :         /* mark the RI as associated with this eclass */
     387         324 :         restrictinfo->left_ec = ec1;
     388         324 :         restrictinfo->right_ec = ec1;
     389             :         /* mark the RI as usable with this pair of EMs */
     390         324 :         restrictinfo->left_em = em1;
     391         324 :         restrictinfo->right_em = em2;
     392             :     }
     393      156874 :     else if (ec1)
     394             :     {
     395             :         /* Case 3: add item2 to ec1 */
     396       12798 :         em2 = add_eq_member(ec1, item2, item2_relids, item2_nullable_relids,
     397             :                             false, item2_type);
     398       12798 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     399       12798 :         ec1->ec_below_outer_join |= below_outer_join;
     400       12798 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     401             :                                    restrictinfo->security_level);
     402       12798 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     403             :                                    restrictinfo->security_level);
     404             :         /* mark the RI as associated with this eclass */
     405       12798 :         restrictinfo->left_ec = ec1;
     406       12798 :         restrictinfo->right_ec = ec1;
     407             :         /* mark the RI as usable with this pair of EMs */
     408       12798 :         restrictinfo->left_em = em1;
     409       12798 :         restrictinfo->right_em = em2;
     410             :     }
     411      144076 :     else if (ec2)
     412             :     {
     413             :         /* Case 3: add item1 to ec2 */
     414        1374 :         em1 = add_eq_member(ec2, item1, item1_relids, item1_nullable_relids,
     415             :                             false, item1_type);
     416        1374 :         ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
     417        1374 :         ec2->ec_below_outer_join |= below_outer_join;
     418        1374 :         ec2->ec_min_security = Min(ec2->ec_min_security,
     419             :                                    restrictinfo->security_level);
     420        1374 :         ec2->ec_max_security = Max(ec2->ec_max_security,
     421             :                                    restrictinfo->security_level);
     422             :         /* mark the RI as associated with this eclass */
     423        1374 :         restrictinfo->left_ec = ec2;
     424        1374 :         restrictinfo->right_ec = ec2;
     425             :         /* mark the RI as usable with this pair of EMs */
     426        1374 :         restrictinfo->left_em = em1;
     427        1374 :         restrictinfo->right_em = em2;
     428             :     }
     429             :     else
     430             :     {
     431             :         /* Case 4: make a new, two-entry EC */
     432      142702 :         EquivalenceClass *ec = makeNode(EquivalenceClass);
     433             : 
     434      142702 :         ec->ec_opfamilies = opfamilies;
     435      142702 :         ec->ec_collation = collation;
     436      142702 :         ec->ec_members = NIL;
     437      142702 :         ec->ec_sources = list_make1(restrictinfo);
     438      142702 :         ec->ec_derives = NIL;
     439      142702 :         ec->ec_relids = NULL;
     440      142702 :         ec->ec_has_const = false;
     441      142702 :         ec->ec_has_volatile = false;
     442      142702 :         ec->ec_below_outer_join = below_outer_join;
     443      142702 :         ec->ec_broken = false;
     444      142702 :         ec->ec_sortref = 0;
     445      142702 :         ec->ec_min_security = restrictinfo->security_level;
     446      142702 :         ec->ec_max_security = restrictinfo->security_level;
     447      142702 :         ec->ec_merged = NULL;
     448      142702 :         em1 = add_eq_member(ec, item1, item1_relids, item1_nullable_relids,
     449             :                             false, item1_type);
     450      142702 :         em2 = add_eq_member(ec, item2, item2_relids, item2_nullable_relids,
     451             :                             false, item2_type);
     452             : 
     453      142702 :         root->eq_classes = lappend(root->eq_classes, ec);
     454             : 
     455             :         /* mark the RI as associated with this eclass */
     456      142702 :         restrictinfo->left_ec = ec;
     457      142702 :         restrictinfo->right_ec = ec;
     458             :         /* mark the RI as usable with this pair of EMs */
     459      142702 :         restrictinfo->left_em = em1;
     460      142702 :         restrictinfo->right_em = em2;
     461             :     }
     462             : 
     463      157198 :     return true;
     464             : }
     465             : 
     466             : /*
     467             :  * canonicalize_ec_expression
     468             :  *
     469             :  * This function ensures that the expression exposes the expected type and
     470             :  * collation, so that it will be equal() to other equivalence-class expressions
     471             :  * that it ought to be equal() to.
     472             :  *
     473             :  * The rule for datatypes is that the exposed type should match what it would
     474             :  * be for an input to an operator of the EC's opfamilies; which is usually
     475             :  * the declared input type of the operator, but in the case of polymorphic
     476             :  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
     477             :  * Expressions coming in from quals will generally have the right type
     478             :  * already, but expressions coming from indexkeys may not (because they are
     479             :  * represented without any explicit relabel in pg_index), and the same problem
     480             :  * occurs for sort expressions (because the parser is likewise cavalier about
     481             :  * putting relabels on them).  Such cases will be binary-compatible with the
     482             :  * real operators, so adding a RelabelType is sufficient.
     483             :  *
     484             :  * Also, the expression's exposed collation must match the EC's collation.
     485             :  * This is important because in comparisons like "foo < bar COLLATE baz",
     486             :  * only one of the expressions has the correct exposed collation as we receive
     487             :  * it from the parser.  Forcing both of them to have it ensures that all
     488             :  * variant spellings of such a construct behave the same.  Again, we can
     489             :  * stick on a RelabelType to force the right exposed collation.  (It might
     490             :  * work to not label the collation at all in EC members, but this is risky
     491             :  * since some parts of the system expect exprCollation() to deliver the
     492             :  * right answer for a sort key.)
     493             :  *
     494             :  * Note this code assumes that the expression has already been through
     495             :  * eval_const_expressions, so there are no CollateExprs and no redundant
     496             :  * RelabelTypes.
     497             :  */
     498             : Expr *
     499     1173394 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
     500             : {
     501     1173394 :     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     1173394 :     if (IsPolymorphicType(req_type) || req_type == RECORDOID)
     508         650 :         req_type = expr_type;
     509             : 
     510             :     /*
     511             :      * No work if the expression exposes the right type/collation already.
     512             :      */
     513     2343062 :     if (expr_type != req_type ||
     514     1169668 :         exprCollation((Node *) expr) != req_collation)
     515             :     {
     516             :         /*
     517             :          * Strip any existing RelabelType, then add a new one if needed. This
     518             :          * is to preserve the invariant of no redundant RelabelTypes.
     519             :          *
     520             :          * If we have to change the exposed type of the stripped expression,
     521             :          * set typmod to -1 (since the new type may not have the same typmod
     522             :          * interpretation).  If we only have to change collation, preserve the
     523             :          * exposed typmod.
     524             :          */
     525        9578 :         while (expr && IsA(expr, RelabelType))
     526         950 :             expr = (Expr *) ((RelabelType *) expr)->arg;
     527             : 
     528        4314 :         if (exprType((Node *) expr) != req_type)
     529        3336 :             expr = (Expr *) makeRelabelType(expr,
     530             :                                             req_type,
     531             :                                             -1,
     532             :                                             req_collation,
     533             :                                             COERCE_IMPLICIT_CAST);
     534         978 :         else if (exprCollation((Node *) expr) != req_collation)
     535         598 :             expr = (Expr *) makeRelabelType(expr,
     536             :                                             req_type,
     537             :                                             exprTypmod((Node *) expr),
     538             :                                             req_collation,
     539             :                                             COERCE_IMPLICIT_CAST);
     540             :     }
     541             : 
     542     1173394 :     return expr;
     543             : }
     544             : 
     545             : /*
     546             :  * add_eq_member - build a new EquivalenceMember and add it to an EC
     547             :  */
     548             : static EquivalenceMember *
     549      438024 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
     550             :               Relids nullable_relids, bool is_child, Oid datatype)
     551             : {
     552      438024 :     EquivalenceMember *em = makeNode(EquivalenceMember);
     553             : 
     554      438024 :     em->em_expr = expr;
     555      438024 :     em->em_relids = relids;
     556      438024 :     em->em_nullable_relids = nullable_relids;
     557      438024 :     em->em_is_const = false;
     558      438024 :     em->em_is_child = is_child;
     559      438024 :     em->em_datatype = datatype;
     560             : 
     561      438024 :     if (bms_is_empty(relids))
     562             :     {
     563             :         /*
     564             :          * No Vars, assume it's a pseudoconstant.  This is correct for entries
     565             :          * generated from process_equivalence(), because a WHERE clause can't
     566             :          * contain aggregates or SRFs, and non-volatility was checked before
     567             :          * process_equivalence() ever got called.  But
     568             :          * get_eclass_for_sort_expr() has to work harder.  We put the tests
     569             :          * there not here to save cycles in the equivalence case.
     570             :          */
     571             :         Assert(!is_child);
     572      130570 :         em->em_is_const = true;
     573      130570 :         ec->ec_has_const = true;
     574             :         /* it can't affect ec_relids */
     575             :     }
     576      307454 :     else if (!is_child)         /* child members don't add to ec_relids */
     577             :     {
     578      287608 :         ec->ec_relids = bms_add_members(ec->ec_relids, relids);
     579             :     }
     580      438024 :     ec->ec_members = lappend(ec->ec_members, em);
     581             : 
     582      438024 :     return em;
     583             : }
     584             : 
     585             : 
     586             : /*
     587             :  * get_eclass_for_sort_expr
     588             :  *    Given an expression and opfamily/collation info, find an existing
     589             :  *    equivalence class it is a member of; if none, optionally build a new
     590             :  *    single-member EquivalenceClass for it.
     591             :  *
     592             :  * expr is the expression, and nullable_relids is the set of base relids
     593             :  * that are potentially nullable below it.  We actually only care about
     594             :  * the set of such relids that are used in the expression; but for caller
     595             :  * convenience, we perform that intersection step here.  The caller need
     596             :  * only be sure that nullable_relids doesn't omit any nullable rels that
     597             :  * might appear in the expr.
     598             :  *
     599             :  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
     600             :  * or zero if not.  (It should never be zero if the expression is volatile!)
     601             :  *
     602             :  * If rel is not NULL, it identifies a specific relation we're considering
     603             :  * a path for, and indicates that child EC members for that relation can be
     604             :  * considered.  Otherwise child members are ignored.  (Note: since child EC
     605             :  * members aren't guaranteed unique, a non-NULL value means that there could
     606             :  * be more than one EC that matches the expression; if so it's order-dependent
     607             :  * which one you get.  This is annoying but it only happens in corner cases,
     608             :  * so for now we live with just reporting the first match.  See also
     609             :  * generate_implied_equalities_for_column and match_pathkeys_to_index.)
     610             :  *
     611             :  * If create_it is true, we'll build a new EquivalenceClass when there is no
     612             :  * match.  If create_it is false, we just return NULL when no match.
     613             :  *
     614             :  * This can be used safely both before and after EquivalenceClass merging;
     615             :  * since it never causes merging it does not invalidate any existing ECs
     616             :  * or PathKeys.  However, ECs added after path generation has begun are
     617             :  * of limited usefulness, so usually it's best to create them beforehand.
     618             :  *
     619             :  * Note: opfamilies must be chosen consistently with the way
     620             :  * process_equivalence() would do; that is, generated from a mergejoinable
     621             :  * equality operator.  Else we might fail to detect valid equivalences,
     622             :  * generating poor (but not incorrect) plans.
     623             :  */
     624             : EquivalenceClass *
     625      856900 : get_eclass_for_sort_expr(PlannerInfo *root,
     626             :                          Expr *expr,
     627             :                          Relids nullable_relids,
     628             :                          List *opfamilies,
     629             :                          Oid opcintype,
     630             :                          Oid collation,
     631             :                          Index sortref,
     632             :                          Relids rel,
     633             :                          bool create_it)
     634             : {
     635             :     Relids      expr_relids;
     636             :     EquivalenceClass *newec;
     637             :     EquivalenceMember *newem;
     638             :     ListCell   *lc1;
     639             :     MemoryContext oldcontext;
     640             : 
     641             :     /*
     642             :      * Ensure the expression exposes the correct type and collation.
     643             :      */
     644      856900 :     expr = canonicalize_ec_expression(expr, opcintype, collation);
     645             : 
     646             :     /*
     647             :      * Get the precise set of nullable relids appearing in the expression.
     648             :      */
     649      856900 :     expr_relids = pull_varnos((Node *) expr);
     650      856900 :     nullable_relids = bms_intersect(nullable_relids, expr_relids);
     651             : 
     652             :     /*
     653             :      * Scan through the existing EquivalenceClasses for a match
     654             :      */
     655     2757088 :     foreach(lc1, root->eq_classes)
     656             :     {
     657     2368076 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     658             :         ListCell   *lc2;
     659             : 
     660             :         /*
     661             :          * Never match to a volatile EC, except when we are looking at another
     662             :          * reference to the same volatile SortGroupClause.
     663             :          */
     664     2368076 :         if (cur_ec->ec_has_volatile &&
     665          18 :             (sortref == 0 || sortref != cur_ec->ec_sortref))
     666         184 :             continue;
     667             : 
     668     2367892 :         if (collation != cur_ec->ec_collation)
     669      608772 :             continue;
     670     1759120 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     671      340628 :             continue;
     672             : 
     673     3100574 :         foreach(lc2, cur_ec->ec_members)
     674             :         {
     675     2149970 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
     676             : 
     677             :             /*
     678             :              * Ignore child members unless they match the request.
     679             :              */
     680     2250498 :             if (cur_em->em_is_child &&
     681      100528 :                 !bms_equal(cur_em->em_relids, rel))
     682       82124 :                 continue;
     683             : 
     684             :             /*
     685             :              * If below an outer join, don't match constants: they're not as
     686             :              * constant as they look.
     687             :              */
     688     2252920 :             if (cur_ec->ec_below_outer_join &&
     689      185074 :                 cur_em->em_is_const)
     690       63132 :                 continue;
     691             : 
     692     3995210 :             if (opcintype == cur_em->em_datatype &&
     693     1990496 :                 equal(expr, cur_em->em_expr))
     694      467888 :                 return cur_ec;  /* Match! */
     695             :         }
     696             :     }
     697             : 
     698             :     /* No match; does caller want a NULL result? */
     699      389012 :     if (!create_it)
     700      270410 :         return NULL;
     701             : 
     702             :     /*
     703             :      * OK, build a new single-member EC
     704             :      *
     705             :      * Here, we must be sure that we construct the EC in the right context.
     706             :      */
     707      118602 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
     708             : 
     709      118602 :     newec = makeNode(EquivalenceClass);
     710      118602 :     newec->ec_opfamilies = list_copy(opfamilies);
     711      118602 :     newec->ec_collation = collation;
     712      118602 :     newec->ec_members = NIL;
     713      118602 :     newec->ec_sources = NIL;
     714      118602 :     newec->ec_derives = NIL;
     715      118602 :     newec->ec_relids = NULL;
     716      118602 :     newec->ec_has_const = false;
     717      118602 :     newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
     718      118602 :     newec->ec_below_outer_join = false;
     719      118602 :     newec->ec_broken = false;
     720      118602 :     newec->ec_sortref = sortref;
     721      118602 :     newec->ec_min_security = UINT_MAX;
     722      118602 :     newec->ec_max_security = 0;
     723      118602 :     newec->ec_merged = NULL;
     724             : 
     725      118602 :     if (newec->ec_has_volatile && sortref == 0) /* should not happen */
     726           0 :         elog(ERROR, "volatile EquivalenceClass has no sortref");
     727             : 
     728      118602 :     newem = add_eq_member(newec, copyObject(expr), expr_relids,
     729             :                           nullable_relids, false, opcintype);
     730             : 
     731             :     /*
     732             :      * add_eq_member doesn't check for volatile functions, set-returning
     733             :      * functions, aggregates, or window functions, but such could appear in
     734             :      * sort expressions; so we have to check whether its const-marking was
     735             :      * correct.
     736             :      */
     737      118602 :     if (newec->ec_has_const)
     738             :     {
     739        1546 :         if (newec->ec_has_volatile ||
     740        1432 :             expression_returns_set((Node *) expr) ||
     741        1244 :             contain_agg_clause((Node *) expr) ||
     742         572 :             contain_window_function((Node *) expr))
     743             :         {
     744         218 :             newec->ec_has_const = false;
     745         218 :             newem->em_is_const = false;
     746             :         }
     747             :     }
     748             : 
     749      118602 :     root->eq_classes = lappend(root->eq_classes, newec);
     750             : 
     751             :     /*
     752             :      * If EC merging is already complete, we have to mop up by adding the new
     753             :      * EC to the eclass_indexes of the relation(s) mentioned in it.
     754             :      */
     755      118602 :     if (root->ec_merging_done)
     756             :     {
     757       45480 :         int         ec_index = list_length(root->eq_classes) - 1;
     758       45480 :         int         i = -1;
     759             : 
     760      135572 :         while ((i = bms_next_member(newec->ec_relids, i)) > 0)
     761             :         {
     762       44612 :             RelOptInfo *rel = root->simple_rel_array[i];
     763             : 
     764             :             Assert(rel->reloptkind == RELOPT_BASEREL ||
     765             :                    rel->reloptkind == RELOPT_DEADREL);
     766             : 
     767       44612 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
     768             :                                                  ec_index);
     769             :         }
     770             :     }
     771             : 
     772      118602 :     MemoryContextSwitchTo(oldcontext);
     773             : 
     774      118602 :     return newec;
     775             : }
     776             : 
     777             : 
     778             : /*
     779             :  * generate_base_implied_equalities
     780             :  *    Generate any restriction clauses that we can deduce from equivalence
     781             :  *    classes.
     782             :  *
     783             :  * When an EC contains pseudoconstants, our strategy is to generate
     784             :  * "member = const1" clauses where const1 is the first constant member, for
     785             :  * every other member (including other constants).  If we are able to do this
     786             :  * then we don't need any "var = var" comparisons because we've successfully
     787             :  * constrained all the vars at their points of creation.  If we fail to
     788             :  * generate any of these clauses due to lack of cross-type operators, we fall
     789             :  * back to the "ec_broken" strategy described below.  (XXX if there are
     790             :  * multiple constants of different types, it's possible that we might succeed
     791             :  * in forming all the required clauses if we started from a different const
     792             :  * member; but this seems a sufficiently hokey corner case to not be worth
     793             :  * spending lots of cycles on.)
     794             :  *
     795             :  * For ECs that contain no pseudoconstants, we generate derived clauses
     796             :  * "member1 = member2" for each pair of members belonging to the same base
     797             :  * relation (actually, if there are more than two for the same base relation,
     798             :  * we only need enough clauses to link each to each other).  This provides
     799             :  * the base case for the recursion: each row emitted by a base relation scan
     800             :  * will constrain all computable members of the EC to be equal.  As each
     801             :  * join path is formed, we'll add additional derived clauses on-the-fly
     802             :  * to maintain this invariant (see generate_join_implied_equalities).
     803             :  *
     804             :  * If the opfamilies used by the EC do not provide complete sets of cross-type
     805             :  * equality operators, it is possible that we will fail to generate a clause
     806             :  * that must be generated to maintain the invariant.  (An example: given
     807             :  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
     808             :  * generate "a.x = a.z" as a restriction clause for A.)  In this case we mark
     809             :  * the EC "ec_broken" and fall back to regurgitating its original source
     810             :  * RestrictInfos at appropriate times.  We do not try to retract any derived
     811             :  * clauses already generated from the broken EC, so the resulting plan could
     812             :  * be poor due to bad selectivity estimates caused by redundant clauses.  But
     813             :  * the correct solution to that is to fix the opfamilies ...
     814             :  *
     815             :  * Equality clauses derived by this function are passed off to
     816             :  * process_implied_equality (in plan/initsplan.c) to be inserted into the
     817             :  * restrictinfo datastructures.  Note that this must be called after initial
     818             :  * scanning of the quals and before Path construction begins.
     819             :  *
     820             :  * We make no attempt to avoid generating duplicate RestrictInfos here: we
     821             :  * don't search ec_sources for matches, nor put the created RestrictInfos
     822             :  * into ec_derives.  Doing so would require some slightly ugly changes in
     823             :  * initsplan.c's API, and there's no real advantage, because the clauses
     824             :  * generated here can't duplicate anything we will generate for joins anyway.
     825             :  */
     826             : void
     827      187078 : generate_base_implied_equalities(PlannerInfo *root)
     828             : {
     829             :     int         ec_index;
     830             :     ListCell   *lc;
     831             : 
     832             :     /*
     833             :      * At this point, we're done absorbing knowledge of equivalences in the
     834             :      * query, so no further EC merging should happen, and ECs remaining in the
     835             :      * eq_classes list can be considered canonical.  (But note that it's still
     836             :      * possible for new single-member ECs to be added through
     837             :      * get_eclass_for_sort_expr().)
     838             :      */
     839      187078 :     root->ec_merging_done = true;
     840             : 
     841      187078 :     ec_index = 0;
     842      402594 :     foreach(lc, root->eq_classes)
     843             :     {
     844      215516 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
     845      215516 :         bool        can_generate_joinclause = false;
     846             :         int         i;
     847             : 
     848             :         Assert(ec->ec_merged == NULL);   /* else shouldn't be in list */
     849             :         Assert(!ec->ec_broken); /* not yet anyway... */
     850             : 
     851             :         /*
     852             :          * Generate implied equalities that are restriction clauses.
     853             :          * Single-member ECs won't generate any deductions, either here or at
     854             :          * the join level.
     855             :          */
     856      215516 :         if (list_length(ec->ec_members) > 1)
     857             :         {
     858      152162 :             if (ec->ec_has_const)
     859      129700 :                 generate_base_implied_equalities_const(root, ec);
     860             :             else
     861       22462 :                 generate_base_implied_equalities_no_const(root, ec);
     862             : 
     863             :             /* Recover if we failed to generate required derived clauses */
     864      152162 :             if (ec->ec_broken)
     865          20 :                 generate_base_implied_equalities_broken(root, ec);
     866             : 
     867             :             /* Detect whether this EC might generate join clauses */
     868      152162 :             can_generate_joinclause =
     869      152162 :                 (bms_membership(ec->ec_relids) == BMS_MULTIPLE);
     870             :         }
     871             : 
     872             :         /*
     873             :          * Mark the base rels cited in each eclass (which should all exist by
     874             :          * now) with the eq_classes indexes of all eclasses mentioning them.
     875             :          * This will let us avoid searching in subsequent lookups.  While
     876             :          * we're at it, we can mark base rels that have pending eclass joins;
     877             :          * this is a cheap version of has_relevant_eclass_joinclause().
     878             :          */
     879      215516 :         i = -1;
     880      672856 :         while ((i = bms_next_member(ec->ec_relids, i)) > 0)
     881             :         {
     882      241824 :             RelOptInfo *rel = root->simple_rel_array[i];
     883             : 
     884             :             Assert(rel->reloptkind == RELOPT_BASEREL);
     885             : 
     886      241824 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
     887             :                                                  ec_index);
     888             : 
     889      241824 :             if (can_generate_joinclause)
     890       52884 :                 rel->has_eclass_joins = true;
     891             :         }
     892             : 
     893      215516 :         ec_index++;
     894             :     }
     895      187078 : }
     896             : 
     897             : /*
     898             :  * generate_base_implied_equalities when EC contains pseudoconstant(s)
     899             :  */
     900             : static void
     901      129700 : generate_base_implied_equalities_const(PlannerInfo *root,
     902             :                                        EquivalenceClass *ec)
     903             : {
     904      129700 :     EquivalenceMember *const_em = NULL;
     905             :     ListCell   *lc;
     906             : 
     907             :     /*
     908             :      * In the trivial case where we just had one "var = const" clause, push
     909             :      * the original clause back into the main planner machinery.  There is
     910             :      * nothing to be gained by doing it differently, and we save the effort to
     911             :      * re-build and re-analyze an equality clause that will be exactly
     912             :      * equivalent to the old one.
     913             :      */
     914      254892 :     if (list_length(ec->ec_members) == 2 &&
     915      125192 :         list_length(ec->ec_sources) == 1)
     916             :     {
     917      125192 :         RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
     918             : 
     919      125192 :         if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
     920             :         {
     921      125160 :             distribute_restrictinfo_to_rels(root, restrictinfo);
     922      125160 :             return;
     923             :         }
     924             :     }
     925             : 
     926             :     /*
     927             :      * Find the constant member to use.  We prefer an actual constant to
     928             :      * pseudo-constants (such as Params), because the constraint exclusion
     929             :      * machinery might be able to exclude relations on the basis of generated
     930             :      * "var = const" equalities, but "var = param" won't work for that.
     931             :      */
     932       11996 :     foreach(lc, ec->ec_members)
     933             :     {
     934       11988 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
     935             : 
     936       11988 :         if (cur_em->em_is_const)
     937             :         {
     938        4540 :             const_em = cur_em;
     939        4540 :             if (IsA(cur_em->em_expr, Const))
     940        4532 :                 break;
     941             :         }
     942             :     }
     943             :     Assert(const_em != NULL);
     944             : 
     945             :     /* Generate a derived equality against each other member */
     946       18112 :     foreach(lc, ec->ec_members)
     947             :     {
     948       13592 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
     949             :         Oid         eq_op;
     950             : 
     951             :         Assert(!cur_em->em_is_child);    /* no children yet */
     952       13592 :         if (cur_em == const_em)
     953        4524 :             continue;
     954        9068 :         eq_op = select_equality_operator(ec,
     955             :                                          cur_em->em_datatype,
     956             :                                          const_em->em_datatype);
     957        9068 :         if (!OidIsValid(eq_op))
     958             :         {
     959             :             /* failed... */
     960          20 :             ec->ec_broken = true;
     961          20 :             break;
     962             :         }
     963       36192 :         process_implied_equality(root, eq_op, ec->ec_collation,
     964             :                                  cur_em->em_expr, const_em->em_expr,
     965        9048 :                                  bms_copy(ec->ec_relids),
     966        9048 :                                  bms_union(cur_em->em_nullable_relids,
     967        9048 :                                            const_em->em_nullable_relids),
     968             :                                  ec->ec_min_security,
     969        9048 :                                  ec->ec_below_outer_join,
     970        9048 :                                  cur_em->em_is_const);
     971             :     }
     972             : }
     973             : 
     974             : /*
     975             :  * generate_base_implied_equalities when EC contains no pseudoconstants
     976             :  */
     977             : static void
     978       22462 : generate_base_implied_equalities_no_const(PlannerInfo *root,
     979             :                                           EquivalenceClass *ec)
     980             : {
     981             :     EquivalenceMember **prev_ems;
     982             :     ListCell   *lc;
     983             : 
     984             :     /*
     985             :      * We scan the EC members once and track the last-seen member for each
     986             :      * base relation.  When we see another member of the same base relation,
     987             :      * we generate "prev_em = cur_em".  This results in the minimum number of
     988             :      * derived clauses, but it's possible that it will fail when a different
     989             :      * ordering would succeed.  XXX FIXME: use a UNION-FIND algorithm similar
     990             :      * to the way we build merged ECs.  (Use a list-of-lists for each rel.)
     991             :      */
     992       22462 :     prev_ems = (EquivalenceMember **)
     993       22462 :         palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
     994             : 
     995       67882 :     foreach(lc, ec->ec_members)
     996             :     {
     997       45420 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
     998             :         int         relid;
     999             : 
    1000             :         Assert(!cur_em->em_is_child);    /* no children yet */
    1001       45420 :         if (!bms_get_singleton_member(cur_em->em_relids, &relid))
    1002          40 :             continue;
    1003             :         Assert(relid < root->simple_rel_array_size);
    1004             : 
    1005       45380 :         if (prev_ems[relid] != NULL)
    1006             :         {
    1007         158 :             EquivalenceMember *prev_em = prev_ems[relid];
    1008             :             Oid         eq_op;
    1009             : 
    1010         158 :             eq_op = select_equality_operator(ec,
    1011             :                                              prev_em->em_datatype,
    1012             :                                              cur_em->em_datatype);
    1013         158 :             if (!OidIsValid(eq_op))
    1014             :             {
    1015             :                 /* failed... */
    1016           0 :                 ec->ec_broken = true;
    1017           0 :                 break;
    1018             :             }
    1019         474 :             process_implied_equality(root, eq_op, ec->ec_collation,
    1020             :                                      prev_em->em_expr, cur_em->em_expr,
    1021         158 :                                      bms_copy(ec->ec_relids),
    1022         158 :                                      bms_union(prev_em->em_nullable_relids,
    1023         158 :                                                cur_em->em_nullable_relids),
    1024             :                                      ec->ec_min_security,
    1025         158 :                                      ec->ec_below_outer_join,
    1026             :                                      false);
    1027             :         }
    1028       45380 :         prev_ems[relid] = cur_em;
    1029             :     }
    1030             : 
    1031       22462 :     pfree(prev_ems);
    1032             : 
    1033             :     /*
    1034             :      * We also have to make sure that all the Vars used in the member clauses
    1035             :      * will be available at any join node we might try to reference them at.
    1036             :      * For the moment we force all the Vars to be available at all join nodes
    1037             :      * for this eclass.  Perhaps this could be improved by doing some
    1038             :      * pre-analysis of which members we prefer to join, but it's no worse than
    1039             :      * what happened in the pre-8.3 code.
    1040             :      */
    1041       67882 :     foreach(lc, ec->ec_members)
    1042             :     {
    1043       45420 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1044       45420 :         List       *vars = pull_var_clause((Node *) cur_em->em_expr,
    1045             :                                            PVC_RECURSE_AGGREGATES |
    1046             :                                            PVC_RECURSE_WINDOWFUNCS |
    1047             :                                            PVC_INCLUDE_PLACEHOLDERS);
    1048             : 
    1049       45420 :         add_vars_to_targetlist(root, vars, ec->ec_relids, false);
    1050       45420 :         list_free(vars);
    1051             :     }
    1052       22462 : }
    1053             : 
    1054             : /*
    1055             :  * generate_base_implied_equalities cleanup after failure
    1056             :  *
    1057             :  * What we must do here is push any zero- or one-relation source RestrictInfos
    1058             :  * of the EC back into the main restrictinfo datastructures.  Multi-relation
    1059             :  * clauses will be regurgitated later by generate_join_implied_equalities().
    1060             :  * (We do it this way to maintain continuity with the case that ec_broken
    1061             :  * becomes set only after we've gone up a join level or two.)  However, for
    1062             :  * an EC that contains constants, we can adopt a simpler strategy and just
    1063             :  * throw back all the source RestrictInfos immediately; that works because
    1064             :  * we know that such an EC can't become broken later.  (This rule justifies
    1065             :  * ignoring ec_has_const ECs in generate_join_implied_equalities, even when
    1066             :  * they are broken.)
    1067             :  */
    1068             : static void
    1069          20 : generate_base_implied_equalities_broken(PlannerInfo *root,
    1070             :                                         EquivalenceClass *ec)
    1071             : {
    1072             :     ListCell   *lc;
    1073             : 
    1074          64 :     foreach(lc, ec->ec_sources)
    1075             :     {
    1076          44 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1077             : 
    1078          44 :         if (ec->ec_has_const ||
    1079           0 :             bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
    1080          44 :             distribute_restrictinfo_to_rels(root, restrictinfo);
    1081             :     }
    1082          20 : }
    1083             : 
    1084             : 
    1085             : /*
    1086             :  * generate_join_implied_equalities
    1087             :  *    Generate any join clauses that we can deduce from equivalence classes.
    1088             :  *
    1089             :  * At a join node, we must enforce restriction clauses sufficient to ensure
    1090             :  * that all equivalence-class members computable at that node are equal.
    1091             :  * Since the set of clauses to enforce can vary depending on which subset
    1092             :  * relations are the inputs, we have to compute this afresh for each join
    1093             :  * relation pair.  Hence a fresh List of RestrictInfo nodes is built and
    1094             :  * passed back on each call.
    1095             :  *
    1096             :  * In addition to its use at join nodes, this can be applied to generate
    1097             :  * eclass-based join clauses for use in a parameterized scan of a base rel.
    1098             :  * The reason for the asymmetry of specifying the inner rel as a RelOptInfo
    1099             :  * and the outer rel by Relids is that this usage occurs before we have
    1100             :  * built any join RelOptInfos.
    1101             :  *
    1102             :  * An annoying special case for parameterized scans is that the inner rel can
    1103             :  * be an appendrel child (an "other rel").  In this case we must generate
    1104             :  * appropriate clauses using child EC members.  add_child_rel_equivalences
    1105             :  * must already have been done for the child rel.
    1106             :  *
    1107             :  * The results are sufficient for use in merge, hash, and plain nestloop join
    1108             :  * methods.  We do not worry here about selecting clauses that are optimal
    1109             :  * for use in a parameterized indexscan.  indxpath.c makes its own selections
    1110             :  * of clauses to use, and if the ones we pick here are redundant with those,
    1111             :  * the extras will be eliminated at createplan time, using the parent_ec
    1112             :  * markers that we provide (see is_redundant_derived_clause()).
    1113             :  *
    1114             :  * Because the same join clauses are likely to be needed multiple times as
    1115             :  * we consider different join paths, we avoid generating multiple copies:
    1116             :  * whenever we select a particular pair of EquivalenceMembers to join,
    1117             :  * we check to see if the pair matches any original clause (in ec_sources)
    1118             :  * or previously-built clause (in ec_derives).  This saves memory and allows
    1119             :  * re-use of information cached in RestrictInfos.
    1120             :  *
    1121             :  * join_relids should always equal bms_union(outer_relids, inner_rel->relids).
    1122             :  * We could simplify this function's API by computing it internally, but in
    1123             :  * most current uses, the caller has the value at hand anyway.
    1124             :  */
    1125             : List *
    1126      212620 : generate_join_implied_equalities(PlannerInfo *root,
    1127             :                                  Relids join_relids,
    1128             :                                  Relids outer_relids,
    1129             :                                  RelOptInfo *inner_rel)
    1130             : {
    1131      212620 :     List       *result = NIL;
    1132      212620 :     Relids      inner_relids = inner_rel->relids;
    1133             :     Relids      nominal_inner_relids;
    1134             :     Relids      nominal_join_relids;
    1135             :     Bitmapset * matching_ecs;
    1136             :     int         i;
    1137             : 
    1138             :     /* If inner rel is a child, extra setup work is needed */
    1139      212620 :     if (IS_OTHER_REL(inner_rel))
    1140             :     {
    1141             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1142             : 
    1143             :         /* Fetch relid set for the topmost parent rel */
    1144        3366 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1145             :         /* ECs will be marked with the parent's relid, not the child's */
    1146        3366 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1147             :     }
    1148             :     else
    1149             :     {
    1150      209254 :         nominal_inner_relids = inner_relids;
    1151      209254 :         nominal_join_relids = join_relids;
    1152             :     }
    1153             : 
    1154             :     /*
    1155             :      * Get all eclasses in common between inner_rel's relids and outer_relids
    1156             :      */
    1157      212620 :     matching_ecs = get_common_eclass_indexes(root, inner_rel->relids,
    1158             :                                              outer_relids);
    1159             : 
    1160      212620 :     i = -1;
    1161      543814 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    1162             :     {
    1163      118574 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    1164      118574 :         List       *sublist = NIL;
    1165             : 
    1166             :         /* ECs containing consts do not need any further enforcement */
    1167      118574 :         if (ec->ec_has_const)
    1168       18536 :             continue;
    1169             : 
    1170             :         /* Single-member ECs won't generate any deductions */
    1171      100038 :         if (list_length(ec->ec_members) <= 1)
    1172         428 :             continue;
    1173             : 
    1174             :         /* Sanity check that this eclass overlaps the join */
    1175             :         Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
    1176             : 
    1177       99610 :         if (!ec->ec_broken)
    1178       99438 :             sublist = generate_join_implied_equalities_normal(root,
    1179             :                                                               ec,
    1180             :                                                               join_relids,
    1181             :                                                               outer_relids,
    1182             :                                                               inner_relids);
    1183             : 
    1184             :         /* Recover if we failed to generate required derived clauses */
    1185       99610 :         if (ec->ec_broken)
    1186         192 :             sublist = generate_join_implied_equalities_broken(root,
    1187             :                                                               ec,
    1188             :                                                               nominal_join_relids,
    1189             :                                                               outer_relids,
    1190             :                                                               nominal_inner_relids,
    1191             :                                                               inner_rel);
    1192             : 
    1193       99610 :         result = list_concat(result, sublist);
    1194             :     }
    1195             : 
    1196      212620 :     return result;
    1197             : }
    1198             : 
    1199             : /*
    1200             :  * generate_join_implied_equalities_for_ecs
    1201             :  *    As above, but consider only the listed ECs.
    1202             :  */
    1203             : List *
    1204         792 : generate_join_implied_equalities_for_ecs(PlannerInfo *root,
    1205             :                                          List *eclasses,
    1206             :                                          Relids join_relids,
    1207             :                                          Relids outer_relids,
    1208             :                                          RelOptInfo *inner_rel)
    1209             : {
    1210         792 :     List       *result = NIL;
    1211         792 :     Relids      inner_relids = inner_rel->relids;
    1212             :     Relids      nominal_inner_relids;
    1213             :     Relids      nominal_join_relids;
    1214             :     ListCell   *lc;
    1215             : 
    1216             :     /* If inner rel is a child, extra setup work is needed */
    1217         792 :     if (IS_OTHER_REL(inner_rel))
    1218             :     {
    1219             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1220             : 
    1221             :         /* Fetch relid set for the topmost parent rel */
    1222           0 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1223             :         /* ECs will be marked with the parent's relid, not the child's */
    1224           0 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1225             :     }
    1226             :     else
    1227             :     {
    1228         792 :         nominal_inner_relids = inner_relids;
    1229         792 :         nominal_join_relids = join_relids;
    1230             :     }
    1231             : 
    1232        1604 :     foreach(lc, eclasses)
    1233             :     {
    1234         812 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
    1235         812 :         List       *sublist = NIL;
    1236             : 
    1237             :         /* ECs containing consts do not need any further enforcement */
    1238         812 :         if (ec->ec_has_const)
    1239           0 :             continue;
    1240             : 
    1241             :         /* Single-member ECs won't generate any deductions */
    1242         812 :         if (list_length(ec->ec_members) <= 1)
    1243           0 :             continue;
    1244             : 
    1245             :         /* We can quickly ignore any that don't overlap the join, too */
    1246         812 :         if (!bms_overlap(ec->ec_relids, nominal_join_relids))
    1247           0 :             continue;
    1248             : 
    1249         812 :         if (!ec->ec_broken)
    1250         812 :             sublist = generate_join_implied_equalities_normal(root,
    1251             :                                                               ec,
    1252             :                                                               join_relids,
    1253             :                                                               outer_relids,
    1254             :                                                               inner_relids);
    1255             : 
    1256             :         /* Recover if we failed to generate required derived clauses */
    1257         812 :         if (ec->ec_broken)
    1258           0 :             sublist = generate_join_implied_equalities_broken(root,
    1259             :                                                               ec,
    1260             :                                                               nominal_join_relids,
    1261             :                                                               outer_relids,
    1262             :                                                               nominal_inner_relids,
    1263             :                                                               inner_rel);
    1264             : 
    1265         812 :         result = list_concat(result, sublist);
    1266             :     }
    1267             : 
    1268         792 :     return result;
    1269             : }
    1270             : 
    1271             : /*
    1272             :  * generate_join_implied_equalities for a still-valid EC
    1273             :  */
    1274             : static List *
    1275      100250 : generate_join_implied_equalities_normal(PlannerInfo *root,
    1276             :                                         EquivalenceClass *ec,
    1277             :                                         Relids join_relids,
    1278             :                                         Relids outer_relids,
    1279             :                                         Relids inner_relids)
    1280             : {
    1281      100250 :     List       *result = NIL;
    1282      100250 :     List       *new_members = NIL;
    1283      100250 :     List       *outer_members = NIL;
    1284      100250 :     List       *inner_members = NIL;
    1285             :     ListCell   *lc1;
    1286             : 
    1287             :     /*
    1288             :      * First, scan the EC to identify member values that are computable at the
    1289             :      * outer rel, at the inner rel, or at this relation but not in either
    1290             :      * input rel.  The outer-rel members should already be enforced equal,
    1291             :      * likewise for the inner-rel members.  We'll need to create clauses to
    1292             :      * enforce that any newly computable members are all equal to each other
    1293             :      * as well as to at least one input member, plus enforce at least one
    1294             :      * outer-rel member equal to at least one inner-rel member.
    1295             :      */
    1296      338650 :     foreach(lc1, ec->ec_members)
    1297             :     {
    1298      238400 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
    1299             : 
    1300             :         /*
    1301             :          * We don't need to check explicitly for child EC members.  This test
    1302             :          * against join_relids will cause them to be ignored except when
    1303             :          * considering a child inner rel, which is what we want.
    1304             :          */
    1305      238400 :         if (!bms_is_subset(cur_em->em_relids, join_relids))
    1306       34372 :             continue;           /* not computable yet, or wrong child */
    1307             : 
    1308      204028 :         if (bms_is_subset(cur_em->em_relids, outer_relids))
    1309      103156 :             outer_members = lappend(outer_members, cur_em);
    1310      100872 :         else if (bms_is_subset(cur_em->em_relids, inner_relids))
    1311      100176 :             inner_members = lappend(inner_members, cur_em);
    1312             :         else
    1313         696 :             new_members = lappend(new_members, cur_em);
    1314             :     }
    1315             : 
    1316             :     /*
    1317             :      * First, select the joinclause if needed.  We can equate any one outer
    1318             :      * member to any one inner member, but we have to find a datatype
    1319             :      * combination for which an opfamily member operator exists.  If we have
    1320             :      * choices, we prefer simple Var members (possibly with RelabelType) since
    1321             :      * these are (a) cheapest to compute at runtime and (b) most likely to
    1322             :      * have useful statistics. Also, prefer operators that are also
    1323             :      * hashjoinable.
    1324             :      */
    1325      100250 :     if (outer_members && inner_members)
    1326             :     {
    1327       98594 :         EquivalenceMember *best_outer_em = NULL;
    1328       98594 :         EquivalenceMember *best_inner_em = NULL;
    1329       98594 :         Oid         best_eq_op = InvalidOid;
    1330       98594 :         int         best_score = -1;
    1331             :         RestrictInfo *rinfo;
    1332             : 
    1333      101452 :         foreach(lc1, outer_members)
    1334             :         {
    1335       98642 :             EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
    1336             :             ListCell   *lc2;
    1337             : 
    1338      101508 :             foreach(lc2, inner_members)
    1339             :             {
    1340       98650 :                 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
    1341             :                 Oid         eq_op;
    1342             :                 int         score;
    1343             : 
    1344       98650 :                 eq_op = select_equality_operator(ec,
    1345             :                                                  outer_em->em_datatype,
    1346             :                                                  inner_em->em_datatype);
    1347       98650 :                 if (!OidIsValid(eq_op))
    1348          20 :                     continue;
    1349       98630 :                 score = 0;
    1350      102348 :                 if (IsA(outer_em->em_expr, Var) ||
    1351        6066 :                     (IsA(outer_em->em_expr, RelabelType) &&
    1352        2348 :                      IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
    1353       97056 :                     score++;
    1354      102320 :                 if (IsA(inner_em->em_expr, Var) ||
    1355        6042 :                     (IsA(inner_em->em_expr, RelabelType) &&
    1356        2352 :                      IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
    1357       97116 :                     score++;
    1358       98630 :                 if (op_hashjoinable(eq_op,
    1359       98630 :                                     exprType((Node *) outer_em->em_expr)))
    1360       98580 :                     score++;
    1361       98630 :                 if (score > best_score)
    1362             :                 {
    1363       98574 :                     best_outer_em = outer_em;
    1364       98574 :                     best_inner_em = inner_em;
    1365       98574 :                     best_eq_op = eq_op;
    1366       98574 :                     best_score = score;
    1367       98574 :                     if (best_score == 3)
    1368       95784 :                         break;  /* no need to look further */
    1369             :                 }
    1370             :             }
    1371       98642 :             if (best_score == 3)
    1372       95784 :                 break;          /* no need to look further */
    1373             :         }
    1374       98594 :         if (best_score < 0)
    1375             :         {
    1376             :             /* failed... */
    1377          20 :             ec->ec_broken = true;
    1378          20 :             return NIL;
    1379             :         }
    1380             : 
    1381             :         /*
    1382             :          * Create clause, setting parent_ec to mark it as redundant with other
    1383             :          * joinclauses
    1384             :          */
    1385       98574 :         rinfo = create_join_clause(root, ec, best_eq_op,
    1386             :                                    best_outer_em, best_inner_em,
    1387             :                                    ec);
    1388             : 
    1389       98574 :         result = lappend(result, rinfo);
    1390             :     }
    1391             : 
    1392             :     /*
    1393             :      * Now deal with building restrictions for any expressions that involve
    1394             :      * Vars from both sides of the join.  We have to equate all of these to
    1395             :      * each other as well as to at least one old member (if any).
    1396             :      *
    1397             :      * XXX as in generate_base_implied_equalities_no_const, we could be a lot
    1398             :      * smarter here to avoid unnecessary failures in cross-type situations.
    1399             :      * For now, use the same left-to-right method used there.
    1400             :      */
    1401      100230 :     if (new_members)
    1402             :     {
    1403         696 :         List       *old_members = list_concat(outer_members, inner_members);
    1404         696 :         EquivalenceMember *prev_em = NULL;
    1405             :         RestrictInfo *rinfo;
    1406             : 
    1407             :         /* For now, arbitrarily take the first old_member as the one to use */
    1408         696 :         if (old_members)
    1409         572 :             new_members = lappend(new_members, linitial(old_members));
    1410             : 
    1411        1964 :         foreach(lc1, new_members)
    1412             :         {
    1413        1268 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
    1414             : 
    1415        1268 :             if (prev_em != NULL)
    1416             :             {
    1417             :                 Oid         eq_op;
    1418             : 
    1419         572 :                 eq_op = select_equality_operator(ec,
    1420             :                                                  prev_em->em_datatype,
    1421             :                                                  cur_em->em_datatype);
    1422         572 :                 if (!OidIsValid(eq_op))
    1423             :                 {
    1424             :                     /* failed... */
    1425           0 :                     ec->ec_broken = true;
    1426           0 :                     return NIL;
    1427             :                 }
    1428             :                 /* do NOT set parent_ec, this qual is not redundant! */
    1429         572 :                 rinfo = create_join_clause(root, ec, eq_op,
    1430             :                                            prev_em, cur_em,
    1431             :                                            NULL);
    1432             : 
    1433         572 :                 result = lappend(result, rinfo);
    1434             :             }
    1435        1268 :             prev_em = cur_em;
    1436             :         }
    1437             :     }
    1438             : 
    1439      100230 :     return result;
    1440             : }
    1441             : 
    1442             : /*
    1443             :  * generate_join_implied_equalities cleanup after failure
    1444             :  *
    1445             :  * Return any original RestrictInfos that are enforceable at this join.
    1446             :  *
    1447             :  * In the case of a child inner relation, we have to translate the
    1448             :  * original RestrictInfos from parent to child Vars.
    1449             :  */
    1450             : static List *
    1451         192 : generate_join_implied_equalities_broken(PlannerInfo *root,
    1452             :                                         EquivalenceClass *ec,
    1453             :                                         Relids nominal_join_relids,
    1454             :                                         Relids outer_relids,
    1455             :                                         Relids nominal_inner_relids,
    1456             :                                         RelOptInfo *inner_rel)
    1457             : {
    1458         192 :     List       *result = NIL;
    1459             :     ListCell   *lc;
    1460             : 
    1461         528 :     foreach(lc, ec->ec_sources)
    1462             :     {
    1463         336 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1464         336 :         Relids      clause_relids = restrictinfo->required_relids;
    1465             : 
    1466         520 :         if (bms_is_subset(clause_relids, nominal_join_relids) &&
    1467         352 :             !bms_is_subset(clause_relids, outer_relids) &&
    1468         168 :             !bms_is_subset(clause_relids, nominal_inner_relids))
    1469         168 :             result = lappend(result, restrictinfo);
    1470             :     }
    1471             : 
    1472             :     /*
    1473             :      * If we have to translate, just brute-force apply adjust_appendrel_attrs
    1474             :      * to all the RestrictInfos at once.  This will result in returning
    1475             :      * RestrictInfos that are not listed in ec_derives, but there shouldn't be
    1476             :      * any duplication, and it's a sufficiently narrow corner case that we
    1477             :      * shouldn't sweat too much over it anyway.
    1478             :      *
    1479             :      * Since inner_rel might be an indirect descendant of the baserel
    1480             :      * mentioned in the ec_sources clauses, we have to be prepared to apply
    1481             :      * multiple levels of Var translation.
    1482             :      */
    1483         192 :     if (IS_OTHER_REL(inner_rel) && result != NIL)
    1484         108 :         result = (List *) adjust_appendrel_attrs_multilevel(root,
    1485             :                                                             (Node *) result,
    1486             :                                                             inner_rel->relids,
    1487             :                                                             inner_rel->top_parent_relids);
    1488             : 
    1489         192 :     return result;
    1490             : }
    1491             : 
    1492             : 
    1493             : /*
    1494             :  * select_equality_operator
    1495             :  *    Select a suitable equality operator for comparing two EC members
    1496             :  *
    1497             :  * Returns InvalidOid if no operator can be found for this datatype combination
    1498             :  */
    1499             : static Oid
    1500      152298 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
    1501             : {
    1502             :     ListCell   *lc;
    1503             : 
    1504      152338 :     foreach(lc, ec->ec_opfamilies)
    1505             :     {
    1506      152298 :         Oid         opfamily = lfirst_oid(lc);
    1507             :         Oid         opno;
    1508             : 
    1509      152298 :         opno = get_opfamily_member(opfamily, lefttype, righttype,
    1510             :                                    BTEqualStrategyNumber);
    1511      152298 :         if (!OidIsValid(opno))
    1512          40 :             continue;
    1513             :         /* If no barrier quals in query, don't worry about leaky operators */
    1514      152258 :         if (ec->ec_max_security == 0)
    1515      304132 :             return opno;
    1516             :         /* Otherwise, insist that selected operators be leakproof */
    1517         384 :         if (get_func_leakproof(get_opcode(opno)))
    1518         384 :             return opno;
    1519             :     }
    1520          40 :     return InvalidOid;
    1521             : }
    1522             : 
    1523             : 
    1524             : /*
    1525             :  * create_join_clause
    1526             :  *    Find or make a RestrictInfo comparing the two given EC members
    1527             :  *    with the given operator.
    1528             :  *
    1529             :  * parent_ec is either equal to ec (if the clause is a potentially-redundant
    1530             :  * join clause) or NULL (if not).  We have to treat this as part of the
    1531             :  * match requirements --- it's possible that a clause comparing the same two
    1532             :  * EMs is a join clause in one join path and a restriction clause in another.
    1533             :  */
    1534             : static RestrictInfo *
    1535      137374 : create_join_clause(PlannerInfo *root,
    1536             :                    EquivalenceClass *ec, Oid opno,
    1537             :                    EquivalenceMember *leftem,
    1538             :                    EquivalenceMember *rightem,
    1539             :                    EquivalenceClass *parent_ec)
    1540             : {
    1541             :     RestrictInfo *rinfo;
    1542             :     ListCell   *lc;
    1543             :     MemoryContext oldcontext;
    1544             : 
    1545             :     /*
    1546             :      * Search to see if we already built a RestrictInfo for this pair of
    1547             :      * EquivalenceMembers.  We can use either original source clauses or
    1548             :      * previously-derived clauses.  The check on opno is probably redundant,
    1549             :      * but be safe ...
    1550             :      */
    1551      288836 :     foreach(lc, ec->ec_sources)
    1552             :     {
    1553      151510 :         rinfo = (RestrictInfo *) lfirst(lc);
    1554      217256 :         if (rinfo->left_em == leftem &&
    1555      125934 :             rinfo->right_em == rightem &&
    1556       60236 :             rinfo->parent_ec == parent_ec &&
    1557          48 :             opno == ((OpExpr *) rinfo->clause)->opno)
    1558          48 :             return rinfo;
    1559             :     }
    1560             : 
    1561      272164 :     foreach(lc, ec->ec_derives)
    1562             :     {
    1563      224488 :         rinfo = (RestrictInfo *) lfirst(lc);
    1564      327888 :         if (rinfo->left_em == leftem &&
    1565      193482 :             rinfo->right_em == rightem &&
    1566      179732 :             rinfo->parent_ec == parent_ec &&
    1567       89650 :             opno == ((OpExpr *) rinfo->clause)->opno)
    1568       89650 :             return rinfo;
    1569             :     }
    1570             : 
    1571             :     /*
    1572             :      * Not there, so build it, in planner context so we can re-use it. (Not
    1573             :      * important in normal planning, but definitely so in GEQO.)
    1574             :      */
    1575       47676 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    1576             : 
    1577      143028 :     rinfo = build_implied_join_equality(opno,
    1578             :                                         ec->ec_collation,
    1579             :                                         leftem->em_expr,
    1580             :                                         rightem->em_expr,
    1581       47676 :                                         bms_union(leftem->em_relids,
    1582       47676 :                                                   rightem->em_relids),
    1583       47676 :                                         bms_union(leftem->em_nullable_relids,
    1584       47676 :                                                   rightem->em_nullable_relids),
    1585             :                                         ec->ec_min_security);
    1586             : 
    1587             :     /* Mark the clause as redundant, or not */
    1588       47676 :     rinfo->parent_ec = parent_ec;
    1589             : 
    1590             :     /*
    1591             :      * We know the correct values for left_ec/right_ec, ie this particular EC,
    1592             :      * so we can just set them directly instead of forcing another lookup.
    1593             :      */
    1594       47676 :     rinfo->left_ec = ec;
    1595       47676 :     rinfo->right_ec = ec;
    1596             : 
    1597             :     /* Mark it as usable with these EMs */
    1598       47676 :     rinfo->left_em = leftem;
    1599       47676 :     rinfo->right_em = rightem;
    1600             :     /* and save it for possible re-use */
    1601       47676 :     ec->ec_derives = lappend(ec->ec_derives, rinfo);
    1602             : 
    1603       47676 :     MemoryContextSwitchTo(oldcontext);
    1604             : 
    1605       47676 :     return rinfo;
    1606             : }
    1607             : 
    1608             : 
    1609             : /*
    1610             :  * reconsider_outer_join_clauses
    1611             :  *    Re-examine any outer-join clauses that were set aside by
    1612             :  *    distribute_qual_to_rels(), and see if we can derive any
    1613             :  *    EquivalenceClasses from them.  Then, if they were not made
    1614             :  *    redundant, push them out into the regular join-clause lists.
    1615             :  *
    1616             :  * When we have mergejoinable clauses A = B that are outer-join clauses,
    1617             :  * we can't blindly combine them with other clauses A = C to deduce B = C,
    1618             :  * since in fact the "equality" A = B won't necessarily hold above the
    1619             :  * outer join (one of the variables might be NULL instead).  Nonetheless
    1620             :  * there are cases where we can add qual clauses using transitivity.
    1621             :  *
    1622             :  * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
    1623             :  * for which there is also an equivalence clause OUTERVAR = CONSTANT.
    1624             :  * It is safe and useful to push a clause INNERVAR = CONSTANT into the
    1625             :  * evaluation of the inner (nullable) relation, because any inner rows not
    1626             :  * meeting this condition will not contribute to the outer-join result anyway.
    1627             :  * (Any outer rows they could join to will be eliminated by the pushed-down
    1628             :  * equivalence clause.)
    1629             :  *
    1630             :  * Note that the above rule does not work for full outer joins; nor is it
    1631             :  * very interesting to consider cases where the generated equivalence clause
    1632             :  * would involve relations outside the outer join, since such clauses couldn't
    1633             :  * be pushed into the inner side's scan anyway.  So the restriction to
    1634             :  * outervar = pseudoconstant is not really giving up anything.
    1635             :  *
    1636             :  * For full-join cases, we can only do something useful if it's a FULL JOIN
    1637             :  * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
    1638             :  * By the time it gets here, the merged column will look like
    1639             :  *      COALESCE(LEFTVAR, RIGHTVAR)
    1640             :  * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
    1641             :  * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
    1642             :  * and RIGHTVAR = CONSTANT into the input relations, since any rows not
    1643             :  * meeting these conditions cannot contribute to the join result.
    1644             :  *
    1645             :  * Again, there isn't any traction to be gained by trying to deal with
    1646             :  * clauses comparing a mergedvar to a non-pseudoconstant.  So we can make
    1647             :  * use of the EquivalenceClasses to search for matching variables that were
    1648             :  * equivalenced to constants.  The interesting outer-join clauses were
    1649             :  * accumulated for us by distribute_qual_to_rels.
    1650             :  *
    1651             :  * When we find one of these cases, we implement the changes we want by
    1652             :  * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
    1653             :  * and pushing it into the EquivalenceClass structures.  This is because we
    1654             :  * may already know that INNERVAR is equivalenced to some other var(s), and
    1655             :  * we'd like the constant to propagate to them too.  Note that it would be
    1656             :  * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
    1657             :  * that could result in propagating constant restrictions from
    1658             :  * INNERVAR to OUTERVAR, which would be very wrong.
    1659             :  *
    1660             :  * It's possible that the INNERVAR is also an OUTERVAR for some other
    1661             :  * outer-join clause, in which case the process can be repeated.  So we repeat
    1662             :  * looping over the lists of clauses until no further deductions can be made.
    1663             :  * Whenever we do make a deduction, we remove the generating clause from the
    1664             :  * lists, since we don't want to make the same deduction twice.
    1665             :  *
    1666             :  * If we don't find any match for a set-aside outer join clause, we must
    1667             :  * throw it back into the regular joinclause processing by passing it to
    1668             :  * distribute_restrictinfo_to_rels().  If we do generate a derived clause,
    1669             :  * however, the outer-join clause is redundant.  We still throw it back,
    1670             :  * because otherwise the join will be seen as a clauseless join and avoided
    1671             :  * during join order searching; but we mark it as redundant to keep from
    1672             :  * messing up the joinrel's size estimate.  (This behavior means that the
    1673             :  * API for this routine is uselessly complex: we could have just put all
    1674             :  * the clauses into the regular processing initially.  We keep it because
    1675             :  * someday we might want to do something else, such as inserting "dummy"
    1676             :  * joinclauses instead of real ones.)
    1677             :  *
    1678             :  * Outer join clauses that are marked outerjoin_delayed are special: this
    1679             :  * condition means that one or both VARs might go to null due to a lower
    1680             :  * outer join.  We can still push a constant through the clause, but only
    1681             :  * if its operator is strict; and we *have to* throw the clause back into
    1682             :  * regular joinclause processing.  By keeping the strict join clause,
    1683             :  * we ensure that any null-extended rows that are mistakenly generated due
    1684             :  * to suppressing rows not matching the constant will be rejected at the
    1685             :  * upper outer join.  (This doesn't work for full-join clauses.)
    1686             :  */
    1687             : void
    1688      192660 : reconsider_outer_join_clauses(PlannerInfo *root)
    1689             : {
    1690             :     bool        found;
    1691             :     ListCell   *cell;
    1692             : 
    1693             :     /* Outer loop repeats until we find no more deductions */
    1694             :     do
    1695             :     {
    1696      192660 :         found = false;
    1697             : 
    1698             :         /* Process the LEFT JOIN clauses */
    1699      224288 :         foreach(cell, root->left_join_clauses)
    1700             :         {
    1701       31628 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1702             : 
    1703       31628 :             if (reconsider_outer_join_clause(root, rinfo, true))
    1704             :             {
    1705        5274 :                 found = true;
    1706             :                 /* remove it from the list */
    1707        5274 :                 root->left_join_clauses =
    1708        5274 :                     foreach_delete_current(root->left_join_clauses, cell);
    1709             :                 /* we throw it back anyway (see notes above) */
    1710             :                 /* but the thrown-back clause has no extra selectivity */
    1711        5274 :                 rinfo->norm_selec = 2.0;
    1712        5274 :                 rinfo->outer_selec = 1.0;
    1713        5274 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1714             :             }
    1715             :         }
    1716             : 
    1717             :         /* Process the RIGHT JOIN clauses */
    1718      203272 :         foreach(cell, root->right_join_clauses)
    1719             :         {
    1720       10612 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1721             : 
    1722       10612 :             if (reconsider_outer_join_clause(root, rinfo, false))
    1723             :             {
    1724         312 :                 found = true;
    1725             :                 /* remove it from the list */
    1726         312 :                 root->right_join_clauses =
    1727         312 :                     foreach_delete_current(root->right_join_clauses, cell);
    1728             :                 /* we throw it back anyway (see notes above) */
    1729             :                 /* but the thrown-back clause has no extra selectivity */
    1730         312 :                 rinfo->norm_selec = 2.0;
    1731         312 :                 rinfo->outer_selec = 1.0;
    1732         312 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1733             :             }
    1734             :         }
    1735             : 
    1736             :         /* Process the FULL JOIN clauses */
    1737      193182 :         foreach(cell, root->full_join_clauses)
    1738             :         {
    1739         522 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1740             : 
    1741         522 :             if (reconsider_full_join_clause(root, rinfo))
    1742             :             {
    1743           4 :                 found = true;
    1744             :                 /* remove it from the list */
    1745           4 :                 root->full_join_clauses =
    1746           4 :                     foreach_delete_current(root->full_join_clauses, cell);
    1747             :                 /* we throw it back anyway (see notes above) */
    1748             :                 /* but the thrown-back clause has no extra selectivity */
    1749           4 :                 rinfo->norm_selec = 2.0;
    1750           4 :                 rinfo->outer_selec = 1.0;
    1751           4 :                 distribute_restrictinfo_to_rels(root, rinfo);
    1752             :             }
    1753             :         }
    1754      192660 :     } while (found);
    1755             : 
    1756             :     /* Now, any remaining clauses have to be thrown back */
    1757      211570 :     foreach(cell, root->left_join_clauses)
    1758             :     {
    1759       24492 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1760             : 
    1761       24492 :         distribute_restrictinfo_to_rels(root, rinfo);
    1762             :     }
    1763      195656 :     foreach(cell, root->right_join_clauses)
    1764             :     {
    1765        8578 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1766             : 
    1767        8578 :         distribute_restrictinfo_to_rels(root, rinfo);
    1768             :     }
    1769      187596 :     foreach(cell, root->full_join_clauses)
    1770             :     {
    1771         518 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    1772             : 
    1773         518 :         distribute_restrictinfo_to_rels(root, rinfo);
    1774             :     }
    1775      187078 : }
    1776             : 
    1777             : /*
    1778             :  * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
    1779             :  *
    1780             :  * Returns true if we were able to propagate a constant through the clause.
    1781             :  */
    1782             : static bool
    1783       42240 : reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo,
    1784             :                              bool outer_on_left)
    1785             : {
    1786             :     Expr       *outervar,
    1787             :                *innervar;
    1788             :     Oid         opno,
    1789             :                 collation,
    1790             :                 left_type,
    1791             :                 right_type,
    1792             :                 inner_datatype;
    1793             :     Relids      inner_relids,
    1794             :                 inner_nullable_relids;
    1795             :     ListCell   *lc1;
    1796             : 
    1797             :     Assert(is_opclause(rinfo->clause));
    1798       42240 :     opno = ((OpExpr *) rinfo->clause)->opno;
    1799       42240 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    1800             : 
    1801             :     /* If clause is outerjoin_delayed, operator must be strict */
    1802       42240 :     if (rinfo->outerjoin_delayed && !op_strict(opno))
    1803           0 :         return false;
    1804             : 
    1805             :     /* Extract needed info from the clause */
    1806       42240 :     op_input_types(opno, &left_type, &right_type);
    1807       42240 :     if (outer_on_left)
    1808             :     {
    1809       31628 :         outervar = (Expr *) get_leftop(rinfo->clause);
    1810       31628 :         innervar = (Expr *) get_rightop(rinfo->clause);
    1811       31628 :         inner_datatype = right_type;
    1812       31628 :         inner_relids = rinfo->right_relids;
    1813             :     }
    1814             :     else
    1815             :     {
    1816       10612 :         outervar = (Expr *) get_rightop(rinfo->clause);
    1817       10612 :         innervar = (Expr *) get_leftop(rinfo->clause);
    1818       10612 :         inner_datatype = left_type;
    1819       10612 :         inner_relids = rinfo->left_relids;
    1820             :     }
    1821       42240 :     inner_nullable_relids = bms_intersect(inner_relids,
    1822       42240 :                                           rinfo->nullable_relids);
    1823             : 
    1824             :     /* Scan EquivalenceClasses for a match to outervar */
    1825      207064 :     foreach(lc1, root->eq_classes)
    1826             :     {
    1827      170410 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    1828             :         bool        match;
    1829             :         ListCell   *lc2;
    1830             : 
    1831             :         /* Ignore EC unless it contains pseudoconstants */
    1832      170410 :         if (!cur_ec->ec_has_const)
    1833      115426 :             continue;
    1834             :         /* Never match to a volatile EC */
    1835       54984 :         if (cur_ec->ec_has_volatile)
    1836           0 :             continue;
    1837             :         /* It has to match the outer-join clause as to semantics, too */
    1838       54984 :         if (collation != cur_ec->ec_collation)
    1839        1150 :             continue;
    1840       53834 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    1841        9650 :             continue;
    1842             :         /* Does it contain a match to outervar? */
    1843       44184 :         match = false;
    1844      129922 :         foreach(lc2, cur_ec->ec_members)
    1845             :         {
    1846       91324 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    1847             : 
    1848             :             Assert(!cur_em->em_is_child);    /* no children yet */
    1849       91324 :             if (equal(outervar, cur_em->em_expr))
    1850             :             {
    1851        5586 :                 match = true;
    1852        5586 :                 break;
    1853             :             }
    1854             :         }
    1855       44184 :         if (!match)
    1856       38598 :             continue;           /* no match, so ignore this EC */
    1857             : 
    1858             :         /*
    1859             :          * Yes it does!  Try to generate a clause INNERVAR = CONSTANT for each
    1860             :          * CONSTANT in the EC.  Note that we must succeed with at least one
    1861             :          * constant before we can decide to throw away the outer-join clause.
    1862             :          */
    1863        5586 :         match = false;
    1864       18972 :         foreach(lc2, cur_ec->ec_members)
    1865             :         {
    1866       13386 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    1867             :             Oid         eq_op;
    1868             :             RestrictInfo *newrinfo;
    1869             : 
    1870       13386 :             if (!cur_em->em_is_const)
    1871       15544 :                 continue;       /* ignore non-const members */
    1872        5614 :             eq_op = select_equality_operator(cur_ec,
    1873             :                                              inner_datatype,
    1874             :                                              cur_em->em_datatype);
    1875        5614 :             if (!OidIsValid(eq_op))
    1876           0 :                 continue;       /* can't generate equality */
    1877        5614 :             newrinfo = build_implied_join_equality(eq_op,
    1878             :                                                    cur_ec->ec_collation,
    1879             :                                                    innervar,
    1880             :                                                    cur_em->em_expr,
    1881             :                                                    bms_copy(inner_relids),
    1882             :                                                    bms_copy(inner_nullable_relids),
    1883             :                                                    cur_ec->ec_min_security);
    1884        5614 :             if (process_equivalence(root, &newrinfo, true))
    1885        5614 :                 match = true;
    1886             :         }
    1887             : 
    1888             :         /*
    1889             :          * If we were able to equate INNERVAR to any constant, report success.
    1890             :          * Otherwise, fall out of the search loop, since we know the OUTERVAR
    1891             :          * appears in at most one EC.
    1892             :          */
    1893        5586 :         if (match)
    1894        5586 :             return true;
    1895             :         else
    1896           0 :             break;
    1897             :     }
    1898             : 
    1899       36654 :     return false;               /* failed to make any deduction */
    1900             : }
    1901             : 
    1902             : /*
    1903             :  * reconsider_outer_join_clauses for a single FULL JOIN clause
    1904             :  *
    1905             :  * Returns true if we were able to propagate a constant through the clause.
    1906             :  */
    1907             : static bool
    1908         522 : reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
    1909             : {
    1910             :     Expr       *leftvar;
    1911             :     Expr       *rightvar;
    1912             :     Oid         opno,
    1913             :                 collation,
    1914             :                 left_type,
    1915             :                 right_type;
    1916             :     Relids      left_relids,
    1917             :                 right_relids,
    1918             :                 left_nullable_relids,
    1919             :                 right_nullable_relids;
    1920             :     ListCell   *lc1;
    1921             : 
    1922             :     /* Can't use an outerjoin_delayed clause here */
    1923         522 :     if (rinfo->outerjoin_delayed)
    1924          38 :         return false;
    1925             : 
    1926             :     /* Extract needed info from the clause */
    1927             :     Assert(is_opclause(rinfo->clause));
    1928         484 :     opno = ((OpExpr *) rinfo->clause)->opno;
    1929         484 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    1930         484 :     op_input_types(opno, &left_type, &right_type);
    1931         484 :     leftvar = (Expr *) get_leftop(rinfo->clause);
    1932         484 :     rightvar = (Expr *) get_rightop(rinfo->clause);
    1933         484 :     left_relids = rinfo->left_relids;
    1934         484 :     right_relids = rinfo->right_relids;
    1935         484 :     left_nullable_relids = bms_intersect(left_relids,
    1936         484 :                                          rinfo->nullable_relids);
    1937         484 :     right_nullable_relids = bms_intersect(right_relids,
    1938         484 :                                           rinfo->nullable_relids);
    1939             : 
    1940        2044 :     foreach(lc1, root->eq_classes)
    1941             :     {
    1942        1564 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    1943        1564 :         EquivalenceMember *coal_em = NULL;
    1944             :         bool        match;
    1945             :         bool        matchleft;
    1946             :         bool        matchright;
    1947             :         ListCell   *lc2;
    1948             : 
    1949             :         /* Ignore EC unless it contains pseudoconstants */
    1950        1564 :         if (!cur_ec->ec_has_const)
    1951        1420 :             continue;
    1952             :         /* Never match to a volatile EC */
    1953         144 :         if (cur_ec->ec_has_volatile)
    1954           0 :             continue;
    1955             :         /* It has to match the outer-join clause as to semantics, too */
    1956         144 :         if (collation != cur_ec->ec_collation)
    1957          24 :             continue;
    1958         120 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    1959           0 :             continue;
    1960             : 
    1961             :         /*
    1962             :          * Does it contain a COALESCE(leftvar, rightvar) construct?
    1963             :          *
    1964             :          * We can assume the COALESCE() inputs are in the same order as the
    1965             :          * join clause, since both were automatically generated in the cases
    1966             :          * we care about.
    1967             :          *
    1968             :          * XXX currently this may fail to match in cross-type cases because
    1969             :          * the COALESCE will contain typecast operations while the join clause
    1970             :          * may not (if there is a cross-type mergejoin operator available for
    1971             :          * the two column types). Is it OK to strip implicit coercions from
    1972             :          * the COALESCE arguments?
    1973             :          */
    1974         120 :         match = false;
    1975         344 :         foreach(lc2, cur_ec->ec_members)
    1976             :         {
    1977         228 :             coal_em = (EquivalenceMember *) lfirst(lc2);
    1978             :             Assert(!coal_em->em_is_child);   /* no children yet */
    1979         228 :             if (IsA(coal_em->em_expr, CoalesceExpr))
    1980             :             {
    1981           4 :                 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
    1982             :                 Node       *cfirst;
    1983             :                 Node       *csecond;
    1984             : 
    1985           4 :                 if (list_length(cexpr->args) != 2)
    1986           0 :                     continue;
    1987           4 :                 cfirst = (Node *) linitial(cexpr->args);
    1988           4 :                 csecond = (Node *) lsecond(cexpr->args);
    1989             : 
    1990           4 :                 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
    1991             :                 {
    1992           4 :                     match = true;
    1993           4 :                     break;
    1994             :                 }
    1995             :             }
    1996             :         }
    1997         120 :         if (!match)
    1998         116 :             continue;           /* no match, so ignore this EC */
    1999             : 
    2000             :         /*
    2001             :          * Yes it does!  Try to generate clauses LEFTVAR = CONSTANT and
    2002             :          * RIGHTVAR = CONSTANT for each CONSTANT in the EC.  Note that we must
    2003             :          * succeed with at least one constant for each var before we can
    2004             :          * decide to throw away the outer-join clause.
    2005             :          */
    2006           4 :         matchleft = matchright = false;
    2007          12 :         foreach(lc2, cur_ec->ec_members)
    2008             :         {
    2009           8 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    2010             :             Oid         eq_op;
    2011             :             RestrictInfo *newrinfo;
    2012             : 
    2013           8 :             if (!cur_em->em_is_const)
    2014           4 :                 continue;       /* ignore non-const members */
    2015           4 :             eq_op = select_equality_operator(cur_ec,
    2016             :                                              left_type,
    2017             :                                              cur_em->em_datatype);
    2018           4 :             if (OidIsValid(eq_op))
    2019             :             {
    2020           4 :                 newrinfo = build_implied_join_equality(eq_op,
    2021             :                                                        cur_ec->ec_collation,
    2022             :                                                        leftvar,
    2023             :                                                        cur_em->em_expr,
    2024             :                                                        bms_copy(left_relids),
    2025             :                                                        bms_copy(left_nullable_relids),
    2026             :                                                        cur_ec->ec_min_security);
    2027           4 :                 if (process_equivalence(root, &newrinfo, true))
    2028           4 :                     matchleft = true;
    2029             :             }
    2030           4 :             eq_op = select_equality_operator(cur_ec,
    2031             :                                              right_type,
    2032             :                                              cur_em->em_datatype);
    2033           4 :             if (OidIsValid(eq_op))
    2034             :             {
    2035           4 :                 newrinfo = build_implied_join_equality(eq_op,
    2036             :                                                        cur_ec->ec_collation,
    2037             :                                                        rightvar,
    2038             :                                                        cur_em->em_expr,
    2039             :                                                        bms_copy(right_relids),
    2040             :                                                        bms_copy(right_nullable_relids),
    2041             :                                                        cur_ec->ec_min_security);
    2042           4 :                 if (process_equivalence(root, &newrinfo, true))
    2043           4 :                     matchright = true;
    2044             :             }
    2045             :         }
    2046             : 
    2047             :         /*
    2048             :          * If we were able to equate both vars to constants, we're done, and
    2049             :          * we can throw away the full-join clause as redundant.  Moreover, we
    2050             :          * can remove the COALESCE entry from the EC, since the added
    2051             :          * restrictions ensure it will always have the expected value. (We
    2052             :          * don't bother trying to update ec_relids or ec_sources.)
    2053             :          */
    2054           4 :         if (matchleft && matchright)
    2055             :         {
    2056           4 :             cur_ec->ec_members = list_delete_ptr(cur_ec->ec_members, coal_em);
    2057           4 :             return true;
    2058             :         }
    2059             : 
    2060             :         /*
    2061             :          * Otherwise, fall out of the search loop, since we know the COALESCE
    2062             :          * appears in at most one EC (XXX might stop being true if we allow
    2063             :          * stripping of coercions above?)
    2064             :          */
    2065           0 :         break;
    2066             :     }
    2067             : 
    2068         480 :     return false;               /* failed to make any deduction */
    2069             : }
    2070             : 
    2071             : 
    2072             : /*
    2073             :  * exprs_known_equal
    2074             :  *    Detect whether two expressions are known equal due to equivalence
    2075             :  *    relationships.
    2076             :  *
    2077             :  * Actually, this only shows that the expressions are equal according
    2078             :  * to some opfamily's notion of equality --- but we only use it for
    2079             :  * selectivity estimation, so a fuzzy idea of equality is OK.
    2080             :  *
    2081             :  * Note: does not bother to check for "equal(item1, item2)"; caller must
    2082             :  * check that case if it's possible to pass identical items.
    2083             :  */
    2084             : bool
    2085         364 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
    2086             : {
    2087             :     ListCell   *lc1;
    2088             : 
    2089        1902 :     foreach(lc1, root->eq_classes)
    2090             :     {
    2091        1594 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
    2092        1594 :         bool        item1member = false;
    2093        1594 :         bool        item2member = false;
    2094             :         ListCell   *lc2;
    2095             : 
    2096             :         /* Never match to a volatile EC */
    2097        1594 :         if (ec->ec_has_volatile)
    2098           0 :             continue;
    2099             : 
    2100        4702 :         foreach(lc2, ec->ec_members)
    2101             :         {
    2102        3164 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2103             : 
    2104        3164 :             if (em->em_is_child)
    2105         832 :                 continue;       /* ignore children here */
    2106        2332 :             if (equal(item1, em->em_expr))
    2107         324 :                 item1member = true;
    2108        2008 :             else if (equal(item2, em->em_expr))
    2109         324 :                 item2member = true;
    2110             :             /* Exit as soon as equality is proven */
    2111        2332 :             if (item1member && item2member)
    2112          56 :                 return true;
    2113             :         }
    2114             :     }
    2115         308 :     return false;
    2116             : }
    2117             : 
    2118             : 
    2119             : /*
    2120             :  * match_eclasses_to_foreign_key_col
    2121             :  *    See whether a foreign key column match is proven by any eclass.
    2122             :  *
    2123             :  * If the referenced and referencing Vars of the fkey's colno'th column are
    2124             :  * known equal due to any eclass, return that eclass; otherwise return NULL.
    2125             :  * (In principle there might be more than one matching eclass if multiple
    2126             :  * collations are involved, but since collation doesn't matter for equality,
    2127             :  * we ignore that fine point here.)  This is much like exprs_known_equal,
    2128             :  * except that we insist on the comparison operator matching the eclass, so
    2129             :  * that the result is definite not approximate.
    2130             :  */
    2131             : EquivalenceClass *
    2132        1318 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
    2133             :                                   ForeignKeyOptInfo *fkinfo,
    2134             :                                   int colno)
    2135             : {
    2136        1318 :     Index       var1varno = fkinfo->con_relid;
    2137        1318 :     AttrNumber  var1attno = fkinfo->conkey[colno];
    2138        1318 :     Index       var2varno = fkinfo->ref_relid;
    2139        1318 :     AttrNumber  var2attno = fkinfo->confkey[colno];
    2140        1318 :     Oid         eqop = fkinfo->conpfeqop[colno];
    2141        1318 :     RelOptInfo *rel1 = root->simple_rel_array[var1varno];
    2142        1318 :     RelOptInfo *rel2 = root->simple_rel_array[var2varno];
    2143        1318 :     List       *opfamilies = NIL;   /* compute only if needed */
    2144             :     Bitmapset  *matching_ecs;
    2145             :     int         i;
    2146             : 
    2147             :     /* Consider only eclasses mentioning both relations */
    2148             :     Assert(root->ec_merging_done);
    2149             :     Assert(IS_SIMPLE_REL(rel1));
    2150             :     Assert(IS_SIMPLE_REL(rel2));
    2151        1318 :     matching_ecs = bms_intersect(rel1->eclass_indexes,
    2152        1318 :                                  rel2->eclass_indexes);
    2153             : 
    2154        1318 :     i = -1;
    2155        2636 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2156             :     {
    2157         166 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2158             :                                                              i);
    2159         166 :         bool        item1member = false;
    2160         166 :         bool        item2member = false;
    2161             :         ListCell   *lc2;
    2162             : 
    2163             :         /* Never match to a volatile EC */
    2164         166 :         if (ec->ec_has_volatile)
    2165           0 :             continue;
    2166             :         /* Note: it seems okay to match to "broken" eclasses here */
    2167             : 
    2168         332 :         foreach(lc2, ec->ec_members)
    2169             :         {
    2170         332 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2171             :             Var        *var;
    2172             : 
    2173         332 :             if (em->em_is_child)
    2174           0 :                 continue;       /* ignore children here */
    2175             : 
    2176             :             /* EM must be a Var, possibly with RelabelType */
    2177         332 :             var = (Var *) em->em_expr;
    2178         664 :             while (var && IsA(var, RelabelType))
    2179           0 :                 var = (Var *) ((RelabelType *) var)->arg;
    2180         332 :             if (!(var && IsA(var, Var)))
    2181           0 :                 continue;
    2182             : 
    2183             :             /* Match? */
    2184         332 :             if (var->varno == var1varno && var->varattno == var1attno)
    2185         166 :                 item1member = true;
    2186         166 :             else if (var->varno == var2varno && var->varattno == var2attno)
    2187         166 :                 item2member = true;
    2188             : 
    2189             :             /* Have we found both PK and FK column in this EC? */
    2190         332 :             if (item1member && item2member)
    2191             :             {
    2192             :                 /*
    2193             :                  * Succeed if eqop matches EC's opfamilies.  We could test
    2194             :                  * this before scanning the members, but it's probably cheaper
    2195             :                  * to test for member matches first.
    2196             :                  */
    2197         166 :                 if (opfamilies == NIL)  /* compute if we didn't already */
    2198         166 :                     opfamilies = get_mergejoin_opfamilies(eqop);
    2199         166 :                 if (equal(opfamilies, ec->ec_opfamilies))
    2200         166 :                     return ec;
    2201             :                 /* Otherwise, done with this EC, move on to the next */
    2202           0 :                 break;
    2203             :             }
    2204             :         }
    2205             :     }
    2206        1152 :     return NULL;
    2207             : }
    2208             : 
    2209             : 
    2210             : /*
    2211             :  * add_child_rel_equivalences
    2212             :  *    Search for EC members that reference the parent_rel, and
    2213             :  *    add transformed members referencing the child_rel.
    2214             :  *
    2215             :  * Note that this function won't be called at all unless we have at least some
    2216             :  * reason to believe that the EC members it generates will be useful.
    2217             :  *
    2218             :  * parent_rel and child_rel could be derived from appinfo, but since the
    2219             :  * caller has already computed them, we might as well just pass them in.
    2220             :  */
    2221             : void
    2222       11768 : add_child_rel_equivalences(PlannerInfo *root,
    2223             :                            AppendRelInfo *appinfo,
    2224             :                            RelOptInfo *parent_rel,
    2225             :                            RelOptInfo *child_rel)
    2226             : {
    2227             :     int         i;
    2228             : 
    2229             :     /*
    2230             :      * EC merging should be complete already, so we can use the parent rel's
    2231             :      * eclass_indexes to avoid searching all of root->eq_classes.
    2232             :      */
    2233             :     Assert(root->ec_merging_done);
    2234             :     Assert(IS_SIMPLE_REL(parent_rel));
    2235             : 
    2236       11768 :     i = -1;
    2237       43358 :     while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
    2238             :     {
    2239       19822 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2240             :         int         num_members;
    2241             : 
    2242             :         /*
    2243             :          * If this EC contains a volatile expression, then generating child
    2244             :          * EMs would be downright dangerous, so skip it.  We rely on a
    2245             :          * volatile EC having only one EM.
    2246             :          */
    2247       19822 :         if (cur_ec->ec_has_volatile)
    2248           0 :             continue;
    2249             : 
    2250             :         /* Sanity check eclass_indexes only contain ECs for parent_rel */
    2251             :         Assert(bms_is_subset(child_rel->top_parent_relids, cur_ec->ec_relids));
    2252             : 
    2253             :         /*
    2254             :          * We don't use foreach() here because there's no point in scanning
    2255             :          * newly-added child members, so we can stop after the last
    2256             :          * pre-existing EC member.
    2257             :          */
    2258       19822 :         num_members = list_length(cur_ec->ec_members);
    2259       92636 :         for (int pos = 0; pos < num_members; pos++)
    2260             :         {
    2261       72814 :             EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
    2262             : 
    2263       72814 :             if (cur_em->em_is_const)
    2264        1788 :                 continue;       /* ignore consts here */
    2265             : 
    2266             :             /*
    2267             :              * We consider only original EC members here, not
    2268             :              * already-transformed child members.  Otherwise, if some original
    2269             :              * member expression references more than one appendrel, we'd get
    2270             :              * an O(N^2) explosion of useless derived expressions for
    2271             :              * combinations of children.
    2272             :              */
    2273       71026 :             if (cur_em->em_is_child)
    2274       45876 :                 continue;       /* ignore children here */
    2275             : 
    2276             :             /* Does this member reference child's topmost parent rel? */
    2277       25150 :             if (bms_overlap(cur_em->em_relids, child_rel->top_parent_relids))
    2278             :             {
    2279             :                 /* Yes, generate transformed child version */
    2280             :                 Expr       *child_expr;
    2281             :                 Relids      new_relids;
    2282             :                 Relids      new_nullable_relids;
    2283             : 
    2284       19846 :                 if (parent_rel->reloptkind == RELOPT_BASEREL)
    2285             :                 {
    2286             :                     /* Simple single-level transformation */
    2287       15758 :                     child_expr = (Expr *)
    2288             :                         adjust_appendrel_attrs(root,
    2289       15758 :                                                (Node *) cur_em->em_expr,
    2290             :                                                1, &appinfo);
    2291             :                 }
    2292             :                 else
    2293             :                 {
    2294             :                     /* Must do multi-level transformation */
    2295        4088 :                     child_expr = (Expr *)
    2296        4088 :                         adjust_appendrel_attrs_multilevel(root,
    2297        4088 :                                                           (Node *) cur_em->em_expr,
    2298             :                                                           child_rel->relids,
    2299             :                                                           child_rel->top_parent_relids);
    2300             :                 }
    2301             : 
    2302             :                 /*
    2303             :                  * Transform em_relids to match.  Note we do *not* do
    2304             :                  * pull_varnos(child_expr) here, as for example the
    2305             :                  * transformation might have substituted a constant, but we
    2306             :                  * don't want the child member to be marked as constant.
    2307             :                  */
    2308       19846 :                 new_relids = bms_difference(cur_em->em_relids,
    2309       19846 :                                             child_rel->top_parent_relids);
    2310       19846 :                 new_relids = bms_add_members(new_relids, child_rel->relids);
    2311             : 
    2312             :                 /*
    2313             :                  * And likewise for nullable_relids.  Note this code assumes
    2314             :                  * parent and child relids are singletons.
    2315             :                  */
    2316       19846 :                 new_nullable_relids = cur_em->em_nullable_relids;
    2317       19846 :                 if (bms_overlap(new_nullable_relids,
    2318       19846 :                                 child_rel->top_parent_relids))
    2319             :                 {
    2320          96 :                     new_nullable_relids = bms_difference(new_nullable_relids,
    2321          96 :                                                          child_rel->top_parent_relids);
    2322          96 :                     new_nullable_relids = bms_add_members(new_nullable_relids,
    2323          96 :                                                           child_rel->relids);
    2324             :                 }
    2325             : 
    2326       19846 :                 (void) add_eq_member(cur_ec, child_expr,
    2327             :                                      new_relids, new_nullable_relids,
    2328             :                                      true, cur_em->em_datatype);
    2329             : 
    2330             :                 /* Record this EC index for the child rel */
    2331       19846 :                 child_rel->eclass_indexes = bms_add_member(child_rel->eclass_indexes, i);
    2332             :             }
    2333             :         }
    2334             :     }
    2335       11768 : }
    2336             : 
    2337             : 
    2338             : /*
    2339             :  * generate_implied_equalities_for_column
    2340             :  *    Create EC-derived joinclauses usable with a specific column.
    2341             :  *
    2342             :  * This is used by indxpath.c to extract potentially indexable joinclauses
    2343             :  * from ECs, and can be used by foreign data wrappers for similar purposes.
    2344             :  * We assume that only expressions in Vars of a single table are of interest,
    2345             :  * but the caller provides a callback function to identify exactly which
    2346             :  * such expressions it would like to know about.
    2347             :  *
    2348             :  * We assume that any given table/index column could appear in only one EC.
    2349             :  * (This should be true in all but the most pathological cases, and if it
    2350             :  * isn't, we stop on the first match anyway.)  Therefore, what we return
    2351             :  * is a redundant list of clauses equating the table/index column to each of
    2352             :  * the other-relation values it is known to be equal to.  Any one of
    2353             :  * these clauses can be used to create a parameterized path, and there
    2354             :  * is no value in using more than one.  (But it *is* worthwhile to create
    2355             :  * a separate parameterized path for each one, since that leads to different
    2356             :  * join orders.)
    2357             :  *
    2358             :  * The caller can pass a Relids set of rels we aren't interested in joining
    2359             :  * to, so as to save the work of creating useless clauses.
    2360             :  */
    2361             : List *
    2362      190116 : generate_implied_equalities_for_column(PlannerInfo *root,
    2363             :                                        RelOptInfo *rel,
    2364             :                                        ec_matches_callback_type callback,
    2365             :                                        void *callback_arg,
    2366             :                                        Relids prohibited_rels)
    2367             : {
    2368      190116 :     List       *result = NIL;
    2369      190116 :     bool        is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
    2370             :     Relids      parent_relids;
    2371             :     int         i;
    2372             : 
    2373             :     /* Should be OK to rely on eclass_indexes */
    2374             :     Assert(root->ec_merging_done);
    2375             : 
    2376             :     /* Indexes are available only on base or "other" member relations. */
    2377             :     Assert(IS_SIMPLE_REL(rel));
    2378             : 
    2379             :     /* If it's a child rel, we'll need to know what its parent(s) are */
    2380      190116 :     if (is_child_rel)
    2381        5032 :         parent_relids = find_childrel_parents(root, rel);
    2382             :     else
    2383      185084 :         parent_relids = NULL;   /* not used, but keep compiler quiet */
    2384             : 
    2385      190116 :     i = -1;
    2386      677154 :     while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
    2387             :     {
    2388      333684 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2389             :         EquivalenceMember *cur_em;
    2390             :         ListCell   *lc2;
    2391             : 
    2392             :         /* Sanity check eclass_indexes only contain ECs for rel */
    2393             :         Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
    2394             : 
    2395             :         /*
    2396             :          * Won't generate joinclauses if const or single-member (the latter
    2397             :          * test covers the volatile case too)
    2398             :          */
    2399      333684 :         if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
    2400      157892 :             continue;
    2401             : 
    2402             :         /*
    2403             :          * Scan members, looking for a match to the target column.  Note that
    2404             :          * child EC members are considered, but only when they belong to the
    2405             :          * target relation.  (Unlike regular members, the same expression
    2406             :          * could be a child member of more than one EC.  Therefore, it's
    2407             :          * potentially order-dependent which EC a child relation's target
    2408             :          * column gets matched to.  This is annoying but it only happens in
    2409             :          * corner cases, so for now we live with just reporting the first
    2410             :          * match.  See also get_eclass_for_sort_expr.)
    2411             :          */
    2412      175792 :         cur_em = NULL;
    2413      514080 :         foreach(lc2, cur_ec->ec_members)
    2414             :         {
    2415      375094 :             cur_em = (EquivalenceMember *) lfirst(lc2);
    2416      550866 :             if (bms_equal(cur_em->em_relids, rel->relids) &&
    2417      175772 :                 callback(root, rel, cur_ec, cur_em, callback_arg))
    2418       36806 :                 break;
    2419      338288 :             cur_em = NULL;
    2420             :         }
    2421             : 
    2422      175792 :         if (!cur_em)
    2423      138986 :             continue;
    2424             : 
    2425             :         /*
    2426             :          * Found our match.  Scan the other EC members and attempt to generate
    2427             :          * joinclauses.
    2428             :          */
    2429      121524 :         foreach(lc2, cur_ec->ec_members)
    2430             :         {
    2431       84718 :             EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
    2432             :             Oid         eq_op;
    2433             :             RestrictInfo *rinfo;
    2434             : 
    2435       84718 :             if (other_em->em_is_child)
    2436        9632 :                 continue;       /* ignore children here */
    2437             : 
    2438             :             /* Make sure it'll be a join to a different rel */
    2439      114682 :             if (other_em == cur_em ||
    2440       39596 :                 bms_overlap(other_em->em_relids, rel->relids))
    2441       35530 :                 continue;
    2442             : 
    2443             :             /* Forget it if caller doesn't want joins to this rel */
    2444       39556 :             if (bms_overlap(other_em->em_relids, prohibited_rels))
    2445           4 :                 continue;
    2446             : 
    2447             :             /*
    2448             :              * Also, if this is a child rel, avoid generating a useless join
    2449             :              * to its parent rel(s).
    2450             :              */
    2451       42552 :             if (is_child_rel &&
    2452        3000 :                 bms_overlap(parent_relids, other_em->em_relids))
    2453        1324 :                 continue;
    2454             : 
    2455       38228 :             eq_op = select_equality_operator(cur_ec,
    2456             :                                              cur_em->em_datatype,
    2457             :                                              other_em->em_datatype);
    2458       38228 :             if (!OidIsValid(eq_op))
    2459           0 :                 continue;
    2460             : 
    2461             :             /* set parent_ec to mark as redundant with other joinclauses */
    2462       38228 :             rinfo = create_join_clause(root, cur_ec, eq_op,
    2463             :                                        cur_em, other_em,
    2464             :                                        cur_ec);
    2465             : 
    2466       38228 :             result = lappend(result, rinfo);
    2467             :         }
    2468             : 
    2469             :         /*
    2470             :          * If somehow we failed to create any join clauses, we might as well
    2471             :          * keep scanning the ECs for another match.  But if we did make any,
    2472             :          * we're done, because we don't want to return non-redundant clauses.
    2473             :          */
    2474       36806 :         if (result)
    2475       36762 :             break;
    2476             :     }
    2477             : 
    2478      190116 :     return result;
    2479             : }
    2480             : 
    2481             : /*
    2482             :  * have_relevant_eclass_joinclause
    2483             :  *      Detect whether there is an EquivalenceClass that could produce
    2484             :  *      a joinclause involving the two given relations.
    2485             :  *
    2486             :  * This is essentially a very cut-down version of
    2487             :  * generate_join_implied_equalities().  Note it's OK to occasionally say "yes"
    2488             :  * incorrectly.  Hence we don't bother with details like whether the lack of a
    2489             :  * cross-type operator might prevent the clause from actually being generated.
    2490             :  */
    2491             : bool
    2492       65786 : have_relevant_eclass_joinclause(PlannerInfo *root,
    2493             :                                 RelOptInfo *rel1, RelOptInfo *rel2)
    2494             : {
    2495             :     Bitmapset  *matching_ecs;
    2496             :     int         i;
    2497             : 
    2498             :     /* Examine only eclasses mentioning both rel1 and rel2 */
    2499       65786 :     matching_ecs = get_common_eclass_indexes(root, rel1->relids,
    2500             :                                              rel2->relids);
    2501             : 
    2502       65786 :     i = -1;
    2503      131572 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2504             :     {
    2505       54626 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2506             :                                                              i);
    2507             : 
    2508             :         /*
    2509             :          * Sanity check that get_common_eclass_indexes gave only ECs
    2510             :          * containing both rels.
    2511             :          */
    2512             :         Assert(bms_overlap(rel1->relids, ec->ec_relids));
    2513             :         Assert(bms_overlap(rel2->relids, ec->ec_relids));
    2514             : 
    2515             :         /*
    2516             :          * Won't generate joinclauses if single-member (this test covers the
    2517             :          * volatile case too)
    2518             :          */
    2519       54626 :         if (list_length(ec->ec_members) <= 1)
    2520           0 :             continue;
    2521             : 
    2522             :         /*
    2523             :          * We do not need to examine the individual members of the EC, because
    2524             :          * all that we care about is whether each rel overlaps the relids of
    2525             :          * at least one member, and get_common_eclass_indexes() and the single
    2526             :          * member check above are sufficient to prove that.  (As with
    2527             :          * have_relevant_joinclause(), it is not necessary that the EC be able
    2528             :          * to form a joinclause relating exactly the two given rels, only that
    2529             :          * it be able to form a joinclause mentioning both, and this will
    2530             :          * surely be true if both of them overlap ec_relids.)
    2531             :          *
    2532             :          * Note we don't test ec_broken; if we did, we'd need a separate code
    2533             :          * path to look through ec_sources.  Checking the membership anyway is
    2534             :          * OK as a possibly-overoptimistic heuristic.
    2535             :          *
    2536             :          * We don't test ec_has_const either, even though a const eclass won't
    2537             :          * generate real join clauses.  This is because if we had "WHERE a.x =
    2538             :          * b.y and a.x = 42", it is worth considering a join between a and b,
    2539             :          * since the join result is likely to be small even though it'll end
    2540             :          * up being an unqualified nestloop.
    2541             :          */
    2542             : 
    2543       54626 :         return true;
    2544             :     }
    2545             : 
    2546       11160 :     return false;
    2547             : }
    2548             : 
    2549             : 
    2550             : /*
    2551             :  * has_relevant_eclass_joinclause
    2552             :  *      Detect whether there is an EquivalenceClass that could produce
    2553             :  *      a joinclause involving the given relation and anything else.
    2554             :  *
    2555             :  * This is the same as have_relevant_eclass_joinclause with the other rel
    2556             :  * implicitly defined as "everything else in the query".
    2557             :  */
    2558             : bool
    2559       93172 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
    2560             : {
    2561             :     Bitmapset  *matched_ecs;
    2562             :     int         i;
    2563             : 
    2564             :     /* Examine only eclasses mentioning rel1 */
    2565       93172 :     matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
    2566             : 
    2567       93172 :     i = -1;
    2568      403774 :     while ((i = bms_next_member(matched_ecs, i)) >= 0)
    2569             :     {
    2570      249358 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2571             :                                                              i);
    2572             : 
    2573             :         /*
    2574             :          * Won't generate joinclauses if single-member (this test covers the
    2575             :          * volatile case too)
    2576             :          */
    2577      249358 :         if (list_length(ec->ec_members) <= 1)
    2578      114100 :             continue;
    2579             : 
    2580             :         /*
    2581             :          * Per the comment in have_relevant_eclass_joinclause, it's sufficient
    2582             :          * to find an EC that mentions both this rel and some other rel.
    2583             :          */
    2584      135258 :         if (!bms_is_subset(ec->ec_relids, rel1->relids))
    2585       31928 :             return true;
    2586             :     }
    2587             : 
    2588       61244 :     return false;
    2589             : }
    2590             : 
    2591             : 
    2592             : /*
    2593             :  * eclass_useful_for_merging
    2594             :  *    Detect whether the EC could produce any mergejoinable join clauses
    2595             :  *    against the specified relation.
    2596             :  *
    2597             :  * This is just a heuristic test and doesn't have to be exact; it's better
    2598             :  * to say "yes" incorrectly than "no".  Hence we don't bother with details
    2599             :  * like whether the lack of a cross-type operator might prevent the clause
    2600             :  * from actually being generated.
    2601             :  */
    2602             : bool
    2603      271382 : eclass_useful_for_merging(PlannerInfo *root,
    2604             :                           EquivalenceClass *eclass,
    2605             :                           RelOptInfo *rel)
    2606             : {
    2607             :     Relids      relids;
    2608             :     ListCell   *lc;
    2609             : 
    2610             :     Assert(!eclass->ec_merged);
    2611             : 
    2612             :     /*
    2613             :      * Won't generate joinclauses if const or single-member (the latter test
    2614             :      * covers the volatile case too)
    2615             :      */
    2616      271382 :     if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
    2617       30564 :         return false;
    2618             : 
    2619             :     /*
    2620             :      * Note we don't test ec_broken; if we did, we'd need a separate code path
    2621             :      * to look through ec_sources.  Checking the members anyway is OK as a
    2622             :      * possibly-overoptimistic heuristic.
    2623             :      */
    2624             : 
    2625             :     /* If specified rel is a child, we must consider the topmost parent rel */
    2626      240818 :     if (IS_OTHER_REL(rel))
    2627             :     {
    2628             :         Assert(!bms_is_empty(rel->top_parent_relids));
    2629        5412 :         relids = rel->top_parent_relids;
    2630             :     }
    2631             :     else
    2632      235406 :         relids = rel->relids;
    2633             : 
    2634             :     /* If rel already includes all members of eclass, no point in searching */
    2635      240818 :     if (bms_is_subset(eclass->ec_relids, relids))
    2636       95970 :         return false;
    2637             : 
    2638             :     /* To join, we need a member not in the given rel */
    2639      213148 :     foreach(lc, eclass->ec_members)
    2640             :     {
    2641      212860 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    2642             : 
    2643      212860 :         if (cur_em->em_is_child)
    2644           0 :             continue;           /* ignore children here */
    2645             : 
    2646      212860 :         if (!bms_overlap(cur_em->em_relids, relids))
    2647      144560 :             return true;
    2648             :     }
    2649             : 
    2650         288 :     return false;
    2651             : }
    2652             : 
    2653             : 
    2654             : /*
    2655             :  * is_redundant_derived_clause
    2656             :  *      Test whether rinfo is derived from same EC as any clause in clauselist;
    2657             :  *      if so, it can be presumed to represent a condition that's redundant
    2658             :  *      with that member of the list.
    2659             :  */
    2660             : bool
    2661          56 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
    2662             : {
    2663          56 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    2664             :     ListCell   *lc;
    2665             : 
    2666             :     /* Fail if it's not a potentially-redundant clause from some EC */
    2667          56 :     if (parent_ec == NULL)
    2668          48 :         return false;
    2669             : 
    2670           8 :     foreach(lc, clauselist)
    2671             :     {
    2672           8 :         RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
    2673             : 
    2674           8 :         if (otherrinfo->parent_ec == parent_ec)
    2675           8 :             return true;
    2676             :     }
    2677             : 
    2678           0 :     return false;
    2679             : }
    2680             : 
    2681             : /*
    2682             :  * is_redundant_with_indexclauses
    2683             :  *      Test whether rinfo is redundant with any clause in the IndexClause
    2684             :  *      list.  Here, for convenience, we test both simple identity and
    2685             :  *      whether it is derived from the same EC as any member of the list.
    2686             :  */
    2687             : bool
    2688      636510 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
    2689             : {
    2690      636510 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    2691             :     ListCell   *lc;
    2692             : 
    2693      858048 :     foreach(lc, indexclauses)
    2694             :     {
    2695      687734 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    2696      687734 :         RestrictInfo *otherrinfo = iclause->rinfo;
    2697             : 
    2698             :         /* If indexclause is lossy, it won't enforce the condition exactly */
    2699      687734 :         if (iclause->lossy)
    2700       14546 :             continue;
    2701             : 
    2702             :         /* Match if it's same clause (pointer equality should be enough) */
    2703      673188 :         if (rinfo == otherrinfo)
    2704      829154 :             return true;
    2705             :         /* Match if derived from same EC */
    2706      310230 :         if (parent_ec && otherrinfo->parent_ec == parent_ec)
    2707      103238 :             return true;
    2708             : 
    2709             :         /*
    2710             :          * No need to look at the derived clauses in iclause->indexquals; they
    2711             :          * couldn't match if the parent clause didn't.
    2712             :          */
    2713             :     }
    2714             : 
    2715      170314 :     return false;
    2716             : }
    2717             : 
    2718             : /*
    2719             :  * get_eclass_indexes_for_relids
    2720             :  *      Build and return a Bitmapset containing the indexes into root's
    2721             :  *      eq_classes list for all eclasses that mention any of these relids
    2722             :  */
    2723             : static Bitmapset *
    2724      456302 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
    2725             : {
    2726      456302 :     Bitmapset  *ec_indexes = NULL;
    2727      456302 :     int         i = -1;
    2728             : 
    2729             :     /* Should be OK to rely on eclass_indexes */
    2730             :     Assert(root->ec_merging_done);
    2731             : 
    2732     1723108 :     while ((i = bms_next_member(relids, i)) > 0)
    2733             :     {
    2734      810504 :         RelOptInfo *rel = root->simple_rel_array[i];
    2735             : 
    2736      810504 :         ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
    2737             :     }
    2738      456302 :     return ec_indexes;
    2739             : }
    2740             : 
    2741             : /*
    2742             :  * get_common_eclass_indexes
    2743             :  *      Build and return a Bitmapset containing the indexes into root's
    2744             :  *      eq_classes list for all eclasses that mention rels in both
    2745             :  *      relids1 and relids2.
    2746             :  */
    2747             : static Bitmapset *
    2748      278406 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
    2749             : {
    2750             :     Bitmapset  *rel1ecs;
    2751             :     Bitmapset  *rel2ecs;
    2752             :     int         relid;
    2753             : 
    2754      278406 :     rel1ecs = get_eclass_indexes_for_relids(root, relids1);
    2755             : 
    2756             :     /*
    2757             :      * We can get away with just using the relation's eclass_indexes directly
    2758             :      * when relids2 is a singleton set.
    2759             :      */
    2760      278406 :     if (bms_get_singleton_member(relids2, &relid))
    2761      193682 :         rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
    2762             :     else
    2763       84724 :         rel2ecs = get_eclass_indexes_for_relids(root, relids2);
    2764             : 
    2765             :     /* Calculate and return the common EC indexes, recycling the left input. */
    2766      278406 :     return bms_int_members(rel1ecs, rel2ecs);
    2767             : }

Generated by: LCOV version 1.13