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

Generated by: LCOV version 1.13