LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - equivclass.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.6 % 1059 981
Test Date: 2026-08-30 15:16:44 Functions: 93.6 % 47 44
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 83.4 % 884 737

             Branch data     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-2026, 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 "common/hashfn.h"
      24                 :             : #include "nodes/makefuncs.h"
      25                 :             : #include "nodes/nodeFuncs.h"
      26                 :             : #include "optimizer/appendinfo.h"
      27                 :             : #include "optimizer/clauses.h"
      28                 :             : #include "optimizer/optimizer.h"
      29                 :             : #include "optimizer/pathnode.h"
      30                 :             : #include "optimizer/paths.h"
      31                 :             : #include "optimizer/planmain.h"
      32                 :             : #include "optimizer/restrictinfo.h"
      33                 :             : #include "rewrite/rewriteManip.h"
      34                 :             : #include "utils/lsyscache.h"
      35                 :             : 
      36                 :             : 
      37                 :             : static EquivalenceMember *make_eq_member(EquivalenceClass *ec,
      38                 :             :                                          Expr *expr, Relids relids,
      39                 :             :                                          JoinDomain *jdomain,
      40                 :             :                                          EquivalenceMember *parent,
      41                 :             :                                          Oid datatype);
      42                 :             : static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
      43                 :             :                                         Expr *expr, Relids relids,
      44                 :             :                                         JoinDomain *jdomain,
      45                 :             :                                         Oid datatype);
      46                 :             : static EquivalenceMember *add_child_eq_member(PlannerInfo *root,
      47                 :             :                                               EquivalenceClass *ec,
      48                 :             :                                               int ec_index, Expr *expr,
      49                 :             :                                               Relids relids,
      50                 :             :                                               JoinDomain *jdomain,
      51                 :             :                                               EquivalenceMember *parent_em,
      52                 :             :                                               Oid datatype,
      53                 :             :                                               Index child_relid);
      54                 :             : static void generate_base_implied_equalities_const(PlannerInfo *root,
      55                 :             :                                                    EquivalenceClass *ec);
      56                 :             : static void generate_base_implied_equalities_no_const(PlannerInfo *root,
      57                 :             :                                                       EquivalenceClass *ec);
      58                 :             : static void generate_base_implied_equalities_broken(PlannerInfo *root,
      59                 :             :                                                     EquivalenceClass *ec);
      60                 :             : static List *generate_join_implied_equalities_normal(PlannerInfo *root,
      61                 :             :                                                      EquivalenceClass *ec,
      62                 :             :                                                      Relids join_relids,
      63                 :             :                                                      Relids outer_relids,
      64                 :             :                                                      Relids inner_relids);
      65                 :             : static List *generate_join_implied_equalities_broken(PlannerInfo *root,
      66                 :             :                                                      EquivalenceClass *ec,
      67                 :             :                                                      Relids nominal_join_relids,
      68                 :             :                                                      Relids outer_relids,
      69                 :             :                                                      Relids nominal_inner_relids,
      70                 :             :                                                      RelOptInfo *inner_rel);
      71                 :             : static Oid  select_equality_operator(EquivalenceClass *ec,
      72                 :             :                                      Oid lefttype, Oid righttype);
      73                 :             : static RestrictInfo *create_join_clause(PlannerInfo *root,
      74                 :             :                                         EquivalenceClass *ec, Oid opno,
      75                 :             :                                         EquivalenceMember *leftem,
      76                 :             :                                         EquivalenceMember *rightem,
      77                 :             :                                         EquivalenceClass *parent_ec);
      78                 :             : static bool reconsider_outer_join_clause(PlannerInfo *root,
      79                 :             :                                          OuterJoinClauseInfo *ojcinfo,
      80                 :             :                                          bool outer_on_left);
      81                 :             : static bool reconsider_full_join_clause(PlannerInfo *root,
      82                 :             :                                         OuterJoinClauseInfo *ojcinfo);
      83                 :             : static JoinDomain *find_join_domain(PlannerInfo *root, Relids relids);
      84                 :             : static Bitmapset *get_eclass_indexes_for_relids(PlannerInfo *root,
      85                 :             :                                                 Relids relids);
      86                 :             : static Bitmapset *get_common_eclass_indexes(PlannerInfo *root, Relids relids1,
      87                 :             :                                             Relids relids2);
      88                 :             : static void ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec);
      89                 :             : static void ec_add_derived_clauses(EquivalenceClass *ec, List *clauses);
      90                 :             : static void ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause);
      91                 :             : static void ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo);
      92                 :             : static void ec_clear_derived_clauses(EquivalenceClass *ec);
      93                 :             : static RestrictInfo *ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
      94                 :             :                                               EquivalenceMember *leftem,
      95                 :             :                                               EquivalenceMember *rightem,
      96                 :             :                                               EquivalenceClass *parent_ec);
      97                 :             : static RestrictInfo *ec_search_derived_clause_for_ems(PlannerInfo *root,
      98                 :             :                                                       EquivalenceClass *ec,
      99                 :             :                                                       EquivalenceMember *leftem,
     100                 :             :                                                       EquivalenceMember *rightem,
     101                 :             :                                                       EquivalenceClass *parent_ec);
     102                 :             : 
     103                 :             : /*
     104                 :             :  * Hash key identifying a derived clause.
     105                 :             :  *
     106                 :             :  * This structure should not be filled manually. Use fill_ec_derives_key() to
     107                 :             :  * set it up in canonical form.
     108                 :             :  */
     109                 :             : typedef struct
     110                 :             : {
     111                 :             :     EquivalenceMember *em1;
     112                 :             :     EquivalenceMember *em2;
     113                 :             :     EquivalenceClass *parent_ec;
     114                 :             : } ECDerivesKey;
     115                 :             : 
     116                 :             : /* Hash table entry in ec_derives_hash. */
     117                 :             : typedef struct
     118                 :             : {
     119                 :             :     uint32      status;
     120                 :             :     ECDerivesKey key;
     121                 :             :     RestrictInfo *rinfo;
     122                 :             : } ECDerivesEntry;
     123                 :             : 
     124                 :             : /* Threshold for switching from list to hash table */
     125                 :             : #define EC_DERIVES_HASH_THRESHOLD 32
     126                 :             : 
     127                 :             : #define SH_PREFIX               derives
     128                 :             : #define SH_ELEMENT_TYPE         ECDerivesEntry
     129                 :             : #define SH_KEY_TYPE             ECDerivesKey
     130                 :             : #define SH_KEY                  key
     131                 :             : #define SH_HASH_KEY(tb, key)    \
     132                 :             :     hash_bytes((const unsigned char *) &(key), sizeof(ECDerivesKey))
     133                 :             : #define SH_EQUAL(tb, a, b)      \
     134                 :             :     ((a).em1 == (b).em1 && (a).em2 == (b).em2 && (a).parent_ec == (b).parent_ec)
     135                 :             : #define SH_SCOPE                static inline
     136                 :             : #define SH_DECLARE
     137                 :             : #define SH_DEFINE
     138                 :             : #include "lib/simplehash.h"
     139                 :             : 
     140                 :             : /*
     141                 :             :  * process_equivalence
     142                 :             :  *    The given clause has a mergejoinable operator and is not an outer-join
     143                 :             :  *    qualification, so its two sides can be considered equal
     144                 :             :  *    anywhere they are both computable; moreover that equality can be
     145                 :             :  *    extended transitively.  Record this knowledge in the EquivalenceClass
     146                 :             :  *    data structure, if applicable.  Returns true if successful, false if not
     147                 :             :  *    (in which case caller should treat the clause as ordinary, not an
     148                 :             :  *    equivalence).
     149                 :             :  *
     150                 :             :  * In some cases, although we cannot convert a clause into EquivalenceClass
     151                 :             :  * knowledge, we can still modify it to a more useful form than the original.
     152                 :             :  * Then, *p_restrictinfo will be replaced by a new RestrictInfo, which is what
     153                 :             :  * the caller should use for further processing.
     154                 :             :  *
     155                 :             :  * jdomain is the join domain within which the given clause was found.
     156                 :             :  * This limits the applicability of deductions from the EquivalenceClass,
     157                 :             :  * as described in optimizer/README.
     158                 :             :  *
     159                 :             :  * We reject proposed equivalence clauses if they contain leaky functions
     160                 :             :  * and have security_level above zero.  The EC evaluation rules require us to
     161                 :             :  * apply certain tests at certain joining levels, and we can't tolerate
     162                 :             :  * delaying any test on security_level grounds.  By rejecting candidate clauses
     163                 :             :  * that might require security delays, we ensure it's safe to apply an EC
     164                 :             :  * clause as soon as it's supposed to be applied.
     165                 :             :  *
     166                 :             :  * On success return, we have also initialized the clause's left_ec/right_ec
     167                 :             :  * fields to point to the EquivalenceClass representing it.  This saves lookup
     168                 :             :  * effort later.
     169                 :             :  *
     170                 :             :  * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
     171                 :             :  * problem, for which there exist better data structures than simple lists.
     172                 :             :  * If this code ever proves to be a bottleneck then it could be sped up ---
     173                 :             :  * but for now, simple is beautiful.
     174                 :             :  *
     175                 :             :  * Note: this is only called during planner startup, not during GEQO
     176                 :             :  * exploration, so we need not worry about whether we're in the right
     177                 :             :  * memory context.
     178                 :             :  */
     179                 :             : bool
     180                 :      246618 : process_equivalence(PlannerInfo *root,
     181                 :             :                     RestrictInfo **p_restrictinfo,
     182                 :             :                     JoinDomain *jdomain)
     183                 :             : {
     184                 :      246618 :     RestrictInfo *restrictinfo = *p_restrictinfo;
     185                 :      246618 :     Expr       *clause = restrictinfo->clause;
     186                 :             :     Oid         opno,
     187                 :             :                 collation,
     188                 :             :                 item1_type,
     189                 :             :                 item2_type;
     190                 :             :     Expr       *item1;
     191                 :             :     Expr       *item2;
     192                 :             :     Relids      item1_relids,
     193                 :             :                 item2_relids;
     194                 :             :     List       *opfamilies;
     195                 :             :     EquivalenceClass *ec1,
     196                 :             :                *ec2;
     197                 :             :     EquivalenceMember *em1,
     198                 :             :                *em2;
     199                 :             :     ListCell   *lc1;
     200                 :             :     int         ec2_idx;
     201                 :             : 
     202                 :             :     /* Should not already be marked as having generated an eclass */
     203                 :             :     Assert(restrictinfo->left_ec == NULL);
     204                 :             :     Assert(restrictinfo->right_ec == NULL);
     205                 :             : 
     206                 :             :     /* Reject if it is potentially postponable by security considerations */
     207   [ +  +  +  + ]:      246618 :     if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
     208                 :         172 :         return false;
     209                 :             : 
     210                 :             :     /* Extract info from given clause */
     211                 :             :     Assert(is_opclause(clause));
     212                 :      246446 :     opno = ((OpExpr *) clause)->opno;
     213                 :      246446 :     collation = ((OpExpr *) clause)->inputcollid;
     214                 :      246446 :     item1 = (Expr *) get_leftop(clause);
     215                 :      246446 :     item2 = (Expr *) get_rightop(clause);
     216                 :      246446 :     item1_relids = restrictinfo->left_relids;
     217                 :      246446 :     item2_relids = restrictinfo->right_relids;
     218                 :             : 
     219                 :             :     /*
     220                 :             :      * Ensure both input expressions expose the desired collation (their types
     221                 :             :      * should be OK already); see comments for canonicalize_ec_expression.
     222                 :             :      */
     223                 :      246446 :     item1 = canonicalize_ec_expression(item1,
     224                 :             :                                        exprType((Node *) item1),
     225                 :             :                                        collation);
     226                 :      246446 :     item2 = canonicalize_ec_expression(item2,
     227                 :             :                                        exprType((Node *) item2),
     228                 :             :                                        collation);
     229                 :             : 
     230                 :             :     /*
     231                 :             :      * Clauses of the form X=X cannot be translated into EquivalenceClasses.
     232                 :             :      * We'd either end up with a single-entry EC, losing the knowledge that
     233                 :             :      * the clause was present at all, or else make an EC with duplicate
     234                 :             :      * entries, causing other issues.
     235                 :             :      */
     236         [ +  + ]:      246446 :     if (equal(item1, item2))
     237                 :             :     {
     238                 :             :         /*
     239                 :             :          * If the operator is strict, then the clause can be treated as just
     240                 :             :          * "X IS NOT NULL".  (Since we know we are considering a top-level
     241                 :             :          * qual, we can ignore the difference between FALSE and NULL results.)
     242                 :             :          * It's worth making the conversion because we'll typically get a much
     243                 :             :          * better selectivity estimate than we would for X=X.
     244                 :             :          *
     245                 :             :          * If the operator is not strict, we can't be sure what it will do
     246                 :             :          * with NULLs, so don't attempt to optimize it.
     247                 :             :          */
     248                 :          45 :         set_opfuncid((OpExpr *) clause);
     249         [ +  - ]:          45 :         if (func_strict(((OpExpr *) clause)->opfuncid))
     250                 :             :         {
     251                 :          45 :             NullTest   *ntest = makeNode(NullTest);
     252                 :             : 
     253                 :          45 :             ntest->arg = item1;
     254                 :          45 :             ntest->nulltesttype = IS_NOT_NULL;
     255                 :          45 :             ntest->argisrow = false; /* correct even if composite arg */
     256                 :          45 :             ntest->location = -1;
     257                 :             : 
     258                 :          45 :             *p_restrictinfo =
     259                 :          45 :                 make_restrictinfo(root,
     260                 :             :                                   (Expr *) ntest,
     261                 :          45 :                                   restrictinfo->is_pushed_down,
     262                 :          45 :                                   restrictinfo->has_clone,
     263                 :          45 :                                   restrictinfo->is_clone,
     264                 :          45 :                                   restrictinfo->pseudoconstant,
     265                 :             :                                   restrictinfo->security_level,
     266                 :             :                                   NULL,
     267                 :             :                                   restrictinfo->incompatible_relids,
     268                 :             :                                   restrictinfo->outer_relids);
     269                 :             :         }
     270                 :          45 :         return false;
     271                 :             :     }
     272                 :             : 
     273                 :             :     /*
     274                 :             :      * We use the declared input types of the operator, not exprType() of the
     275                 :             :      * inputs, as the nominal datatypes for opfamily lookup.  This presumes
     276                 :             :      * that btree operators are always registered with amoplefttype and
     277                 :             :      * amoprighttype equal to their declared input types.  We will need this
     278                 :             :      * info anyway to build EquivalenceMember nodes, and by extracting it now
     279                 :             :      * we can use type comparisons to short-circuit some equal() tests.
     280                 :             :      */
     281                 :      246401 :     op_input_types(opno, &item1_type, &item2_type);
     282                 :             : 
     283                 :      246401 :     opfamilies = restrictinfo->mergeopfamilies;
     284                 :             : 
     285                 :             :     /*
     286                 :             :      * Sweep through the existing EquivalenceClasses looking for matches to
     287                 :             :      * item1 and item2.  These are the possible outcomes:
     288                 :             :      *
     289                 :             :      * 1. We find both in the same EC.  The equivalence is already known, so
     290                 :             :      * there's nothing to do.
     291                 :             :      *
     292                 :             :      * 2. We find both in different ECs.  Merge the two ECs together.
     293                 :             :      *
     294                 :             :      * 3. We find just one.  Add the other to its EC.
     295                 :             :      *
     296                 :             :      * 4. We find neither.  Make a new, two-entry EC.
     297                 :             :      *
     298                 :             :      * Note: since all ECs are built through this process or the similar
     299                 :             :      * search in get_eclass_for_sort_expr(), it's impossible that we'd match
     300                 :             :      * an item in more than one existing nonvolatile EC.  So it's okay to stop
     301                 :             :      * at the first match.
     302                 :             :      */
     303                 :      246401 :     ec1 = ec2 = NULL;
     304                 :      246401 :     em1 = em2 = NULL;
     305                 :      246401 :     ec2_idx = -1;
     306   [ +  +  +  +  :      425792 :     foreach(lc1, root->eq_classes)
                   +  + ]
     307                 :             :     {
     308                 :      179494 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     309                 :             :         ListCell   *lc2;
     310                 :             : 
     311                 :             :         /* Never match to a volatile EC */
     312         [ -  + ]:      179494 :         if (cur_ec->ec_has_volatile)
     313                 :           0 :             continue;
     314                 :             : 
     315                 :             :         /*
     316                 :             :          * The collation has to match; check this first since it's cheaper
     317                 :             :          * than the opfamily comparison.
     318                 :             :          */
     319         [ +  + ]:      179494 :         if (collation != cur_ec->ec_collation)
     320                 :       18507 :             continue;
     321                 :             : 
     322                 :             :         /*
     323                 :             :          * A "match" requires matching sets of btree opfamilies.  Use of
     324                 :             :          * equal() for this test has implications discussed in the comments
     325                 :             :          * for get_mergejoin_opfamilies().
     326                 :             :          */
     327         [ +  + ]:      160987 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     328                 :       42514 :             continue;
     329                 :             : 
     330                 :             :         /* We don't expect any children yet */
     331                 :             :         Assert(cur_ec->ec_childmembers == NULL);
     332                 :             : 
     333   [ +  -  +  +  :      353366 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
     334                 :             :         {
     335                 :      234996 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
     336                 :             : 
     337                 :             :             /* Child members should not exist in ec_members */
     338                 :             :             Assert(!cur_em->em_is_child);
     339                 :             : 
     340                 :             :             /*
     341                 :             :              * Match constants only within the same JoinDomain (see
     342                 :             :              * optimizer/README).
     343                 :             :              */
     344   [ +  +  +  + ]:      234996 :             if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
     345                 :        3013 :                 continue;
     346                 :             : 
     347         [ +  + ]:      231983 :             if (!ec1 &&
     348   [ +  +  +  + ]:      443784 :                 item1_type == cur_em->em_datatype &&
     349                 :      221739 :                 equal(item1, cur_em->em_expr))
     350                 :             :             {
     351                 :       13921 :                 ec1 = cur_ec;
     352                 :       13921 :                 em1 = cur_em;
     353         [ +  + ]:       13921 :                 if (ec2)
     354                 :          60 :                     break;
     355                 :             :             }
     356                 :             : 
     357         [ +  + ]:      231923 :             if (!ec2 &&
     358   [ +  +  +  + ]:      459413 :                 item2_type == cur_em->em_datatype &&
     359                 :      229401 :                 equal(item2, cur_em->em_expr))
     360                 :             :             {
     361                 :        2979 :                 ec2 = cur_ec;
     362                 :        2979 :                 ec2_idx = foreach_current_index(lc1);
     363                 :        2979 :                 em2 = cur_em;
     364         [ +  + ]:        2979 :                 if (ec1)
     365                 :          43 :                     break;
     366                 :             :             }
     367                 :             :         }
     368                 :             : 
     369   [ +  +  +  + ]:      118473 :         if (ec1 && ec2)
     370                 :         103 :             break;
     371                 :             :     }
     372                 :             : 
     373                 :             :     /* Sweep finished, what did we find? */
     374                 :             : 
     375   [ +  +  +  + ]:      246401 :     if (ec1 && ec2)
     376                 :             :     {
     377                 :             :         /* If case 1, nothing to do, except add to sources */
     378         [ +  + ]:         103 :         if (ec1 == ec2)
     379                 :             :         {
     380                 :          70 :             ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     381                 :          70 :             ec1->ec_min_security = Min(ec1->ec_min_security,
     382                 :             :                                        restrictinfo->security_level);
     383                 :          70 :             ec1->ec_max_security = Max(ec1->ec_max_security,
     384                 :             :                                        restrictinfo->security_level);
     385                 :             :             /* mark the RI as associated with this eclass */
     386                 :          70 :             restrictinfo->left_ec = ec1;
     387                 :          70 :             restrictinfo->right_ec = ec1;
     388                 :             :             /* mark the RI as usable with this pair of EMs */
     389                 :          70 :             restrictinfo->left_em = em1;
     390                 :          70 :             restrictinfo->right_em = em2;
     391                 :          70 :             return true;
     392                 :             :         }
     393                 :             : 
     394                 :             :         /*
     395                 :             :          * Case 2: need to merge ec1 and ec2.  This should never happen after
     396                 :             :          * the ECs have reached canonical state; otherwise, pathkeys could be
     397                 :             :          * rendered non-canonical by the merge, and relation eclass indexes
     398                 :             :          * would get broken by removal of an eq_classes list entry.
     399                 :             :          */
     400         [ -  + ]:          33 :         if (root->ec_merging_done)
     401         [ #  # ]:           0 :             elog(ERROR, "too late to merge equivalence classes");
     402                 :             : 
     403                 :             :         /*
     404                 :             :          * We add ec2's items to ec1, then set ec2's ec_merged link to point
     405                 :             :          * to ec1 and remove ec2 from the eq_classes list.  We cannot simply
     406                 :             :          * delete ec2 because that could leave dangling pointers in existing
     407                 :             :          * PathKeys.  We leave it behind with a link so that the merged EC can
     408                 :             :          * be found.
     409                 :             :          */
     410                 :          33 :         ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
     411                 :          33 :         ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
     412                 :             : 
     413                 :             :         /*
     414                 :             :          * Appends ec2's derived clauses to ec1->ec_derives_list and adds them
     415                 :             :          * to ec1->ec_derives_hash if present.
     416                 :             :          */
     417                 :          33 :         ec_add_derived_clauses(ec1, ec2->ec_derives_list);
     418                 :          33 :         ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
     419                 :          33 :         ec1->ec_has_const |= ec2->ec_has_const;
     420                 :             :         /* can't need to set has_volatile */
     421                 :          33 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     422                 :             :                                    ec2->ec_min_security);
     423                 :          33 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     424                 :             :                                    ec2->ec_max_security);
     425                 :          33 :         ec2->ec_merged = ec1;
     426                 :          33 :         root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
     427                 :             :         /* just to avoid debugging confusion w/ dangling pointers: */
     428                 :          33 :         ec2->ec_members = NIL;
     429                 :          33 :         ec2->ec_sources = NIL;
     430                 :          33 :         ec_clear_derived_clauses(ec2);
     431                 :          33 :         ec2->ec_relids = NULL;
     432                 :          33 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     433                 :          33 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     434                 :             :                                    restrictinfo->security_level);
     435                 :          33 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     436                 :             :                                    restrictinfo->security_level);
     437                 :             :         /* mark the RI as associated with this eclass */
     438                 :          33 :         restrictinfo->left_ec = ec1;
     439                 :          33 :         restrictinfo->right_ec = ec1;
     440                 :             :         /* mark the RI as usable with this pair of EMs */
     441                 :          33 :         restrictinfo->left_em = em1;
     442                 :          33 :         restrictinfo->right_em = em2;
     443                 :             :     }
     444         [ +  + ]:      246298 :     else if (ec1)
     445                 :             :     {
     446                 :             :         /* Case 3: add item2 to ec1 */
     447                 :       13818 :         em2 = add_eq_member(ec1, item2, item2_relids,
     448                 :             :                             jdomain, item2_type);
     449                 :       13818 :         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
     450                 :       13818 :         ec1->ec_min_security = Min(ec1->ec_min_security,
     451                 :             :                                    restrictinfo->security_level);
     452                 :       13818 :         ec1->ec_max_security = Max(ec1->ec_max_security,
     453                 :             :                                    restrictinfo->security_level);
     454                 :             :         /* mark the RI as associated with this eclass */
     455                 :       13818 :         restrictinfo->left_ec = ec1;
     456                 :       13818 :         restrictinfo->right_ec = ec1;
     457                 :             :         /* mark the RI as usable with this pair of EMs */
     458                 :       13818 :         restrictinfo->left_em = em1;
     459                 :       13818 :         restrictinfo->right_em = em2;
     460                 :             :     }
     461         [ +  + ]:      232480 :     else if (ec2)
     462                 :             :     {
     463                 :             :         /* Case 3: add item1 to ec2 */
     464                 :        2876 :         em1 = add_eq_member(ec2, item1, item1_relids,
     465                 :             :                             jdomain, item1_type);
     466                 :        2876 :         ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
     467                 :        2876 :         ec2->ec_min_security = Min(ec2->ec_min_security,
     468                 :             :                                    restrictinfo->security_level);
     469                 :        2876 :         ec2->ec_max_security = Max(ec2->ec_max_security,
     470                 :             :                                    restrictinfo->security_level);
     471                 :             :         /* mark the RI as associated with this eclass */
     472                 :        2876 :         restrictinfo->left_ec = ec2;
     473                 :        2876 :         restrictinfo->right_ec = ec2;
     474                 :             :         /* mark the RI as usable with this pair of EMs */
     475                 :        2876 :         restrictinfo->left_em = em1;
     476                 :        2876 :         restrictinfo->right_em = em2;
     477                 :             :     }
     478                 :             :     else
     479                 :             :     {
     480                 :             :         /* Case 4: make a new, two-entry EC */
     481                 :      229604 :         EquivalenceClass *ec = makeNode(EquivalenceClass);
     482                 :             : 
     483                 :      229604 :         ec->ec_opfamilies = opfamilies;
     484                 :      229604 :         ec->ec_collation = collation;
     485                 :      229604 :         ec->ec_childmembers_size = 0;
     486                 :      229604 :         ec->ec_members = NIL;
     487                 :      229604 :         ec->ec_childmembers = NULL;
     488                 :      229604 :         ec->ec_sources = list_make1(restrictinfo);
     489                 :      229604 :         ec->ec_derives_list = NIL;
     490                 :      229604 :         ec->ec_derives_hash = NULL;
     491                 :      229604 :         ec->ec_relids = NULL;
     492                 :      229604 :         ec->ec_has_const = false;
     493                 :      229604 :         ec->ec_has_volatile = false;
     494                 :      229604 :         ec->ec_broken = false;
     495                 :      229604 :         ec->ec_sortref = 0;
     496                 :      229604 :         ec->ec_min_security = restrictinfo->security_level;
     497                 :      229604 :         ec->ec_max_security = restrictinfo->security_level;
     498                 :      229604 :         ec->ec_merged = NULL;
     499                 :      229604 :         em1 = add_eq_member(ec, item1, item1_relids,
     500                 :             :                             jdomain, item1_type);
     501                 :      229604 :         em2 = add_eq_member(ec, item2, item2_relids,
     502                 :             :                             jdomain, item2_type);
     503                 :             : 
     504                 :      229604 :         root->eq_classes = lappend(root->eq_classes, ec);
     505                 :             : 
     506                 :             :         /* mark the RI as associated with this eclass */
     507                 :      229604 :         restrictinfo->left_ec = ec;
     508                 :      229604 :         restrictinfo->right_ec = ec;
     509                 :             :         /* mark the RI as usable with this pair of EMs */
     510                 :      229604 :         restrictinfo->left_em = em1;
     511                 :      229604 :         restrictinfo->right_em = em2;
     512                 :             :     }
     513                 :             : 
     514                 :      246331 :     return true;
     515                 :             : }
     516                 :             : 
     517                 :             : /*
     518                 :             :  * canonicalize_ec_expression
     519                 :             :  *
     520                 :             :  * This function ensures that the expression exposes the expected type and
     521                 :             :  * collation, so that it will be equal() to other equivalence-class expressions
     522                 :             :  * that it ought to be equal() to.
     523                 :             :  *
     524                 :             :  * The rule for datatypes is that the exposed type should match what it would
     525                 :             :  * be for an input to an operator of the EC's opfamilies; which is usually
     526                 :             :  * the declared input type of the operator, but in the case of polymorphic
     527                 :             :  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
     528                 :             :  * Expressions coming in from quals will generally have the right type
     529                 :             :  * already, but expressions coming from indexkeys may not (because they are
     530                 :             :  * represented without any explicit relabel in pg_index), and the same problem
     531                 :             :  * occurs for sort expressions (because the parser is likewise cavalier about
     532                 :             :  * putting relabels on them).  Such cases will be binary-compatible with the
     533                 :             :  * real operators, so adding a RelabelType is sufficient.
     534                 :             :  *
     535                 :             :  * Also, the expression's exposed collation must match the EC's collation.
     536                 :             :  * This is important because in comparisons like "foo < bar COLLATE baz",
     537                 :             :  * only one of the expressions has the correct exposed collation as we receive
     538                 :             :  * it from the parser.  Forcing both of them to have it ensures that all
     539                 :             :  * variant spellings of such a construct behave the same.  Again, we can
     540                 :             :  * stick on a RelabelType to force the right exposed collation.  (It might
     541                 :             :  * work to not label the collation at all in EC members, but this is risky
     542                 :             :  * since some parts of the system expect exprCollation() to deliver the
     543                 :             :  * right answer for a sort key.)
     544                 :             :  */
     545                 :             : Expr *
     546                 :     2378552 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
     547                 :             : {
     548                 :     2378552 :     Oid         expr_type = exprType((Node *) expr);
     549                 :             : 
     550                 :             :     /*
     551                 :             :      * For a polymorphic-input-type opclass, just keep the same exposed type.
     552                 :             :      * RECORD opclasses work like polymorphic-type ones for this purpose.
     553                 :             :      */
     554   [ +  -  +  +  :     2378552 :     if (IsPolymorphicType(req_type) || req_type == RECORDOID)
          +  -  +  +  +  
          +  +  +  +  -  
          +  -  +  -  +  
             -  +  -  +  
                      + ]
     555                 :        9440 :         req_type = expr_type;
     556                 :             : 
     557                 :             :     /*
     558                 :             :      * No work if the expression exposes the right type/collation already.
     559                 :             :      */
     560   [ +  +  +  + ]:     4694393 :     if (expr_type != req_type ||
     561                 :     2315841 :         exprCollation((Node *) expr) != req_collation)
     562                 :             :     {
     563                 :             :         /*
     564                 :             :          * If we have to change the type of the expression, set typmod to -1,
     565                 :             :          * since the new type may not have the same typmod interpretation.
     566                 :             :          * When we only have to change collation, preserve the exposed typmod.
     567                 :             :          */
     568                 :             :         int32       req_typmod;
     569                 :             : 
     570         [ +  + ]:       64523 :         if (expr_type != req_type)
     571                 :       62711 :             req_typmod = -1;
     572                 :             :         else
     573                 :        1812 :             req_typmod = exprTypmod((Node *) expr);
     574                 :             : 
     575                 :             :         /*
     576                 :             :          * Use applyRelabelType so that we preserve const-flatness.  This is
     577                 :             :          * important since eval_const_expressions has already been applied.
     578                 :             :          */
     579                 :       64523 :         expr = (Expr *) applyRelabelType((Node *) expr,
     580                 :             :                                          req_type, req_typmod, req_collation,
     581                 :             :                                          COERCE_IMPLICIT_CAST, -1, false);
     582                 :             :     }
     583                 :             : 
     584                 :     2378552 :     return expr;
     585                 :             : }
     586                 :             : 
     587                 :             : /*
     588                 :             :  * make_eq_member
     589                 :             :  *      Build a new EquivalenceMember without adding it to an EC.  If 'parent'
     590                 :             :  *      is NULL, the result will be a parent member, otherwise a child member.
     591                 :             :  */
     592                 :             : static EquivalenceMember *
     593                 :      783832 : make_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
     594                 :             :                JoinDomain *jdomain, EquivalenceMember *parent, Oid datatype)
     595                 :             : {
     596                 :      783832 :     EquivalenceMember *em = makeNode(EquivalenceMember);
     597                 :             : 
     598                 :      783832 :     em->em_expr = expr;
     599                 :      783832 :     em->em_relids = relids;
     600                 :      783832 :     em->em_is_const = false;
     601                 :      783832 :     em->em_is_child = (parent != NULL);
     602                 :      783832 :     em->em_datatype = datatype;
     603                 :      783832 :     em->em_jdomain = jdomain;
     604                 :      783832 :     em->em_parent = parent;
     605                 :             : 
     606         [ +  + ]:      783832 :     if (bms_is_empty(relids))
     607                 :             :     {
     608                 :             :         /*
     609                 :             :          * No Vars, assume it's a pseudoconstant.  This is correct for entries
     610                 :             :          * generated from process_equivalence(), because a WHERE clause can't
     611                 :             :          * contain aggregates or SRFs, and non-volatility was checked before
     612                 :             :          * process_equivalence() ever got called.  But
     613                 :             :          * get_eclass_for_sort_expr() has to work harder.  We put the tests
     614                 :             :          * there not here to save cycles in the equivalence case.
     615                 :             :          */
     616                 :             :         Assert(!parent);
     617                 :      174135 :         em->em_is_const = true;
     618                 :      174135 :         ec->ec_has_const = true;
     619                 :             :         /* it can't affect ec_relids */
     620                 :             :     }
     621                 :             : 
     622                 :      783832 :     return em;
     623                 :             : }
     624                 :             : 
     625                 :             : /*
     626                 :             :  * add_eq_member - build a new non-child EquivalenceMember and add it to 'ec'.
     627                 :             :  */
     628                 :             : static EquivalenceMember *
     629                 :      699658 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
     630                 :             :               JoinDomain *jdomain, Oid datatype)
     631                 :             : {
     632                 :      699658 :     EquivalenceMember *em = make_eq_member(ec, expr, relids, jdomain,
     633                 :             :                                            NULL, datatype);
     634                 :             : 
     635                 :             :     /* add to the members list */
     636                 :      699658 :     ec->ec_members = lappend(ec->ec_members, em);
     637                 :             : 
     638                 :             :     /* record the relids for parent members */
     639                 :      699658 :     ec->ec_relids = bms_add_members(ec->ec_relids, relids);
     640                 :             : 
     641                 :      699658 :     return em;
     642                 :             : }
     643                 :             : 
     644                 :             : /*
     645                 :             :  * add_child_eq_member
     646                 :             :  *      Create an em_is_child=true EquivalenceMember and add it to 'ec'.
     647                 :             :  *
     648                 :             :  * 'root' is the PlannerInfo that 'ec' belongs to.
     649                 :             :  * 'ec' is the EquivalenceClass to add the child member to.
     650                 :             :  * 'ec_index' the index of 'ec' within root->eq_classes, or -1 if maintaining
     651                 :             :  * the RelOptInfo.eclass_indexes isn't needed.
     652                 :             :  * 'expr' is the em_expr for the new member.
     653                 :             :  * 'relids' is the 'em_relids' for the new member.
     654                 :             :  * 'jdomain' is the 'em_jdomain' for the new member.
     655                 :             :  * 'parent_em' is the parent member of the child to create.
     656                 :             :  * 'datatype' is the em_datatype of the new member.
     657                 :             :  * 'child_relid' defines which element of ec_childmembers to add this member
     658                 :             :  * to.  This is generally a RELOPT_OTHER_MEMBER_REL, but for set operations
     659                 :             :  * can be a RELOPT_BASEREL representing the set-op children.
     660                 :             :  */
     661                 :             : static EquivalenceMember *
     662                 :       84174 : add_child_eq_member(PlannerInfo *root, EquivalenceClass *ec, int ec_index,
     663                 :             :                     Expr *expr, Relids relids, JoinDomain *jdomain,
     664                 :             :                     EquivalenceMember *parent_em, Oid datatype,
     665                 :             :                     Index child_relid)
     666                 :             : {
     667                 :             :     EquivalenceMember *em;
     668                 :             : 
     669                 :             :     Assert(parent_em != NULL);
     670                 :             : 
     671                 :             :     /*
     672                 :             :      * Allocate the array to store child members; an array of Lists indexed by
     673                 :             :      * relid, or expand the existing one, if necessary.
     674                 :             :      */
     675         [ +  + ]:       84174 :     if (unlikely(ec->ec_childmembers_size < root->simple_rel_array_size))
     676                 :             :     {
     677         [ +  - ]:       23784 :         if (ec->ec_childmembers == NULL)
     678                 :       23784 :             ec->ec_childmembers = palloc0_array(List *, root->simple_rel_array_size);
     679                 :             :         else
     680                 :           0 :             ec->ec_childmembers = repalloc0_array(ec->ec_childmembers, List *,
     681                 :             :                                                   ec->ec_childmembers_size,
     682                 :             :                                                   root->simple_rel_array_size);
     683                 :             : 
     684                 :       23784 :         ec->ec_childmembers_size = root->simple_rel_array_size;
     685                 :             :     }
     686                 :             : 
     687                 :       84174 :     em = make_eq_member(ec, expr, relids, jdomain, parent_em, datatype);
     688                 :             : 
     689                 :             :     /* add member to the ec_childmembers List for the given child_relid */
     690                 :       84174 :     ec->ec_childmembers[child_relid] = lappend(ec->ec_childmembers[child_relid], em);
     691                 :             : 
     692                 :             :     /* Record this EC index for the child rel */
     693         [ +  + ]:       84174 :     if (ec_index >= 0)
     694                 :             :     {
     695                 :       51253 :         RelOptInfo *child_rel = root->simple_rel_array[child_relid];
     696                 :             : 
     697                 :       51253 :         child_rel->eclass_indexes =
     698                 :       51253 :             bms_add_member(child_rel->eclass_indexes, ec_index);
     699                 :             :     }
     700                 :             : 
     701                 :       84174 :     return em;
     702                 :             : }
     703                 :             : 
     704                 :             : 
     705                 :             : /*
     706                 :             :  * get_eclass_for_sort_expr
     707                 :             :  *    Given an expression and opfamily/collation info, find an existing
     708                 :             :  *    equivalence class it is a member of; if none, optionally build a new
     709                 :             :  *    single-member EquivalenceClass for it.
     710                 :             :  *
     711                 :             :  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
     712                 :             :  * or zero if not.  (It should never be zero if the expression is volatile!)
     713                 :             :  *
     714                 :             :  * If rel is not NULL, it identifies a specific relation we're considering
     715                 :             :  * a path for, and indicates that child EC members for that relation can be
     716                 :             :  * considered.  Otherwise child members are ignored.  (Note: since child EC
     717                 :             :  * members aren't guaranteed unique, a non-NULL value means that there could
     718                 :             :  * be more than one EC that matches the expression; if so it's order-dependent
     719                 :             :  * which one you get.  This is annoying but it only happens in corner cases,
     720                 :             :  * so for now we live with just reporting the first match.  See also
     721                 :             :  * generate_implied_equalities_for_column and match_pathkeys_to_index.)
     722                 :             :  *
     723                 :             :  * If create_it is true, we'll build a new EquivalenceClass when there is no
     724                 :             :  * match.  If create_it is false, we just return NULL when no match.
     725                 :             :  *
     726                 :             :  * This can be used safely both before and after EquivalenceClass merging;
     727                 :             :  * since it never causes merging it does not invalidate any existing ECs
     728                 :             :  * or PathKeys.  However, ECs added after path generation has begun are
     729                 :             :  * of limited usefulness, so usually it's best to create them beforehand.
     730                 :             :  *
     731                 :             :  * Note: opfamilies must be chosen consistently with the way
     732                 :             :  * process_equivalence() would do; that is, generated from a mergejoinable
     733                 :             :  * equality operator.  Else we might fail to detect valid equivalences,
     734                 :             :  * generating poor (but not incorrect) plans.
     735                 :             :  */
     736                 :             : EquivalenceClass *
     737                 :     1757294 : get_eclass_for_sort_expr(PlannerInfo *root,
     738                 :             :                          Expr *expr,
     739                 :             :                          List *opfamilies,
     740                 :             :                          Oid opcintype,
     741                 :             :                          Oid collation,
     742                 :             :                          Index sortref,
     743                 :             :                          Relids rel,
     744                 :             :                          bool create_it)
     745                 :             : {
     746                 :             :     JoinDomain *jdomain;
     747                 :             :     Relids      expr_relids;
     748                 :             :     EquivalenceClass *newec;
     749                 :             :     EquivalenceMember *newem;
     750                 :             :     ListCell   *lc1;
     751                 :             :     MemoryContext oldcontext;
     752                 :             : 
     753                 :             :     /*
     754                 :             :      * Ensure the expression exposes the correct type and collation.
     755                 :             :      */
     756                 :     1757294 :     expr = canonicalize_ec_expression(expr, opcintype, collation);
     757                 :             : 
     758                 :             :     /*
     759                 :             :      * Since SortGroupClause nodes are top-level expressions (GROUP BY, ORDER
     760                 :             :      * BY, etc), they can be presumed to belong to the top JoinDomain.
     761                 :             :      */
     762                 :     1757294 :     jdomain = linitial_node(JoinDomain, root->join_domains);
     763                 :             : 
     764                 :             :     /*
     765                 :             :      * Scan through the existing EquivalenceClasses for a match
     766                 :             :      */
     767   [ +  +  +  +  :     5742619 :     foreach(lc1, root->eq_classes)
                   +  + ]
     768                 :             :     {
     769                 :     5004488 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
     770                 :             :         EquivalenceMemberIterator it;
     771                 :             :         EquivalenceMember *cur_em;
     772                 :             : 
     773                 :             :         /*
     774                 :             :          * Never match to a volatile EC, except when we are looking at another
     775                 :             :          * reference to the same volatile SortGroupClause.
     776                 :             :          */
     777   [ +  +  +  + ]:     5004488 :         if (cur_ec->ec_has_volatile &&
     778         [ +  + ]:          28 :             (sortref == 0 || sortref != cur_ec->ec_sortref))
     779                 :     2116051 :             continue;
     780                 :             : 
     781         [ +  + ]:     5003978 :         if (collation != cur_ec->ec_collation)
     782                 :     1400585 :             continue;
     783         [ +  + ]:     3603393 :         if (!equal(opfamilies, cur_ec->ec_opfamilies))
     784                 :      714956 :             continue;
     785                 :             : 
     786                 :     2888437 :         setup_eclass_member_iterator(&it, cur_ec, rel);
     787         [ +  + ]:     6418628 :         while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
     788                 :             :         {
     789                 :             :             /*
     790                 :             :              * Ignore child members unless they match the request.
     791                 :             :              */
     792         [ +  + ]:     4549354 :             if (cur_em->em_is_child &&
     793         [ -  + ]:       84926 :                 !bms_equal(cur_em->em_relids, rel))
     794                 :           0 :                 continue;
     795                 :             : 
     796                 :             :             /*
     797                 :             :              * Match constants only within the same JoinDomain (see
     798                 :             :              * optimizer/README).
     799                 :             :              */
     800   [ +  +  +  + ]:     4549354 :             if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
     801                 :       57322 :                 continue;
     802                 :             : 
     803   [ +  +  +  + ]:     8950599 :             if (opcintype == cur_em->em_datatype &&
     804                 :     4458567 :                 equal(expr, cur_em->em_expr))
     805                 :     1019163 :                 return cur_ec;  /* Match! */
     806                 :             :         }
     807                 :             :     }
     808                 :             : 
     809                 :             :     /* No match; does caller want a NULL result? */
     810         [ +  + ]:      738131 :     if (!create_it)
     811                 :      514375 :         return NULL;
     812                 :             : 
     813                 :             :     /*
     814                 :             :      * OK, build a new single-member EC
     815                 :             :      *
     816                 :             :      * Here, we must be sure that we construct the EC in the right context.
     817                 :             :      */
     818                 :      223756 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
     819                 :             : 
     820                 :      223756 :     newec = makeNode(EquivalenceClass);
     821                 :      223756 :     newec->ec_opfamilies = list_copy(opfamilies);
     822                 :      223756 :     newec->ec_collation = collation;
     823                 :      223756 :     newec->ec_childmembers_size = 0;
     824                 :      223756 :     newec->ec_members = NIL;
     825                 :      223756 :     newec->ec_childmembers = NULL;
     826                 :      223756 :     newec->ec_sources = NIL;
     827                 :      223756 :     newec->ec_derives_list = NIL;
     828                 :      223756 :     newec->ec_derives_hash = NULL;
     829                 :      223756 :     newec->ec_relids = NULL;
     830                 :      223756 :     newec->ec_has_const = false;
     831                 :      223756 :     newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
     832                 :      223756 :     newec->ec_broken = false;
     833                 :      223756 :     newec->ec_sortref = sortref;
     834                 :      223756 :     newec->ec_min_security = UINT_MAX;
     835                 :      223756 :     newec->ec_max_security = 0;
     836                 :      223756 :     newec->ec_merged = NULL;
     837                 :             : 
     838   [ +  +  -  + ]:      223756 :     if (newec->ec_has_volatile && sortref == 0) /* should not happen */
     839         [ #  # ]:           0 :         elog(ERROR, "volatile EquivalenceClass has no sortref");
     840                 :             : 
     841                 :             :     /*
     842                 :             :      * Get the precise set of relids appearing in the expression.
     843                 :             :      */
     844                 :      223756 :     expr_relids = pull_varnos(root, (Node *) expr);
     845                 :             : 
     846                 :      223756 :     newem = add_eq_member(newec, copyObject(expr), expr_relids,
     847                 :             :                           jdomain, opcintype);
     848                 :             : 
     849                 :             :     /*
     850                 :             :      * add_eq_member doesn't check for volatile functions, set-returning
     851                 :             :      * functions, aggregates, or window functions, but such could appear in
     852                 :             :      * sort expressions; so we have to check whether its const-marking was
     853                 :             :      * correct.
     854                 :             :      */
     855         [ +  + ]:      223756 :     if (newec->ec_has_const)
     856                 :             :     {
     857   [ +  +  +  + ]:       15370 :         if (newec->ec_has_volatile ||
     858         [ +  + ]:       15142 :             expression_returns_set((Node *) expr) ||
     859         [ +  + ]:       14871 :             contain_agg_clause((Node *) expr) ||
     860                 :        7360 :             contain_window_function((Node *) expr))
     861                 :             :         {
     862                 :         384 :             newec->ec_has_const = false;
     863                 :         384 :             newem->em_is_const = false;
     864                 :             :         }
     865                 :             :     }
     866                 :             : 
     867                 :      223756 :     root->eq_classes = lappend(root->eq_classes, newec);
     868                 :             : 
     869                 :             :     /*
     870                 :             :      * If EC merging is already complete, we have to mop up by adding the new
     871                 :             :      * EC to the eclass_indexes of the relation(s) mentioned in it.
     872                 :             :      */
     873         [ +  + ]:      223756 :     if (root->ec_merging_done)
     874                 :             :     {
     875                 :      130415 :         int         ec_index = list_length(root->eq_classes) - 1;
     876                 :      130415 :         int         i = -1;
     877                 :             : 
     878         [ +  + ]:      251722 :         while ((i = bms_next_member(newec->ec_relids, i)) > 0)
     879                 :             :         {
     880                 :      121307 :             RelOptInfo *rel = root->simple_rel_array[i];
     881                 :             : 
     882                 :             :             /* ignore the RTE_GROUP RTE */
     883         [ +  + ]:      121307 :             if (i == root->group_rtindex)
     884                 :         584 :                 continue;
     885                 :             : 
     886         [ +  + ]:      120723 :             if (rel == NULL)    /* must be an outer join */
     887                 :             :             {
     888                 :             :                 Assert(bms_is_member(i, root->outer_join_rels));
     889                 :        5446 :                 continue;
     890                 :             :             }
     891                 :             : 
     892                 :             :             Assert(rel->reloptkind == RELOPT_BASEREL);
     893                 :             : 
     894                 :      115277 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
     895                 :             :                                                  ec_index);
     896                 :             :         }
     897                 :             :     }
     898                 :             : 
     899                 :      223756 :     MemoryContextSwitchTo(oldcontext);
     900                 :             : 
     901                 :      223756 :     return newec;
     902                 :             : }
     903                 :             : 
     904                 :             : /*
     905                 :             :  * find_ec_member_matching_expr
     906                 :             :  *      Locate an EquivalenceClass member matching the given expr, if any;
     907                 :             :  *      return NULL if no match.
     908                 :             :  *
     909                 :             :  * "Matching" is defined as "equal after stripping RelabelTypes".
     910                 :             :  * This is used for identifying sort expressions, and we need to allow
     911                 :             :  * binary-compatible relabeling for some cases involving binary-compatible
     912                 :             :  * sort operators.
     913                 :             :  *
     914                 :             :  * Child EC members are ignored unless they belong to given 'relids'.
     915                 :             :  */
     916                 :             : EquivalenceMember *
     917                 :      275612 : find_ec_member_matching_expr(EquivalenceClass *ec,
     918                 :             :                              Expr *expr,
     919                 :             :                              Relids relids)
     920                 :             : {
     921                 :             :     EquivalenceMemberIterator it;
     922                 :             :     EquivalenceMember *em;
     923                 :             : 
     924                 :             :     /* We ignore binary-compatible relabeling on both ends */
     925   [ +  -  +  + ]:      298035 :     while (expr && IsA(expr, RelabelType))
     926                 :       22423 :         expr = ((RelabelType *) expr)->arg;
     927                 :             : 
     928                 :      275612 :     setup_eclass_member_iterator(&it, ec, relids);
     929         [ +  + ]:      464101 :     while ((em = eclass_member_iterator_next(&it)) != NULL)
     930                 :             :     {
     931                 :             :         Expr       *emexpr;
     932                 :             : 
     933                 :             :         /*
     934                 :             :          * We shouldn't be trying to sort by an equivalence class that
     935                 :             :          * contains a constant, so no need to consider such cases any further.
     936                 :             :          */
     937         [ -  + ]:      307429 :         if (em->em_is_const)
     938                 :           0 :             continue;
     939                 :             : 
     940                 :             :         /*
     941                 :             :          * Ignore child members unless they belong to the requested rel.
     942                 :             :          */
     943         [ +  + ]:      307429 :         if (em->em_is_child &&
     944         [ +  + ]:       10050 :             !bms_is_subset(em->em_relids, relids))
     945                 :        3396 :             continue;
     946                 :             : 
     947                 :             :         /*
     948                 :             :          * Match if same expression (after stripping relabel).
     949                 :             :          */
     950                 :      304033 :         emexpr = em->em_expr;
     951   [ +  -  +  + ]:      310853 :         while (emexpr && IsA(emexpr, RelabelType))
     952                 :        6820 :             emexpr = ((RelabelType *) emexpr)->arg;
     953                 :             : 
     954         [ +  + ]:      304033 :         if (equal(emexpr, expr))
     955                 :      118940 :             return em;
     956                 :             :     }
     957                 :             : 
     958                 :      156672 :     return NULL;
     959                 :             : }
     960                 :             : 
     961                 :             : /*
     962                 :             :  * find_computable_ec_member
     963                 :             :  *      Locate an EquivalenceClass member that can be computed from the
     964                 :             :  *      expressions appearing in "exprs"; return NULL if no match.
     965                 :             :  *
     966                 :             :  * "exprs" can be either a list of bare expression trees, or a list of
     967                 :             :  * TargetEntry nodes.  Typically it will contain Vars and possibly Aggrefs
     968                 :             :  * and WindowFuncs; however, when considering an appendrel member the list
     969                 :             :  * could contain arbitrary expressions.  We consider an EC member to be
     970                 :             :  * computable if all the Vars, PlaceHolderVars, Aggrefs, and WindowFuncs
     971                 :             :  * it needs are present in "exprs".
     972                 :             :  *
     973                 :             :  * There is some subtlety in that definition: for example, if an EC member is
     974                 :             :  * Var_A + 1 while what is in "exprs" is Var_A + 2, it's still computable.
     975                 :             :  * This works because in the final plan tree, the EC member's expression will
     976                 :             :  * be computed as part of the same plan node targetlist that is currently
     977                 :             :  * represented by "exprs".  So if we have Var_A available for the existing
     978                 :             :  * tlist member, it must be OK to use it in the EC expression too.
     979                 :             :  *
     980                 :             :  * Unlike find_ec_member_matching_expr, there's no special provision here
     981                 :             :  * for binary-compatible relabeling.  This is intentional: if we have to
     982                 :             :  * compute an expression in this way, setrefs.c is going to insist on exact
     983                 :             :  * matches of Vars to the source tlist.
     984                 :             :  *
     985                 :             :  * Child EC members are ignored unless they belong to given 'relids'.
     986                 :             :  * Also, non-parallel-safe expressions are ignored if 'require_parallel_safe'.
     987                 :             :  *
     988                 :             :  * Note: some callers pass root == NULL for notational reasons.  This is OK
     989                 :             :  * when require_parallel_safe is false.
     990                 :             :  */
     991                 :             : EquivalenceMember *
     992                 :        7333 : find_computable_ec_member(PlannerInfo *root,
     993                 :             :                           EquivalenceClass *ec,
     994                 :             :                           List *exprs,
     995                 :             :                           Relids relids,
     996                 :             :                           bool require_parallel_safe)
     997                 :             : {
     998                 :             :     List       *exprvars;
     999                 :             :     EquivalenceMemberIterator it;
    1000                 :             :     EquivalenceMember *em;
    1001                 :             : 
    1002                 :             :     /*
    1003                 :             :      * Pull out the Vars and quasi-Vars present in "exprs".  In the typical
    1004                 :             :      * non-appendrel case, this is just another representation of the same
    1005                 :             :      * list.  However, it does remove the distinction between the case of a
    1006                 :             :      * list of plain expressions and a list of TargetEntrys.
    1007                 :             :      */
    1008                 :        7333 :     exprvars = pull_var_clause((Node *) exprs,
    1009                 :             :                                PVC_INCLUDE_AGGREGATES |
    1010                 :             :                                PVC_INCLUDE_WINDOWFUNCS |
    1011                 :             :                                PVC_INCLUDE_PLACEHOLDERS);
    1012                 :             : 
    1013                 :        7333 :     setup_eclass_member_iterator(&it, ec, relids);
    1014         [ +  + ]:       14663 :     while ((em = eclass_member_iterator_next(&it)) != NULL)
    1015                 :             :     {
    1016                 :             :         List       *emvars;
    1017                 :             :         ListCell   *lc2;
    1018                 :             : 
    1019                 :             :         /*
    1020                 :             :          * We shouldn't be trying to sort by an equivalence class that
    1021                 :             :          * contains a constant, so no need to consider such cases any further.
    1022                 :             :          */
    1023         [ -  + ]:        7801 :         if (em->em_is_const)
    1024                 :           0 :             continue;
    1025                 :             : 
    1026                 :             :         /*
    1027                 :             :          * Ignore child members unless they belong to the requested rel.
    1028                 :             :          */
    1029         [ +  + ]:        7801 :         if (em->em_is_child &&
    1030         [ +  + ]:         270 :             !bms_is_subset(em->em_relids, relids))
    1031                 :         110 :             continue;
    1032                 :             : 
    1033                 :             :         /*
    1034                 :             :          * Match if all Vars and quasi-Vars are present in "exprs".
    1035                 :             :          */
    1036                 :        7691 :         emvars = pull_var_clause((Node *) em->em_expr,
    1037                 :             :                                  PVC_INCLUDE_AGGREGATES |
    1038                 :             :                                  PVC_INCLUDE_WINDOWFUNCS |
    1039                 :             :                                  PVC_INCLUDE_PLACEHOLDERS);
    1040   [ +  +  +  +  :        8618 :         foreach(lc2, emvars)
                   +  + ]
    1041                 :             :         {
    1042         [ +  + ]:        8027 :             if (!list_member(exprvars, lfirst(lc2)))
    1043                 :        7100 :                 break;
    1044                 :             :         }
    1045                 :        7691 :         list_free(emvars);
    1046         [ +  + ]:        7691 :         if (lc2)
    1047                 :        7100 :             continue;           /* we hit a non-available Var */
    1048                 :             : 
    1049                 :             :         /*
    1050                 :             :          * If requested, reject expressions that are not parallel-safe.  We
    1051                 :             :          * check this last because it's a rather expensive test.
    1052                 :             :          */
    1053         [ +  + ]:         591 :         if (require_parallel_safe &&
    1054         [ +  + ]:         281 :             !is_parallel_safe(root, (Node *) em->em_expr))
    1055                 :         120 :             continue;
    1056                 :             : 
    1057                 :         471 :         return em;              /* found usable expression */
    1058                 :             :     }
    1059                 :             : 
    1060                 :        6862 :     return NULL;
    1061                 :             : }
    1062                 :             : 
    1063                 :             : /*
    1064                 :             :  * relation_can_be_sorted_early
    1065                 :             :  *      Can this relation be sorted on this EC before the final output step?
    1066                 :             :  *
    1067                 :             :  * To succeed, we must find an EC member that prepare_sort_from_pathkeys knows
    1068                 :             :  * how to sort on, given the rel's reltarget as input.  There are also a few
    1069                 :             :  * additional constraints based on the fact that the desired sort will be done
    1070                 :             :  * "early", within the scan/join part of the plan.  Also, non-parallel-safe
    1071                 :             :  * expressions are ignored if 'require_parallel_safe'.
    1072                 :             :  *
    1073                 :             :  * At some point we might want to return the identified EquivalenceMember,
    1074                 :             :  * but for now, callers only want to know if there is one.
    1075                 :             :  */
    1076                 :             : bool
    1077                 :       16620 : relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
    1078                 :             :                              EquivalenceClass *ec, bool require_parallel_safe)
    1079                 :             : {
    1080                 :       16620 :     PathTarget *target = rel->reltarget;
    1081                 :             :     EquivalenceMember *em;
    1082                 :             :     ListCell   *lc;
    1083                 :             : 
    1084                 :             :     /*
    1085                 :             :      * Reject volatile ECs immediately; such sorts must always be postponed.
    1086                 :             :      */
    1087         [ +  + ]:       16620 :     if (ec->ec_has_volatile)
    1088                 :          60 :         return false;
    1089                 :             : 
    1090                 :             :     /*
    1091                 :             :      * Try to find an EM directly matching some reltarget member.
    1092                 :             :      */
    1093   [ +  +  +  +  :       38366 :     foreach(lc, target->exprs)
                   +  + ]
    1094                 :             :     {
    1095                 :       31343 :         Expr       *targetexpr = (Expr *) lfirst(lc);
    1096                 :             : 
    1097                 :       31343 :         em = find_ec_member_matching_expr(ec, targetexpr, rel->relids);
    1098         [ +  + ]:       31343 :         if (!em)
    1099                 :       21806 :             continue;
    1100                 :             : 
    1101                 :             :         /*
    1102                 :             :          * Reject expressions involving set-returning functions, as those
    1103                 :             :          * can't be computed early either.  (Note: this test and the following
    1104                 :             :          * one are effectively checking properties of targetexpr, so there's
    1105                 :             :          * no point in asking whether some other EC member would be better.)
    1106                 :             :          */
    1107         [ -  + ]:        9537 :         if (expression_returns_set((Node *) em->em_expr))
    1108                 :           0 :             continue;
    1109                 :             : 
    1110                 :             :         /*
    1111                 :             :          * If requested, reject expressions that are not parallel-safe.  We
    1112                 :             :          * check this last because it's a rather expensive test.
    1113                 :             :          */
    1114         [ +  - ]:        9537 :         if (require_parallel_safe &&
    1115         [ -  + ]:        9537 :             !is_parallel_safe(root, (Node *) em->em_expr))
    1116                 :           0 :             continue;
    1117                 :             : 
    1118                 :        9537 :         return true;
    1119                 :             :     }
    1120                 :             : 
    1121                 :             :     /*
    1122                 :             :      * Try to find an expression computable from the reltarget.
    1123                 :             :      */
    1124                 :        7023 :     em = find_computable_ec_member(root, ec, target->exprs, rel->relids,
    1125                 :             :                                    require_parallel_safe);
    1126         [ +  + ]:        7023 :     if (!em)
    1127                 :        6862 :         return false;
    1128                 :             : 
    1129                 :             :     /*
    1130                 :             :      * Reject expressions involving set-returning functions, as those can't be
    1131                 :             :      * computed early either.  (There's no point in looking for another EC
    1132                 :             :      * member in this case; since SRFs can't appear in WHERE, they cannot
    1133                 :             :      * belong to multi-member ECs.)
    1134                 :             :      */
    1135         [ +  + ]:         161 :     if (expression_returns_set((Node *) em->em_expr))
    1136                 :          10 :         return false;
    1137                 :             : 
    1138                 :         151 :     return true;
    1139                 :             : }
    1140                 :             : 
    1141                 :             : /*
    1142                 :             :  * generate_base_implied_equalities
    1143                 :             :  *    Generate any restriction clauses that we can deduce from equivalence
    1144                 :             :  *    classes.
    1145                 :             :  *
    1146                 :             :  * When an EC contains pseudoconstants, our strategy is to generate
    1147                 :             :  * "member = const1" clauses where const1 is the first constant member, for
    1148                 :             :  * every other member (including other constants).  If we are able to do this
    1149                 :             :  * then we don't need any "var = var" comparisons because we've successfully
    1150                 :             :  * constrained all the vars at their points of creation.  If we fail to
    1151                 :             :  * generate any of these clauses due to lack of cross-type operators, we fall
    1152                 :             :  * back to the "ec_broken" strategy described below.  (XXX if there are
    1153                 :             :  * multiple constants of different types, it's possible that we might succeed
    1154                 :             :  * in forming all the required clauses if we started from a different const
    1155                 :             :  * member; but this seems a sufficiently hokey corner case to not be worth
    1156                 :             :  * spending lots of cycles on.)
    1157                 :             :  *
    1158                 :             :  * For ECs that contain no pseudoconstants, we generate derived clauses
    1159                 :             :  * "member1 = member2" for each pair of members belonging to the same base
    1160                 :             :  * relation (actually, if there are more than two for the same base relation,
    1161                 :             :  * we only need enough clauses to link each to each other).  This provides
    1162                 :             :  * the base case for the recursion: each row emitted by a base relation scan
    1163                 :             :  * will constrain all computable members of the EC to be equal.  As each
    1164                 :             :  * join path is formed, we'll add additional derived clauses on-the-fly
    1165                 :             :  * to maintain this invariant (see generate_join_implied_equalities).
    1166                 :             :  *
    1167                 :             :  * If the opfamilies used by the EC do not provide complete sets of cross-type
    1168                 :             :  * equality operators, it is possible that we will fail to generate a clause
    1169                 :             :  * that must be generated to maintain the invariant.  (An example: given
    1170                 :             :  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
    1171                 :             :  * generate "a.x = a.z" as a restriction clause for A.)  In this case we mark
    1172                 :             :  * the EC "ec_broken" and fall back to regurgitating its original source
    1173                 :             :  * RestrictInfos at appropriate times.  We do not try to retract any derived
    1174                 :             :  * clauses already generated from the broken EC, so the resulting plan could
    1175                 :             :  * be poor due to bad selectivity estimates caused by redundant clauses.  But
    1176                 :             :  * the correct solution to that is to fix the opfamilies ...
    1177                 :             :  *
    1178                 :             :  * Equality clauses derived by this function are passed off to
    1179                 :             :  * process_implied_equality (in plan/initsplan.c) to be inserted into the
    1180                 :             :  * restrictinfo datastructures.  Note that this must be called after initial
    1181                 :             :  * scanning of the quals and before Path construction begins.
    1182                 :             :  *
    1183                 :             :  * We make no attempt to avoid generating duplicate RestrictInfos here: we
    1184                 :             :  * don't search existing source or derived clauses in the EC for matches.  It
    1185                 :             :  * doesn't really seem worth the trouble to do so.
    1186                 :             :  */
    1187                 :             : void
    1188                 :      257712 : generate_base_implied_equalities(PlannerInfo *root)
    1189                 :             : {
    1190                 :             :     int         ec_index;
    1191                 :             :     ListCell   *lc;
    1192                 :             : 
    1193                 :             :     /*
    1194                 :             :      * At this point, we're done absorbing knowledge of equivalences in the
    1195                 :             :      * query, so no further EC merging should happen, and ECs remaining in the
    1196                 :             :      * eq_classes list can be considered canonical.  (But note that it's still
    1197                 :             :      * possible for new single-member ECs to be added through
    1198                 :             :      * get_eclass_for_sort_expr().)
    1199                 :             :      */
    1200                 :      257712 :     root->ec_merging_done = true;
    1201                 :             : 
    1202                 :      257712 :     ec_index = 0;
    1203   [ +  +  +  +  :      580624 :     foreach(lc, root->eq_classes)
                   +  + ]
    1204                 :             :     {
    1205                 :      322912 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
    1206                 :      322912 :         bool        can_generate_joinclause = false;
    1207                 :             :         int         i;
    1208                 :             : 
    1209                 :             :         Assert(ec->ec_merged == NULL);   /* else shouldn't be in list */
    1210                 :             :         Assert(!ec->ec_broken); /* not yet anyway... */
    1211                 :             : 
    1212                 :             :         /*
    1213                 :             :          * Generate implied equalities that are restriction clauses.
    1214                 :             :          * Single-member ECs won't generate any deductions, either here or at
    1215                 :             :          * the join level.
    1216                 :             :          */
    1217         [ +  + ]:      322912 :         if (list_length(ec->ec_members) > 1)
    1218                 :             :         {
    1219         [ +  + ]:      231243 :             if (ec->ec_has_const)
    1220                 :      166256 :                 generate_base_implied_equalities_const(root, ec);
    1221                 :             :             else
    1222                 :       64987 :                 generate_base_implied_equalities_no_const(root, ec);
    1223                 :             : 
    1224                 :             :             /* Recover if we failed to generate required derived clauses */
    1225         [ +  + ]:      231243 :             if (ec->ec_broken)
    1226                 :          25 :                 generate_base_implied_equalities_broken(root, ec);
    1227                 :             : 
    1228                 :             :             /* Detect whether this EC might generate join clauses */
    1229                 :      231243 :             can_generate_joinclause =
    1230                 :      231243 :                 (bms_membership(ec->ec_relids) == BMS_MULTIPLE);
    1231                 :             :         }
    1232                 :             : 
    1233                 :             :         /*
    1234                 :             :          * Mark the base rels cited in each eclass (which should all exist by
    1235                 :             :          * now) with the eq_classes indexes of all eclasses mentioning them.
    1236                 :             :          * This will let us avoid searching in subsequent lookups.  While
    1237                 :             :          * we're at it, we can mark base rels that have pending eclass joins;
    1238                 :             :          * this is a cheap version of has_relevant_eclass_joinclause().
    1239                 :             :          */
    1240                 :      322912 :         i = -1;
    1241         [ +  + ]:      726990 :         while ((i = bms_next_member(ec->ec_relids, i)) > 0)
    1242                 :             :         {
    1243                 :      404078 :             RelOptInfo *rel = root->simple_rel_array[i];
    1244                 :             : 
    1245                 :             :             /* ignore the RTE_GROUP RTE */
    1246         [ -  + ]:      404078 :             if (i == root->group_rtindex)
    1247                 :           0 :                 continue;
    1248                 :             : 
    1249         [ +  + ]:      404078 :             if (rel == NULL)    /* must be an outer join */
    1250                 :             :             {
    1251                 :             :                 Assert(bms_is_member(i, root->outer_join_rels));
    1252                 :        3349 :                 continue;
    1253                 :             :             }
    1254                 :             : 
    1255                 :             :             Assert(rel->reloptkind == RELOPT_BASEREL);
    1256                 :             : 
    1257                 :      400729 :             rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
    1258                 :             :                                                  ec_index);
    1259                 :             : 
    1260         [ +  + ]:      400729 :             if (can_generate_joinclause)
    1261                 :      154422 :                 rel->has_eclass_joins = true;
    1262                 :             :         }
    1263                 :             : 
    1264                 :      322912 :         ec_index++;
    1265                 :             :     }
    1266                 :      257712 : }
    1267                 :             : 
    1268                 :             : /*
    1269                 :             :  * generate_base_implied_equalities when EC contains pseudoconstant(s)
    1270                 :             :  */
    1271                 :             : static void
    1272                 :      166256 : generate_base_implied_equalities_const(PlannerInfo *root,
    1273                 :             :                                        EquivalenceClass *ec)
    1274                 :             : {
    1275                 :      166256 :     EquivalenceMember *const_em = NULL;
    1276                 :             :     ListCell   *lc;
    1277                 :             : 
    1278                 :             :     /*
    1279                 :             :      * In the trivial case where we just had one "var = const" clause, push
    1280                 :             :      * the original clause back into the main planner machinery.  There is
    1281                 :             :      * nothing to be gained by doing it differently, and we save the effort to
    1282                 :             :      * re-build and re-analyze an equality clause that will be exactly
    1283                 :             :      * equivalent to the old one.
    1284                 :             :      */
    1285   [ +  +  +  + ]:      320026 :     if (list_length(ec->ec_members) == 2 &&
    1286                 :      153770 :         list_length(ec->ec_sources) == 1)
    1287                 :             :     {
    1288                 :      153735 :         RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
    1289                 :             : 
    1290                 :      153735 :         distribute_restrictinfo_to_rels(root, restrictinfo);
    1291                 :      153735 :         return;
    1292                 :             :     }
    1293                 :             : 
    1294                 :             :     /* We don't expect any children yet */
    1295                 :             :     Assert(ec->ec_childmembers == NULL);
    1296                 :             : 
    1297                 :             :     /*
    1298                 :             :      * Find the constant member to use.  We prefer an actual constant to
    1299                 :             :      * pseudo-constants (such as Params), because the constraint exclusion
    1300                 :             :      * machinery might be able to exclude relations on the basis of generated
    1301                 :             :      * "var = const" equalities, but "var = param" won't work for that.
    1302                 :             :      */
    1303   [ +  -  +  +  :       30068 :     foreach(lc, ec->ec_members)
                   +  + ]
    1304                 :             :     {
    1305                 :       29974 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1306                 :             : 
    1307         [ +  + ]:       29974 :         if (cur_em->em_is_const)
    1308                 :             :         {
    1309                 :       12526 :             const_em = cur_em;
    1310         [ +  + ]:       12526 :             if (IsA(cur_em->em_expr, Const))
    1311                 :       12427 :                 break;
    1312                 :             :         }
    1313                 :             :     }
    1314                 :             :     Assert(const_em != NULL);
    1315                 :             : 
    1316                 :             :     /* Generate a derived equality against each other member */
    1317   [ +  -  +  +  :       50165 :     foreach(lc, ec->ec_members)
                   +  + ]
    1318                 :             :     {
    1319                 :       37669 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1320                 :             :         Oid         eq_op;
    1321                 :             :         RestrictInfo *rinfo;
    1322                 :             : 
    1323                 :             :         /* Child members should not exist in ec_members */
    1324                 :             :         Assert(!cur_em->em_is_child);
    1325         [ +  + ]:       37669 :         if (cur_em == const_em)
    1326                 :       12501 :             continue;
    1327                 :       25168 :         eq_op = select_equality_operator(ec,
    1328                 :             :                                          cur_em->em_datatype,
    1329                 :             :                                          const_em->em_datatype);
    1330         [ +  + ]:       25168 :         if (!OidIsValid(eq_op))
    1331                 :             :         {
    1332                 :             :             /* failed... */
    1333                 :          25 :             ec->ec_broken = true;
    1334                 :          25 :             break;
    1335                 :             :         }
    1336                 :             : 
    1337                 :             :         /*
    1338                 :             :          * We use the constant's em_jdomain as qualscope, so that if the
    1339                 :             :          * generated clause is variable-free (i.e, both EMs are consts) it
    1340                 :             :          * will be enforced at the join domain level.
    1341                 :             :          */
    1342                 :       25143 :         rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
    1343                 :             :                                          cur_em->em_expr, const_em->em_expr,
    1344                 :       25143 :                                          const_em->em_jdomain->jd_relids,
    1345                 :             :                                          ec->ec_min_security,
    1346                 :       25143 :                                          cur_em->em_is_const);
    1347                 :             : 
    1348                 :             :         /*
    1349                 :             :          * If the clause didn't degenerate to a constant, fill in the correct
    1350                 :             :          * markings for a mergejoinable clause, and save it as a derived
    1351                 :             :          * clause. (We will not re-use such clauses directly, but selectivity
    1352                 :             :          * estimation may consult those later.  Note that this use of derived
    1353                 :             :          * clauses does not overlap with its use for join clauses, since we
    1354                 :             :          * never generate join clauses from an ec_has_const eclass.)
    1355                 :             :          */
    1356   [ +  -  +  + ]:       25143 :         if (rinfo && rinfo->mergeopfamilies)
    1357                 :             :         {
    1358                 :             :             /* it's not redundant, so don't set parent_ec */
    1359                 :       25008 :             rinfo->left_ec = rinfo->right_ec = ec;
    1360                 :       25008 :             rinfo->left_em = cur_em;
    1361                 :       25008 :             rinfo->right_em = const_em;
    1362                 :       25008 :             ec_add_derived_clause(ec, rinfo);
    1363                 :             :         }
    1364                 :             :     }
    1365                 :             : }
    1366                 :             : 
    1367                 :             : /*
    1368                 :             :  * generate_base_implied_equalities when EC contains no pseudoconstants
    1369                 :             :  */
    1370                 :             : static void
    1371                 :       64987 : generate_base_implied_equalities_no_const(PlannerInfo *root,
    1372                 :             :                                           EquivalenceClass *ec)
    1373                 :             : {
    1374                 :             :     EquivalenceMember **prev_ems;
    1375                 :             :     ListCell   *lc;
    1376                 :             : 
    1377                 :             :     /*
    1378                 :             :      * We scan the EC members once and track the last-seen member for each
    1379                 :             :      * base relation.  When we see another member of the same base relation,
    1380                 :             :      * we generate "prev_em = cur_em".  This results in the minimum number of
    1381                 :             :      * derived clauses, but it's possible that it will fail when a different
    1382                 :             :      * ordering would succeed.  XXX FIXME: use a UNION-FIND algorithm similar
    1383                 :             :      * to the way we build merged ECs.  (Use a list-of-lists for each rel.)
    1384                 :             :      */
    1385                 :       64987 :     prev_ems = palloc0_array(EquivalenceMember *, root->simple_rel_array_size);
    1386                 :             : 
    1387                 :             :     /* We don't expect any children yet */
    1388                 :             :     Assert(ec->ec_childmembers == NULL);
    1389                 :             : 
    1390   [ +  -  +  +  :      197387 :     foreach(lc, ec->ec_members)
                   +  + ]
    1391                 :             :     {
    1392                 :      132400 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1393                 :             :         int         relid;
    1394                 :             : 
    1395                 :             :         /* Child members should not exist in ec_members */
    1396                 :             :         Assert(!cur_em->em_is_child);
    1397                 :             : 
    1398         [ +  + ]:      132400 :         if (!bms_get_singleton_member(cur_em->em_relids, &relid))
    1399                 :         185 :             continue;
    1400                 :             :         Assert(relid < root->simple_rel_array_size);
    1401                 :             : 
    1402         [ +  + ]:      132215 :         if (prev_ems[relid] != NULL)
    1403                 :             :         {
    1404                 :         429 :             EquivalenceMember *prev_em = prev_ems[relid];
    1405                 :             :             Oid         eq_op;
    1406                 :             :             RestrictInfo *rinfo;
    1407                 :             : 
    1408                 :         429 :             eq_op = select_equality_operator(ec,
    1409                 :             :                                              prev_em->em_datatype,
    1410                 :             :                                              cur_em->em_datatype);
    1411         [ -  + ]:         429 :             if (!OidIsValid(eq_op))
    1412                 :             :             {
    1413                 :             :                 /* failed... */
    1414                 :           0 :                 ec->ec_broken = true;
    1415                 :           0 :                 break;
    1416                 :             :             }
    1417                 :             : 
    1418                 :             :             /*
    1419                 :             :              * The expressions aren't constants, so the passed qualscope will
    1420                 :             :              * never be used to place the generated clause.  We just need to
    1421                 :             :              * be sure it covers both expressions, which em_relids should do.
    1422                 :             :              */
    1423                 :         429 :             rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
    1424                 :             :                                              prev_em->em_expr, cur_em->em_expr,
    1425                 :             :                                              cur_em->em_relids,
    1426                 :             :                                              ec->ec_min_security,
    1427                 :             :                                              false);
    1428                 :             : 
    1429                 :             :             /*
    1430                 :             :              * If the clause didn't degenerate to a constant, fill in the
    1431                 :             :              * correct markings for a mergejoinable clause.  We don't record
    1432                 :             :              * it as a derived clause, since we don't currently need to
    1433                 :             :              * re-find such clauses, and don't want to clutter the
    1434                 :             :              * derived-clause set with non-join clauses.
    1435                 :             :              */
    1436   [ +  -  +  - ]:         429 :             if (rinfo && rinfo->mergeopfamilies)
    1437                 :             :             {
    1438                 :             :                 /* it's not redundant, so don't set parent_ec */
    1439                 :         429 :                 rinfo->left_ec = rinfo->right_ec = ec;
    1440                 :         429 :                 rinfo->left_em = prev_em;
    1441                 :         429 :                 rinfo->right_em = cur_em;
    1442                 :             :             }
    1443                 :             :         }
    1444                 :      132215 :         prev_ems[relid] = cur_em;
    1445                 :             :     }
    1446                 :             : 
    1447                 :       64987 :     pfree(prev_ems);
    1448                 :             : 
    1449                 :             :     /*
    1450                 :             :      * We also have to make sure that all the Vars used in the member clauses
    1451                 :             :      * will be available at any join node we might try to reference them at.
    1452                 :             :      * For the moment we force all the Vars to be available at all join nodes
    1453                 :             :      * for this eclass.  Perhaps this could be improved by doing some
    1454                 :             :      * pre-analysis of which members we prefer to join, but it's no worse than
    1455                 :             :      * what happened in the pre-8.3 code.
    1456                 :             :      */
    1457   [ +  -  +  +  :      197387 :     foreach(lc, ec->ec_members)
                   +  + ]
    1458                 :             :     {
    1459                 :      132400 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    1460                 :      132400 :         List       *vars = pull_var_clause((Node *) cur_em->em_expr,
    1461                 :             :                                            PVC_RECURSE_AGGREGATES |
    1462                 :             :                                            PVC_RECURSE_WINDOWFUNCS |
    1463                 :             :                                            PVC_INCLUDE_PLACEHOLDERS);
    1464                 :             : 
    1465                 :      132400 :         add_vars_to_targetlist(root, vars, ec->ec_relids);
    1466                 :      132400 :         list_free(vars);
    1467                 :             :     }
    1468                 :       64987 : }
    1469                 :             : 
    1470                 :             : /*
    1471                 :             :  * generate_base_implied_equalities cleanup after failure
    1472                 :             :  *
    1473                 :             :  * What we must do here is push any zero- or one-relation source RestrictInfos
    1474                 :             :  * of the EC back into the main restrictinfo datastructures.  Multi-relation
    1475                 :             :  * clauses will be regurgitated later by generate_join_implied_equalities().
    1476                 :             :  * (We do it this way to maintain continuity with the case that ec_broken
    1477                 :             :  * becomes set only after we've gone up a join level or two.)  However, for
    1478                 :             :  * an EC that contains constants, we can adopt a simpler strategy and just
    1479                 :             :  * throw back all the source RestrictInfos immediately; that works because
    1480                 :             :  * we know that such an EC can't become broken later.  (This rule justifies
    1481                 :             :  * ignoring ec_has_const ECs in generate_join_implied_equalities, even when
    1482                 :             :  * they are broken.)
    1483                 :             :  */
    1484                 :             : static void
    1485                 :          25 : generate_base_implied_equalities_broken(PlannerInfo *root,
    1486                 :             :                                         EquivalenceClass *ec)
    1487                 :             : {
    1488                 :             :     ListCell   *lc;
    1489                 :             : 
    1490   [ +  -  +  +  :          80 :     foreach(lc, ec->ec_sources)
                   +  + ]
    1491                 :             :     {
    1492                 :          55 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1493                 :             : 
    1494   [ -  +  -  - ]:          55 :         if (ec->ec_has_const ||
    1495                 :           0 :             bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
    1496                 :          55 :             distribute_restrictinfo_to_rels(root, restrictinfo);
    1497                 :             :     }
    1498                 :          25 : }
    1499                 :             : 
    1500                 :             : 
    1501                 :             : /*
    1502                 :             :  * generate_join_implied_equalities
    1503                 :             :  *    Generate any join clauses that we can deduce from equivalence classes.
    1504                 :             :  *
    1505                 :             :  * At a join node, we must enforce restriction clauses sufficient to ensure
    1506                 :             :  * that all equivalence-class members computable at that node are equal.
    1507                 :             :  * Since the set of clauses to enforce can vary depending on which subset
    1508                 :             :  * relations are the inputs, we have to compute this afresh for each join
    1509                 :             :  * relation pair.  Hence a fresh List of RestrictInfo nodes is built and
    1510                 :             :  * passed back on each call.
    1511                 :             :  *
    1512                 :             :  * In addition to its use at join nodes, this can be applied to generate
    1513                 :             :  * eclass-based join clauses for use in a parameterized scan of a base rel.
    1514                 :             :  * The reason for the asymmetry of specifying the inner rel as a RelOptInfo
    1515                 :             :  * and the outer rel by Relids is that this usage occurs before we have
    1516                 :             :  * built any join RelOptInfos.
    1517                 :             :  *
    1518                 :             :  * An annoying special case for parameterized scans is that the inner rel can
    1519                 :             :  * be an appendrel child (an "other rel").  In this case we must generate
    1520                 :             :  * appropriate clauses using child EC members.  add_child_rel_equivalences
    1521                 :             :  * must already have been done for the child rel.
    1522                 :             :  *
    1523                 :             :  * The results are sufficient for use in merge, hash, and plain nestloop join
    1524                 :             :  * methods.  We do not worry here about selecting clauses that are optimal
    1525                 :             :  * for use in a parameterized indexscan.  indxpath.c makes its own selections
    1526                 :             :  * of clauses to use, and if the ones we pick here are redundant with those,
    1527                 :             :  * the extras will be eliminated at createplan time, using the parent_ec
    1528                 :             :  * markers that we provide (see is_redundant_derived_clause()).
    1529                 :             :  *
    1530                 :             :  * Because the same join clauses are likely to be needed multiple times as
    1531                 :             :  * we consider different join paths, we avoid generating multiple copies:
    1532                 :             :  * whenever we select a particular pair of EquivalenceMembers to join,
    1533                 :             :  * we check to see if the pair matches any original clause (in ec_sources)
    1534                 :             :  * or previously-built derived clause.  This saves memory and allows
    1535                 :             :  * re-use of information cached in RestrictInfos.  We also avoid generating
    1536                 :             :  * commutative duplicates, i.e. if the algorithm selects "a.x = b.y" but
    1537                 :             :  * we already have "b.y = a.x", we return the existing clause.
    1538                 :             :  *
    1539                 :             :  * If we are considering an outer join, sjinfo is the associated OJ info,
    1540                 :             :  * otherwise it can be NULL.
    1541                 :             :  *
    1542                 :             :  * join_relids should always equal bms_union(outer_relids, inner_rel->relids)
    1543                 :             :  * plus whatever add_outer_joins_to_relids() would add.  We could simplify
    1544                 :             :  * this function's API by computing it internally, but most callers have the
    1545                 :             :  * value at hand anyway.
    1546                 :             :  */
    1547                 :             : List *
    1548                 :      451646 : generate_join_implied_equalities(PlannerInfo *root,
    1549                 :             :                                  Relids join_relids,
    1550                 :             :                                  Relids outer_relids,
    1551                 :             :                                  RelOptInfo *inner_rel,
    1552                 :             :                                  SpecialJoinInfo *sjinfo)
    1553                 :             : {
    1554                 :      451646 :     List       *result = NIL;
    1555                 :      451646 :     Relids      inner_relids = inner_rel->relids;
    1556                 :             :     Relids      nominal_inner_relids;
    1557                 :             :     Relids      nominal_join_relids;
    1558                 :             :     Bitmapset  *matching_ecs;
    1559                 :             :     int         i;
    1560                 :             : 
    1561                 :             :     /* If inner rel is a child, extra setup work is needed */
    1562   [ +  +  +  +  :      451646 :     if (IS_OTHER_REL(inner_rel))
                   -  + ]
    1563                 :             :     {
    1564                 :             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1565                 :             : 
    1566                 :             :         /* Fetch relid set for the topmost parent rel */
    1567                 :        6332 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1568                 :             :         /* ECs will be marked with the parent's relid, not the child's */
    1569                 :        6332 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1570                 :        6332 :         nominal_join_relids = add_outer_joins_to_relids(root,
    1571                 :             :                                                         nominal_join_relids,
    1572                 :             :                                                         sjinfo,
    1573                 :             :                                                         NULL);
    1574                 :             :     }
    1575                 :             :     else
    1576                 :             :     {
    1577                 :      445314 :         nominal_inner_relids = inner_relids;
    1578                 :      445314 :         nominal_join_relids = join_relids;
    1579                 :             :     }
    1580                 :             : 
    1581                 :             :     /*
    1582                 :             :      * Examine all potentially-relevant eclasses.
    1583                 :             :      *
    1584                 :             :      * If we are considering an outer join, we must include "join" clauses
    1585                 :             :      * that mention either input rel plus the outer join's relid; these
    1586                 :             :      * represent post-join filter clauses that have to be applied at this
    1587                 :             :      * join.  We don't have infrastructure that would let us identify such
    1588                 :             :      * eclasses cheaply, so just fall back to considering all eclasses
    1589                 :             :      * mentioning anything in nominal_join_relids.
    1590                 :             :      *
    1591                 :             :      * At inner joins, we can be smarter: only consider eclasses mentioning
    1592                 :             :      * both input rels.
    1593                 :             :      */
    1594   [ +  +  +  + ]:      451646 :     if (sjinfo && sjinfo->ojrelid != 0)
    1595                 :       63005 :         matching_ecs = get_eclass_indexes_for_relids(root, nominal_join_relids);
    1596                 :             :     else
    1597                 :      388641 :         matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
    1598                 :             :                                                  outer_relids);
    1599                 :             : 
    1600                 :      451646 :     i = -1;
    1601         [ +  + ]:     1198600 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    1602                 :             :     {
    1603                 :      746954 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    1604                 :      746954 :         List       *sublist = NIL;
    1605                 :             : 
    1606                 :             :         /* ECs containing consts do not need any further enforcement */
    1607         [ +  + ]:      746954 :         if (ec->ec_has_const)
    1608                 :       88119 :             continue;
    1609                 :             : 
    1610                 :             :         /* Single-member ECs won't generate any deductions */
    1611         [ +  + ]:      658835 :         if (list_length(ec->ec_members) <= 1)
    1612                 :      301990 :             continue;
    1613                 :             : 
    1614                 :             :         /* Sanity check that this eclass overlaps the join */
    1615                 :             :         Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
    1616                 :             : 
    1617         [ +  + ]:      356845 :         if (!ec->ec_broken)
    1618                 :      356575 :             sublist = generate_join_implied_equalities_normal(root,
    1619                 :             :                                                               ec,
    1620                 :             :                                                               join_relids,
    1621                 :             :                                                               outer_relids,
    1622                 :             :                                                               inner_relids);
    1623                 :             : 
    1624                 :             :         /* Recover if we failed to generate required derived clauses */
    1625         [ +  + ]:      356845 :         if (ec->ec_broken)
    1626                 :         300 :             sublist = generate_join_implied_equalities_broken(root,
    1627                 :             :                                                               ec,
    1628                 :             :                                                               nominal_join_relids,
    1629                 :             :                                                               outer_relids,
    1630                 :             :                                                               nominal_inner_relids,
    1631                 :             :                                                               inner_rel);
    1632                 :             : 
    1633                 :      356845 :         result = list_concat(result, sublist);
    1634                 :             :     }
    1635                 :             : 
    1636                 :      451646 :     return result;
    1637                 :             : }
    1638                 :             : 
    1639                 :             : /*
    1640                 :             :  * generate_join_implied_equalities_for_ecs
    1641                 :             :  *    As above, but consider only the listed ECs.
    1642                 :             :  *
    1643                 :             :  * For the sole current caller, we can assume sjinfo == NULL, that is we are
    1644                 :             :  * not interested in outer-join filter clauses.  This might need to change
    1645                 :             :  * in future.
    1646                 :             :  */
    1647                 :             : List *
    1648                 :        5909 : generate_join_implied_equalities_for_ecs(PlannerInfo *root,
    1649                 :             :                                          List *eclasses,
    1650                 :             :                                          Relids join_relids,
    1651                 :             :                                          Relids outer_relids,
    1652                 :             :                                          RelOptInfo *inner_rel)
    1653                 :             : {
    1654                 :        5909 :     List       *result = NIL;
    1655                 :        5909 :     Relids      inner_relids = inner_rel->relids;
    1656                 :             :     Relids      nominal_inner_relids;
    1657                 :             :     Relids      nominal_join_relids;
    1658                 :             :     ListCell   *lc;
    1659                 :             : 
    1660                 :             :     /* If inner rel is a child, extra setup work is needed */
    1661   [ +  +  +  -  :        5909 :     if (IS_OTHER_REL(inner_rel))
                   -  + ]
    1662                 :             :     {
    1663                 :             :         Assert(!bms_is_empty(inner_rel->top_parent_relids));
    1664                 :             : 
    1665                 :             :         /* Fetch relid set for the topmost parent rel */
    1666                 :          20 :         nominal_inner_relids = inner_rel->top_parent_relids;
    1667                 :             :         /* ECs will be marked with the parent's relid, not the child's */
    1668                 :          20 :         nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
    1669                 :             :     }
    1670                 :             :     else
    1671                 :             :     {
    1672                 :        5889 :         nominal_inner_relids = inner_relids;
    1673                 :        5889 :         nominal_join_relids = join_relids;
    1674                 :             :     }
    1675                 :             : 
    1676   [ +  -  +  +  :       12231 :     foreach(lc, eclasses)
                   +  + ]
    1677                 :             :     {
    1678                 :        6322 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
    1679                 :        6322 :         List       *sublist = NIL;
    1680                 :             : 
    1681                 :             :         /* ECs containing consts do not need any further enforcement */
    1682         [ -  + ]:        6322 :         if (ec->ec_has_const)
    1683                 :           0 :             continue;
    1684                 :             : 
    1685                 :             :         /* Single-member ECs won't generate any deductions */
    1686         [ -  + ]:        6322 :         if (list_length(ec->ec_members) <= 1)
    1687                 :           0 :             continue;
    1688                 :             : 
    1689                 :             :         /* We can quickly ignore any that don't overlap the join, too */
    1690         [ -  + ]:        6322 :         if (!bms_overlap(ec->ec_relids, nominal_join_relids))
    1691                 :           0 :             continue;
    1692                 :             : 
    1693         [ +  - ]:        6322 :         if (!ec->ec_broken)
    1694                 :        6322 :             sublist = generate_join_implied_equalities_normal(root,
    1695                 :             :                                                               ec,
    1696                 :             :                                                               join_relids,
    1697                 :             :                                                               outer_relids,
    1698                 :             :                                                               inner_relids);
    1699                 :             : 
    1700                 :             :         /* Recover if we failed to generate required derived clauses */
    1701         [ -  + ]:        6322 :         if (ec->ec_broken)
    1702                 :           0 :             sublist = generate_join_implied_equalities_broken(root,
    1703                 :             :                                                               ec,
    1704                 :             :                                                               nominal_join_relids,
    1705                 :             :                                                               outer_relids,
    1706                 :             :                                                               nominal_inner_relids,
    1707                 :             :                                                               inner_rel);
    1708                 :             : 
    1709                 :        6322 :         result = list_concat(result, sublist);
    1710                 :             :     }
    1711                 :             : 
    1712                 :        5909 :     return result;
    1713                 :             : }
    1714                 :             : 
    1715                 :             : /*
    1716                 :             :  * generate_join_implied_equalities for a still-valid EC
    1717                 :             :  */
    1718                 :             : static List *
    1719                 :      362897 : generate_join_implied_equalities_normal(PlannerInfo *root,
    1720                 :             :                                         EquivalenceClass *ec,
    1721                 :             :                                         Relids join_relids,
    1722                 :             :                                         Relids outer_relids,
    1723                 :             :                                         Relids inner_relids)
    1724                 :             : {
    1725                 :      362897 :     List       *result = NIL;
    1726                 :      362897 :     List       *new_members = NIL;
    1727                 :      362897 :     List       *outer_members = NIL;
    1728                 :      362897 :     List       *inner_members = NIL;
    1729                 :             :     EquivalenceMemberIterator it;
    1730                 :             :     EquivalenceMember *cur_em;
    1731                 :             : 
    1732                 :             :     /*
    1733                 :             :      * First, scan the EC to identify member values that are computable at the
    1734                 :             :      * outer rel, at the inner rel, or at this relation but not in either
    1735                 :             :      * input rel.  The outer-rel members should already be enforced equal,
    1736                 :             :      * likewise for the inner-rel members.  We'll need to create clauses to
    1737                 :             :      * enforce that any newly computable members are all equal to each other
    1738                 :             :      * as well as to at least one input member, plus enforce at least one
    1739                 :             :      * outer-rel member equal to at least one inner-rel member.
    1740                 :             :      */
    1741                 :      362897 :     setup_eclass_member_iterator(&it, ec, join_relids);
    1742         [ +  + ]:     1160942 :     while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
    1743                 :             :     {
    1744                 :             :         /*
    1745                 :             :          * We don't need to check explicitly for child EC members.  This test
    1746                 :             :          * against join_relids will cause them to be ignored except when
    1747                 :             :          * considering a child inner rel, which is what we want.
    1748                 :             :          */
    1749         [ +  + ]:      798045 :         if (!bms_is_subset(cur_em->em_relids, join_relids))
    1750                 :       66896 :             continue;           /* not computable yet, or wrong child */
    1751                 :             : 
    1752         [ +  + ]:      731149 :         if (bms_is_subset(cur_em->em_relids, outer_relids))
    1753                 :      408897 :             outer_members = lappend(outer_members, cur_em);
    1754         [ +  + ]:      322252 :         else if (bms_is_subset(cur_em->em_relids, inner_relids))
    1755                 :      320422 :             inner_members = lappend(inner_members, cur_em);
    1756                 :             :         else
    1757                 :        1830 :             new_members = lappend(new_members, cur_em);
    1758                 :             :     }
    1759                 :             : 
    1760                 :             :     /*
    1761                 :             :      * First, select the joinclause if needed.  We can equate any one outer
    1762                 :             :      * member to any one inner member, but we have to find a datatype
    1763                 :             :      * combination for which an opfamily member operator exists.  If we have
    1764                 :             :      * choices, we prefer simple Var members (possibly with RelabelType) since
    1765                 :             :      * these are (a) cheapest to compute at runtime and (b) most likely to
    1766                 :             :      * have useful statistics. Also, prefer operators that are also
    1767                 :             :      * hashjoinable.
    1768                 :             :      */
    1769   [ +  +  +  + ]:      362897 :     if (outer_members && inner_members)
    1770                 :             :     {
    1771                 :      308298 :         EquivalenceMember *best_outer_em = NULL;
    1772                 :      308298 :         EquivalenceMember *best_inner_em = NULL;
    1773                 :      308298 :         Oid         best_eq_op = InvalidOid;
    1774                 :      308298 :         int         best_score = -1;
    1775                 :             :         RestrictInfo *rinfo;
    1776                 :             :         ListCell   *lc1;
    1777                 :             : 
    1778   [ +  -  +  +  :      321144 :         foreach(lc1, outer_members)
                   +  + ]
    1779                 :             :         {
    1780                 :      308363 :             EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
    1781                 :             :             ListCell   *lc2;
    1782                 :             : 
    1783   [ +  -  +  +  :      321229 :             foreach(lc2, inner_members)
                   +  + ]
    1784                 :             :             {
    1785                 :      308383 :                 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
    1786                 :             :                 Oid         eq_op;
    1787                 :             :                 int         score;
    1788                 :             : 
    1789                 :      308383 :                 eq_op = select_equality_operator(ec,
    1790                 :             :                                                  outer_em->em_datatype,
    1791                 :             :                                                  inner_em->em_datatype);
    1792         [ +  + ]:      308383 :                 if (!OidIsValid(eq_op))
    1793                 :          30 :                     continue;
    1794                 :      308353 :                 score = 0;
    1795         [ +  + ]:      308353 :                 if (IsA(outer_em->em_expr, Var) ||
    1796         [ +  + ]:       17119 :                     (IsA(outer_em->em_expr, RelabelType) &&
    1797         [ +  + ]:        6316 :                      IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
    1798                 :      297429 :                     score++;
    1799         [ +  + ]:      308353 :                 if (IsA(inner_em->em_expr, Var) ||
    1800         [ +  + ]:       12405 :                     (IsA(inner_em->em_expr, RelabelType) &&
    1801         [ +  + ]:       10226 :                      IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
    1802                 :      306098 :                     score++;
    1803         [ +  + ]:      308353 :                 if (op_hashjoinable(eq_op,
    1804                 :      308353 :                                     exprType((Node *) outer_em->em_expr)))
    1805                 :      308294 :                     score++;
    1806         [ +  + ]:      308353 :                 if (score > best_score)
    1807                 :             :                 {
    1808                 :      308268 :                     best_outer_em = outer_em;
    1809                 :      308268 :                     best_inner_em = inner_em;
    1810                 :      308268 :                     best_eq_op = eq_op;
    1811                 :      308268 :                     best_score = score;
    1812         [ +  + ]:      308268 :                     if (best_score == 3)
    1813                 :      295517 :                         break;  /* no need to look further */
    1814                 :             :                 }
    1815                 :             :             }
    1816         [ +  + ]:      308363 :             if (best_score == 3)
    1817                 :      295517 :                 break;          /* no need to look further */
    1818                 :             :         }
    1819         [ +  + ]:      308298 :         if (best_score < 0)
    1820                 :             :         {
    1821                 :             :             /* failed... */
    1822                 :          30 :             ec->ec_broken = true;
    1823                 :          30 :             return NIL;
    1824                 :             :         }
    1825                 :             : 
    1826                 :             :         /*
    1827                 :             :          * Create clause, setting parent_ec to mark it as redundant with other
    1828                 :             :          * joinclauses
    1829                 :             :          */
    1830                 :      308268 :         rinfo = create_join_clause(root, ec, best_eq_op,
    1831                 :             :                                    best_outer_em, best_inner_em,
    1832                 :             :                                    ec);
    1833                 :             : 
    1834                 :      308268 :         result = lappend(result, rinfo);
    1835                 :             :     }
    1836                 :             : 
    1837                 :             :     /*
    1838                 :             :      * Now deal with building restrictions for any expressions that involve
    1839                 :             :      * Vars from both sides of the join.  We have to equate all of these to
    1840                 :             :      * each other as well as to at least one old member (if any).
    1841                 :             :      *
    1842                 :             :      * XXX as in generate_base_implied_equalities_no_const, we could be a lot
    1843                 :             :      * smarter here to avoid unnecessary failures in cross-type situations.
    1844                 :             :      * For now, use the same left-to-right method used there.
    1845                 :             :      */
    1846         [ +  + ]:      362867 :     if (new_members)
    1847                 :             :     {
    1848                 :        1800 :         List       *old_members = list_concat(outer_members, inner_members);
    1849                 :        1800 :         EquivalenceMember *prev_em = NULL;
    1850                 :             :         RestrictInfo *rinfo;
    1851                 :             :         ListCell   *lc1;
    1852                 :             : 
    1853                 :             :         /* For now, arbitrarily take the first old_member as the one to use */
    1854         [ +  + ]:        1800 :         if (old_members)
    1855                 :        1515 :             new_members = lappend(new_members, linitial(old_members));
    1856                 :             : 
    1857   [ +  -  +  +  :        5145 :         foreach(lc1, new_members)
                   +  + ]
    1858                 :             :         {
    1859                 :        3345 :             cur_em = (EquivalenceMember *) lfirst(lc1);
    1860                 :             : 
    1861         [ +  + ]:        3345 :             if (prev_em != NULL)
    1862                 :             :             {
    1863                 :             :                 Oid         eq_op;
    1864                 :             : 
    1865                 :        1545 :                 eq_op = select_equality_operator(ec,
    1866                 :             :                                                  prev_em->em_datatype,
    1867                 :             :                                                  cur_em->em_datatype);
    1868         [ -  + ]:        1545 :                 if (!OidIsValid(eq_op))
    1869                 :             :                 {
    1870                 :             :                     /* failed... */
    1871                 :           0 :                     ec->ec_broken = true;
    1872                 :           0 :                     return NIL;
    1873                 :             :                 }
    1874                 :             :                 /* do NOT set parent_ec, this qual is not redundant! */
    1875                 :        1545 :                 rinfo = create_join_clause(root, ec, eq_op,
    1876                 :             :                                            prev_em, cur_em,
    1877                 :             :                                            NULL);
    1878                 :             : 
    1879                 :        1545 :                 result = lappend(result, rinfo);
    1880                 :             :             }
    1881                 :        3345 :             prev_em = cur_em;
    1882                 :             :         }
    1883                 :             :     }
    1884                 :             : 
    1885                 :      362867 :     return result;
    1886                 :             : }
    1887                 :             : 
    1888                 :             : /*
    1889                 :             :  * generate_join_implied_equalities cleanup after failure
    1890                 :             :  *
    1891                 :             :  * Return any original RestrictInfos that are enforceable at this join.
    1892                 :             :  *
    1893                 :             :  * In the case of a child inner relation, we have to translate the
    1894                 :             :  * original RestrictInfos from parent to child Vars.
    1895                 :             :  */
    1896                 :             : static List *
    1897                 :         300 : generate_join_implied_equalities_broken(PlannerInfo *root,
    1898                 :             :                                         EquivalenceClass *ec,
    1899                 :             :                                         Relids nominal_join_relids,
    1900                 :             :                                         Relids outer_relids,
    1901                 :             :                                         Relids nominal_inner_relids,
    1902                 :             :                                         RelOptInfo *inner_rel)
    1903                 :             : {
    1904                 :         300 :     List       *result = NIL;
    1905                 :             :     ListCell   *lc;
    1906                 :             : 
    1907   [ +  -  +  +  :         820 :     foreach(lc, ec->ec_sources)
                   +  + ]
    1908                 :             :     {
    1909                 :         520 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
    1910                 :         520 :         Relids      clause_relids = restrictinfo->required_relids;
    1911                 :             : 
    1912         [ +  + ]:         520 :         if (bms_is_subset(clause_relids, nominal_join_relids) &&
    1913         [ +  + ]:         280 :             !bms_is_subset(clause_relids, outer_relids) &&
    1914         [ +  - ]:         260 :             !bms_is_subset(clause_relids, nominal_inner_relids))
    1915                 :         260 :             result = lappend(result, restrictinfo);
    1916                 :             :     }
    1917                 :             : 
    1918                 :             :     /*
    1919                 :             :      * If we have to translate, just brute-force apply adjust_appendrel_attrs
    1920                 :             :      * to all the RestrictInfos at once.  This will result in returning
    1921                 :             :      * RestrictInfos that are not included in EC's derived clauses, but there
    1922                 :             :      * shouldn't be any duplication, and it's a sufficiently narrow corner
    1923                 :             :      * case that we shouldn't sweat too much over it anyway.
    1924                 :             :      *
    1925                 :             :      * Since inner_rel might be an indirect descendant of the baserel
    1926                 :             :      * mentioned in the ec_sources clauses, we have to be prepared to apply
    1927                 :             :      * multiple levels of Var translation.
    1928                 :             :      */
    1929   [ +  +  +  -  :         300 :     if (IS_OTHER_REL(inner_rel) && result != NIL)
             -  +  +  + ]
    1930                 :         135 :         result = (List *) adjust_appendrel_attrs_multilevel(root,
    1931                 :             :                                                             (Node *) result,
    1932                 :             :                                                             inner_rel,
    1933                 :         135 :                                                             inner_rel->top_parent);
    1934                 :             : 
    1935                 :         300 :     return result;
    1936                 :             : }
    1937                 :             : 
    1938                 :             : 
    1939                 :             : /*
    1940                 :             :  * select_equality_operator
    1941                 :             :  *    Select a suitable equality operator for comparing two EC members
    1942                 :             :  *
    1943                 :             :  * Returns InvalidOid if no operator can be found for this datatype combination
    1944                 :             :  */
    1945                 :             : static Oid
    1946                 :      439009 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
    1947                 :             : {
    1948                 :             :     ListCell   *lc;
    1949                 :             : 
    1950   [ +  -  +  +  :      439064 :     foreach(lc, ec->ec_opfamilies)
                   +  + ]
    1951                 :             :     {
    1952                 :      439009 :         Oid         opfamily = lfirst_oid(lc);
    1953                 :             :         Oid         opno;
    1954                 :             : 
    1955                 :      439009 :         opno = get_opfamily_member_for_cmptype(opfamily, lefttype, righttype, COMPARE_EQ);
    1956         [ +  + ]:      439009 :         if (!OidIsValid(opno))
    1957                 :          55 :             continue;
    1958                 :             :         /* If no barrier quals in query, don't worry about leaky operators */
    1959         [ +  + ]:      438954 :         if (ec->ec_max_security == 0)
    1960                 :      438954 :             return opno;
    1961                 :             :         /* Otherwise, insist that selected operators be leakproof */
    1962         [ +  - ]:         839 :         if (get_func_leakproof(get_opcode(opno)))
    1963                 :         839 :             return opno;
    1964                 :             :     }
    1965                 :          55 :     return InvalidOid;
    1966                 :             : }
    1967                 :             : 
    1968                 :             : 
    1969                 :             : /*
    1970                 :             :  * create_join_clause
    1971                 :             :  *    Find or make a RestrictInfo comparing the two given EC members
    1972                 :             :  *    with the given operator (or, possibly, its commutator, because
    1973                 :             :  *    the ordering of the operands in the result is not guaranteed).
    1974                 :             :  *
    1975                 :             :  * parent_ec is either equal to ec (if the clause is a potentially-redundant
    1976                 :             :  * join clause) or NULL (if not).  We have to treat this as part of the
    1977                 :             :  * match requirements --- it's possible that a clause comparing the same two
    1978                 :             :  * EMs is a join clause in one join path and a restriction clause in another.
    1979                 :             :  */
    1980                 :             : static RestrictInfo *
    1981                 :      415274 : create_join_clause(PlannerInfo *root,
    1982                 :             :                    EquivalenceClass *ec, Oid opno,
    1983                 :             :                    EquivalenceMember *leftem,
    1984                 :             :                    EquivalenceMember *rightem,
    1985                 :             :                    EquivalenceClass *parent_ec)
    1986                 :             : {
    1987                 :             :     RestrictInfo *rinfo;
    1988                 :      415274 :     RestrictInfo *parent_rinfo = NULL;
    1989                 :             :     MemoryContext oldcontext;
    1990                 :             : 
    1991                 :      415274 :     rinfo = ec_search_clause_for_ems(root, ec, leftem, rightem, parent_ec);
    1992         [ +  + ]:      415274 :     if (rinfo)
    1993                 :      345704 :         return rinfo;
    1994                 :             : 
    1995                 :             :     /*
    1996                 :             :      * Not there, so build it, in planner context so we can re-use it. (Not
    1997                 :             :      * important in normal planning, but definitely so in GEQO.)
    1998                 :             :      */
    1999                 :       69570 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    2000                 :             : 
    2001                 :             :     /*
    2002                 :             :      * If either EM is a child, recursively create the corresponding
    2003                 :             :      * parent-to-parent clause, so that we can duplicate its rinfo_serial.
    2004                 :             :      */
    2005   [ +  +  +  + ]:       69570 :     if (leftem->em_is_child || rightem->em_is_child)
    2006                 :             :     {
    2007         [ +  + ]:        3679 :         EquivalenceMember *leftp = leftem->em_parent ? leftem->em_parent : leftem;
    2008         [ +  + ]:        3679 :         EquivalenceMember *rightp = rightem->em_parent ? rightem->em_parent : rightem;
    2009                 :             : 
    2010                 :        3679 :         parent_rinfo = create_join_clause(root, ec, opno,
    2011                 :             :                                           leftp, rightp,
    2012                 :             :                                           parent_ec);
    2013                 :             :     }
    2014                 :             : 
    2015                 :       69570 :     rinfo = build_implied_join_equality(root,
    2016                 :             :                                         opno,
    2017                 :             :                                         ec->ec_collation,
    2018                 :             :                                         leftem->em_expr,
    2019                 :             :                                         rightem->em_expr,
    2020                 :       69570 :                                         bms_union(leftem->em_relids,
    2021                 :       69570 :                                                   rightem->em_relids),
    2022                 :             :                                         ec->ec_min_security);
    2023                 :             : 
    2024                 :             :     /*
    2025                 :             :      * If either EM is a child, force the clause's clause_relids to include
    2026                 :             :      * the relid(s) of the child rel.  In normal cases it would already, but
    2027                 :             :      * not if we are considering appendrel child relations with pseudoconstant
    2028                 :             :      * translated variables (i.e., UNION ALL sub-selects with constant output
    2029                 :             :      * items).  We must do this so that join_clause_is_movable_into() will
    2030                 :             :      * think that the clause should be evaluated at the correct place.
    2031                 :             :      */
    2032         [ +  + ]:       69570 :     if (leftem->em_is_child)
    2033                 :        3208 :         rinfo->clause_relids = bms_add_members(rinfo->clause_relids,
    2034                 :        3208 :                                                leftem->em_relids);
    2035         [ +  + ]:       69570 :     if (rightem->em_is_child)
    2036                 :         471 :         rinfo->clause_relids = bms_add_members(rinfo->clause_relids,
    2037                 :         471 :                                                rightem->em_relids);
    2038                 :             : 
    2039                 :             :     /* If it's a child clause, copy the parent's rinfo_serial */
    2040         [ +  + ]:       69570 :     if (parent_rinfo)
    2041                 :        3679 :         rinfo->rinfo_serial = parent_rinfo->rinfo_serial;
    2042                 :             : 
    2043                 :             :     /* Mark the clause as redundant, or not */
    2044                 :       69570 :     rinfo->parent_ec = parent_ec;
    2045                 :             : 
    2046                 :             :     /*
    2047                 :             :      * We know the correct values for left_ec/right_ec, ie this particular EC,
    2048                 :             :      * so we can just set them directly instead of forcing another lookup.
    2049                 :             :      */
    2050                 :       69570 :     rinfo->left_ec = ec;
    2051                 :       69570 :     rinfo->right_ec = ec;
    2052                 :             : 
    2053                 :             :     /* Mark it as usable with these EMs */
    2054                 :       69570 :     rinfo->left_em = leftem;
    2055                 :       69570 :     rinfo->right_em = rightem;
    2056                 :             :     /* and save it for possible re-use */
    2057                 :       69570 :     ec_add_derived_clause(ec, rinfo);
    2058                 :             : 
    2059                 :       69570 :     MemoryContextSwitchTo(oldcontext);
    2060                 :             : 
    2061                 :       69570 :     return rinfo;
    2062                 :             : }
    2063                 :             : 
    2064                 :             : 
    2065                 :             : /*
    2066                 :             :  * reconsider_outer_join_clauses
    2067                 :             :  *    Re-examine any outer-join clauses that were set aside by
    2068                 :             :  *    distribute_qual_to_rels(), and see if we can derive any
    2069                 :             :  *    EquivalenceClasses from them.  Then, if they were not made
    2070                 :             :  *    redundant, push them out into the regular join-clause lists.
    2071                 :             :  *
    2072                 :             :  * When we have mergejoinable clauses A = B that are outer-join clauses,
    2073                 :             :  * we can't blindly combine them with other clauses A = C to deduce B = C,
    2074                 :             :  * since in fact the "equality" A = B won't necessarily hold above the
    2075                 :             :  * outer join (one of the variables might be NULL instead).  Nonetheless
    2076                 :             :  * there are cases where we can add qual clauses using transitivity.
    2077                 :             :  *
    2078                 :             :  * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
    2079                 :             :  * for which there is also an equivalence clause OUTERVAR = CONSTANT.
    2080                 :             :  * It is safe and useful to push a clause INNERVAR = CONSTANT into the
    2081                 :             :  * evaluation of the inner (nullable) relation, because any inner rows not
    2082                 :             :  * meeting this condition will not contribute to the outer-join result anyway.
    2083                 :             :  * (Any outer rows they could join to will be eliminated by the pushed-down
    2084                 :             :  * equivalence clause.)
    2085                 :             :  *
    2086                 :             :  * Note that the above rule does not work for full outer joins; nor is it
    2087                 :             :  * very interesting to consider cases where the generated equivalence clause
    2088                 :             :  * would involve relations outside the outer join, since such clauses couldn't
    2089                 :             :  * be pushed into the inner side's scan anyway.  So the restriction to
    2090                 :             :  * outervar = pseudoconstant is not really giving up anything.
    2091                 :             :  *
    2092                 :             :  * For full-join cases, we can only do something useful if it's a FULL JOIN
    2093                 :             :  * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
    2094                 :             :  * By the time it gets here, the merged column will look like
    2095                 :             :  *      COALESCE(LEFTVAR, RIGHTVAR)
    2096                 :             :  * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
    2097                 :             :  * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
    2098                 :             :  * and RIGHTVAR = CONSTANT into the input relations, since any rows not
    2099                 :             :  * meeting these conditions cannot contribute to the join result.
    2100                 :             :  *
    2101                 :             :  * Again, there isn't any traction to be gained by trying to deal with
    2102                 :             :  * clauses comparing a mergedvar to a non-pseudoconstant.  So we can make
    2103                 :             :  * use of the EquivalenceClasses to search for matching variables that were
    2104                 :             :  * equivalenced to constants.  The interesting outer-join clauses were
    2105                 :             :  * accumulated for us by distribute_qual_to_rels.
    2106                 :             :  *
    2107                 :             :  * When we find one of these cases, we implement the changes we want by
    2108                 :             :  * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
    2109                 :             :  * and pushing it into the EquivalenceClass structures.  This is because we
    2110                 :             :  * may already know that INNERVAR is equivalenced to some other var(s), and
    2111                 :             :  * we'd like the constant to propagate to them too.  Note that it would be
    2112                 :             :  * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
    2113                 :             :  * that could result in propagating constant restrictions from
    2114                 :             :  * INNERVAR to OUTERVAR, which would be very wrong.
    2115                 :             :  *
    2116                 :             :  * It's possible that the INNERVAR is also an OUTERVAR for some other
    2117                 :             :  * outer-join clause, in which case the process can be repeated.  So we repeat
    2118                 :             :  * looping over the lists of clauses until no further deductions can be made.
    2119                 :             :  * Whenever we do make a deduction, we remove the generating clause from the
    2120                 :             :  * lists, since we don't want to make the same deduction twice.
    2121                 :             :  *
    2122                 :             :  * If we don't find any match for a set-aside outer join clause, we must
    2123                 :             :  * throw it back into the regular joinclause processing by passing it to
    2124                 :             :  * distribute_restrictinfo_to_rels().  If we do generate a derived clause,
    2125                 :             :  * however, the outer-join clause is redundant.  We must still put some
    2126                 :             :  * clause into the regular processing, because otherwise the join will be
    2127                 :             :  * seen as a clauseless join and avoided during join order searching.
    2128                 :             :  * We handle this by generating a constant-TRUE clause that is marked with
    2129                 :             :  * the same required_relids etc as the removed outer-join clause, thus
    2130                 :             :  * making it a join clause between the correct relations.
    2131                 :             :  */
    2132                 :             : void
    2133                 :      257712 : reconsider_outer_join_clauses(PlannerInfo *root)
    2134                 :             : {
    2135                 :             :     bool        found;
    2136                 :             :     ListCell   *cell;
    2137                 :             : 
    2138                 :             :     /* Outer loop repeats until we find no more deductions */
    2139                 :             :     do
    2140                 :             :     {
    2141                 :      259364 :         found = false;
    2142                 :             : 
    2143                 :             :         /* Process the LEFT JOIN clauses */
    2144   [ +  +  +  +  :      281787 :         foreach(cell, root->left_join_clauses)
                   +  + ]
    2145                 :             :         {
    2146                 :       22423 :             OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2147                 :             : 
    2148         [ +  + ]:       22423 :             if (reconsider_outer_join_clause(root, ojcinfo, true))
    2149                 :             :             {
    2150                 :         517 :                 RestrictInfo *rinfo = ojcinfo->rinfo;
    2151                 :             : 
    2152                 :         517 :                 found = true;
    2153                 :             :                 /* remove it from the list */
    2154                 :         517 :                 root->left_join_clauses =
    2155                 :         517 :                     foreach_delete_current(root->left_join_clauses, cell);
    2156                 :             :                 /* throw back a dummy replacement clause (see notes above) */
    2157                 :         517 :                 rinfo = make_restrictinfo(root,
    2158                 :         517 :                                           (Expr *) makeBoolConst(true, false),
    2159                 :         517 :                                           rinfo->is_pushed_down,
    2160                 :         517 :                                           rinfo->has_clone,
    2161                 :         517 :                                           rinfo->is_clone,
    2162                 :             :                                           false,    /* pseudoconstant */
    2163                 :             :                                           0,    /* security_level */
    2164                 :             :                                           rinfo->required_relids,
    2165                 :             :                                           rinfo->incompatible_relids,
    2166                 :             :                                           rinfo->outer_relids);
    2167                 :         517 :                 distribute_restrictinfo_to_rels(root, rinfo);
    2168                 :             :             }
    2169                 :             :         }
    2170                 :             : 
    2171                 :             :         /* Process the RIGHT JOIN clauses */
    2172   [ +  +  +  +  :      288518 :         foreach(cell, root->right_join_clauses)
                   +  + ]
    2173                 :             :         {
    2174                 :       29154 :             OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2175                 :             : 
    2176         [ +  + ]:       29154 :             if (reconsider_outer_join_clause(root, ojcinfo, false))
    2177                 :             :             {
    2178                 :        1140 :                 RestrictInfo *rinfo = ojcinfo->rinfo;
    2179                 :             : 
    2180                 :        1140 :                 found = true;
    2181                 :             :                 /* remove it from the list */
    2182                 :        1140 :                 root->right_join_clauses =
    2183                 :        1140 :                     foreach_delete_current(root->right_join_clauses, cell);
    2184                 :             :                 /* throw back a dummy replacement clause (see notes above) */
    2185                 :        1140 :                 rinfo = make_restrictinfo(root,
    2186                 :        1140 :                                           (Expr *) makeBoolConst(true, false),
    2187                 :        1140 :                                           rinfo->is_pushed_down,
    2188                 :        1140 :                                           rinfo->has_clone,
    2189                 :        1140 :                                           rinfo->is_clone,
    2190                 :             :                                           false,    /* pseudoconstant */
    2191                 :             :                                           0,    /* security_level */
    2192                 :             :                                           rinfo->required_relids,
    2193                 :             :                                           rinfo->incompatible_relids,
    2194                 :             :                                           rinfo->outer_relids);
    2195                 :        1140 :                 distribute_restrictinfo_to_rels(root, rinfo);
    2196                 :             :             }
    2197                 :             :         }
    2198                 :             : 
    2199                 :             :         /* Process the FULL JOIN clauses */
    2200   [ +  +  +  +  :      260409 :         foreach(cell, root->full_join_clauses)
                   +  + ]
    2201                 :             :         {
    2202                 :        1045 :             OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2203                 :             : 
    2204         [ +  + ]:        1045 :             if (reconsider_full_join_clause(root, ojcinfo))
    2205                 :             :             {
    2206                 :           5 :                 RestrictInfo *rinfo = ojcinfo->rinfo;
    2207                 :             : 
    2208                 :           5 :                 found = true;
    2209                 :             :                 /* remove it from the list */
    2210                 :           5 :                 root->full_join_clauses =
    2211                 :           5 :                     foreach_delete_current(root->full_join_clauses, cell);
    2212                 :             :                 /* throw back a dummy replacement clause (see notes above) */
    2213                 :           5 :                 rinfo = make_restrictinfo(root,
    2214                 :           5 :                                           (Expr *) makeBoolConst(true, false),
    2215                 :           5 :                                           rinfo->is_pushed_down,
    2216                 :           5 :                                           rinfo->has_clone,
    2217                 :           5 :                                           rinfo->is_clone,
    2218                 :             :                                           false,    /* pseudoconstant */
    2219                 :             :                                           0,    /* security_level */
    2220                 :             :                                           rinfo->required_relids,
    2221                 :             :                                           rinfo->incompatible_relids,
    2222                 :             :                                           rinfo->outer_relids);
    2223                 :           5 :                 distribute_restrictinfo_to_rels(root, rinfo);
    2224                 :             :             }
    2225                 :             :         }
    2226         [ +  + ]:      259364 :     } while (found);
    2227                 :             : 
    2228                 :             :     /* Now, any remaining clauses have to be thrown back */
    2229   [ +  +  +  +  :      279302 :     foreach(cell, root->left_join_clauses)
                   +  + ]
    2230                 :             :     {
    2231                 :       21590 :         OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2232                 :             : 
    2233                 :       21590 :         distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
    2234                 :             :     }
    2235   [ +  +  +  +  :      284539 :     foreach(cell, root->right_join_clauses)
                   +  + ]
    2236                 :             :     {
    2237                 :       26827 :         OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2238                 :             : 
    2239                 :       26827 :         distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
    2240                 :             :     }
    2241   [ +  +  +  +  :      258752 :     foreach(cell, root->full_join_clauses)
                   +  + ]
    2242                 :             :     {
    2243                 :        1040 :         OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
    2244                 :             : 
    2245                 :        1040 :         distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
    2246                 :             :     }
    2247                 :      257712 : }
    2248                 :             : 
    2249                 :             : /*
    2250                 :             :  * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
    2251                 :             :  *
    2252                 :             :  * Returns true if we were able to propagate a constant through the clause.
    2253                 :             :  */
    2254                 :             : static bool
    2255                 :       51577 : reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
    2256                 :             :                              bool outer_on_left)
    2257                 :             : {
    2258                 :       51577 :     RestrictInfo *rinfo = ojcinfo->rinfo;
    2259                 :       51577 :     SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
    2260                 :             :     Expr       *outervar,
    2261                 :             :                *innervar;
    2262                 :             :     Oid         opno,
    2263                 :             :                 collation,
    2264                 :             :                 left_type,
    2265                 :             :                 right_type,
    2266                 :             :                 inner_datatype;
    2267                 :             :     Relids      inner_relids;
    2268                 :             :     ListCell   *lc1;
    2269                 :             : 
    2270                 :             :     Assert(is_opclause(rinfo->clause));
    2271                 :       51577 :     opno = ((OpExpr *) rinfo->clause)->opno;
    2272                 :       51577 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    2273                 :             : 
    2274                 :             :     /* Extract needed info from the clause */
    2275                 :       51577 :     op_input_types(opno, &left_type, &right_type);
    2276         [ +  + ]:       51577 :     if (outer_on_left)
    2277                 :             :     {
    2278                 :       22423 :         outervar = (Expr *) get_leftop(rinfo->clause);
    2279                 :       22423 :         innervar = (Expr *) get_rightop(rinfo->clause);
    2280                 :       22423 :         inner_datatype = right_type;
    2281                 :       22423 :         inner_relids = rinfo->right_relids;
    2282                 :             :     }
    2283                 :             :     else
    2284                 :             :     {
    2285                 :       29154 :         outervar = (Expr *) get_rightop(rinfo->clause);
    2286                 :       29154 :         innervar = (Expr *) get_leftop(rinfo->clause);
    2287                 :       29154 :         inner_datatype = left_type;
    2288                 :       29154 :         inner_relids = rinfo->left_relids;
    2289                 :             :     }
    2290                 :             : 
    2291                 :             :     /* Scan EquivalenceClasses for a match to outervar */
    2292   [ +  -  +  +  :      313975 :     foreach(lc1, root->eq_classes)
                   +  + ]
    2293                 :             :     {
    2294                 :      264055 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    2295                 :             :         bool        match;
    2296                 :             :         ListCell   *lc2;
    2297                 :             : 
    2298                 :             :         /* We don't expect any children yet */
    2299                 :             :         Assert(cur_ec->ec_childmembers == NULL);
    2300                 :             : 
    2301                 :             :         /* Ignore EC unless it contains pseudoconstants */
    2302         [ +  + ]:      264055 :         if (!cur_ec->ec_has_const)
    2303                 :      204909 :             continue;
    2304                 :             :         /* Never match to a volatile EC */
    2305         [ -  + ]:       59146 :         if (cur_ec->ec_has_volatile)
    2306                 :           0 :             continue;
    2307                 :             :         /* It has to match the outer-join clause as to semantics, too */
    2308         [ +  + ]:       59146 :         if (collation != cur_ec->ec_collation)
    2309                 :        3860 :             continue;
    2310         [ +  + ]:       55286 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    2311                 :       10132 :             continue;
    2312                 :             :         /* Does it contain a match to outervar? */
    2313                 :       45154 :         match = false;
    2314   [ +  -  +  +  :      143738 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
    2315                 :             :         {
    2316                 :      100241 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    2317                 :             : 
    2318                 :             :             /* Child members should not exist in ec_members */
    2319                 :             :             Assert(!cur_em->em_is_child);
    2320         [ +  + ]:      100241 :             if (equal(outervar, cur_em->em_expr))
    2321                 :             :             {
    2322                 :        1657 :                 match = true;
    2323                 :        1657 :                 break;
    2324                 :             :             }
    2325                 :             :         }
    2326         [ +  + ]:       45154 :         if (!match)
    2327                 :       43497 :             continue;           /* no match, so ignore this EC */
    2328                 :             : 
    2329                 :             :         /*
    2330                 :             :          * Yes it does!  Try to generate a clause INNERVAR = CONSTANT for each
    2331                 :             :          * CONSTANT in the EC.  Note that we must succeed with at least one
    2332                 :             :          * constant before we can decide to throw away the outer-join clause.
    2333                 :             :          */
    2334                 :        1657 :         match = false;
    2335   [ +  -  +  +  :        5864 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
    2336                 :             :         {
    2337                 :        4207 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    2338                 :             :             Oid         eq_op;
    2339                 :             :             RestrictInfo *newrinfo;
    2340                 :             :             JoinDomain *jdomain;
    2341                 :             : 
    2342         [ +  + ]:        4207 :             if (!cur_em->em_is_const)
    2343                 :        2515 :                 continue;       /* ignore non-const members */
    2344                 :        1692 :             eq_op = select_equality_operator(cur_ec,
    2345                 :             :                                              inner_datatype,
    2346                 :             :                                              cur_em->em_datatype);
    2347         [ -  + ]:        1692 :             if (!OidIsValid(eq_op))
    2348                 :           0 :                 continue;       /* can't generate equality */
    2349                 :        1692 :             newrinfo = build_implied_join_equality(root,
    2350                 :             :                                                    eq_op,
    2351                 :             :                                                    cur_ec->ec_collation,
    2352                 :             :                                                    innervar,
    2353                 :             :                                                    cur_em->em_expr,
    2354                 :             :                                                    bms_copy(inner_relids),
    2355                 :             :                                                    cur_ec->ec_min_security);
    2356                 :             :             /* This equality holds within the OJ's child JoinDomain */
    2357                 :        1692 :             jdomain = find_join_domain(root, sjinfo->syn_righthand);
    2358         [ +  - ]:        1692 :             if (process_equivalence(root, &newrinfo, jdomain))
    2359                 :        1692 :                 match = true;
    2360                 :             :         }
    2361                 :             : 
    2362                 :             :         /*
    2363                 :             :          * If we were able to equate INNERVAR to any constant, report success.
    2364                 :             :          * Otherwise, fall out of the search loop, since we know the OUTERVAR
    2365                 :             :          * appears in at most one EC.
    2366                 :             :          */
    2367         [ +  - ]:        1657 :         if (match)
    2368                 :        1657 :             return true;
    2369                 :             :         else
    2370                 :           0 :             break;
    2371                 :             :     }
    2372                 :             : 
    2373                 :       49920 :     return false;               /* failed to make any deduction */
    2374                 :             : }
    2375                 :             : 
    2376                 :             : /*
    2377                 :             :  * reconsider_outer_join_clauses for a single FULL JOIN clause
    2378                 :             :  *
    2379                 :             :  * Returns true if we were able to propagate a constant through the clause.
    2380                 :             :  */
    2381                 :             : static bool
    2382                 :        1045 : reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
    2383                 :             : {
    2384                 :        1045 :     RestrictInfo *rinfo = ojcinfo->rinfo;
    2385                 :        1045 :     SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
    2386                 :        1045 :     Relids      fjrelids = bms_make_singleton(sjinfo->ojrelid);
    2387                 :             :     Expr       *leftvar;
    2388                 :             :     Expr       *rightvar;
    2389                 :             :     Oid         opno,
    2390                 :             :                 collation,
    2391                 :             :                 left_type,
    2392                 :             :                 right_type;
    2393                 :             :     Relids      left_relids,
    2394                 :             :                 right_relids;
    2395                 :             :     ListCell   *lc1;
    2396                 :             : 
    2397                 :             :     /* Extract needed info from the clause */
    2398                 :             :     Assert(is_opclause(rinfo->clause));
    2399                 :        1045 :     opno = ((OpExpr *) rinfo->clause)->opno;
    2400                 :        1045 :     collation = ((OpExpr *) rinfo->clause)->inputcollid;
    2401                 :        1045 :     op_input_types(opno, &left_type, &right_type);
    2402                 :        1045 :     leftvar = (Expr *) get_leftop(rinfo->clause);
    2403                 :        1045 :     rightvar = (Expr *) get_rightop(rinfo->clause);
    2404                 :        1045 :     left_relids = rinfo->left_relids;
    2405                 :        1045 :     right_relids = rinfo->right_relids;
    2406                 :             : 
    2407   [ +  -  +  +  :        5305 :     foreach(lc1, root->eq_classes)
                   +  + ]
    2408                 :             :     {
    2409                 :        4265 :         EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
    2410                 :        4265 :         EquivalenceMember *coal_em = NULL;
    2411                 :             :         bool        match;
    2412                 :             :         bool        matchleft;
    2413                 :             :         bool        matchright;
    2414                 :             :         ListCell   *lc2;
    2415                 :        4265 :         int         coal_idx = -1;
    2416                 :             : 
    2417                 :             :         /* We don't expect any children yet */
    2418                 :             :         Assert(cur_ec->ec_childmembers == NULL);
    2419                 :             : 
    2420                 :             :         /* Ignore EC unless it contains pseudoconstants */
    2421         [ +  + ]:        4265 :         if (!cur_ec->ec_has_const)
    2422                 :        4015 :             continue;
    2423                 :             :         /* Never match to a volatile EC */
    2424         [ -  + ]:         250 :         if (cur_ec->ec_has_volatile)
    2425                 :           0 :             continue;
    2426                 :             :         /* It has to match the outer-join clause as to semantics, too */
    2427         [ +  + ]:         250 :         if (collation != cur_ec->ec_collation)
    2428                 :          30 :             continue;
    2429         [ -  + ]:         220 :         if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
    2430                 :           0 :             continue;
    2431                 :             : 
    2432                 :             :         /*
    2433                 :             :          * Does it contain a COALESCE(leftvar, rightvar) construct?
    2434                 :             :          *
    2435                 :             :          * We can assume the COALESCE() inputs are in the same order as the
    2436                 :             :          * join clause, since both were automatically generated in the cases
    2437                 :             :          * we care about.
    2438                 :             :          *
    2439                 :             :          * XXX currently this may fail to match in cross-type cases because
    2440                 :             :          * the COALESCE will contain typecast operations while the join clause
    2441                 :             :          * may not (if there is a cross-type mergejoin operator available for
    2442                 :             :          * the two column types). Is it OK to strip implicit coercions from
    2443                 :             :          * the COALESCE arguments?
    2444                 :             :          */
    2445                 :         220 :         match = false;
    2446   [ +  -  +  +  :         645 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
    2447                 :             :         {
    2448                 :         430 :             coal_em = (EquivalenceMember *) lfirst(lc2);
    2449                 :             : 
    2450                 :             :             /* Child members should not exist in ec_members */
    2451                 :             :             Assert(!coal_em->em_is_child);
    2452         [ +  + ]:         430 :             if (IsA(coal_em->em_expr, CoalesceExpr))
    2453                 :             :             {
    2454                 :          15 :                 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
    2455                 :             :                 Node       *cfirst;
    2456                 :             :                 Node       *csecond;
    2457                 :             : 
    2458         [ -  + ]:          15 :                 if (list_length(cexpr->args) != 2)
    2459                 :           0 :                     continue;
    2460                 :          15 :                 cfirst = (Node *) linitial(cexpr->args);
    2461                 :          15 :                 csecond = (Node *) lsecond(cexpr->args);
    2462                 :             : 
    2463                 :             :                 /*
    2464                 :             :                  * The COALESCE arguments will be marked as possibly nulled by
    2465                 :             :                  * the full join, while we wish to generate clauses that apply
    2466                 :             :                  * to the join's inputs.  So we must strip the join from the
    2467                 :             :                  * nullingrels fields of cfirst/csecond before comparing them
    2468                 :             :                  * to leftvar/rightvar.  (Perhaps with a less hokey
    2469                 :             :                  * representation for FULL JOIN USING output columns, this
    2470                 :             :                  * wouldn't be needed?)
    2471                 :             :                  */
    2472                 :          15 :                 cfirst = remove_nulling_relids(cfirst, fjrelids, NULL);
    2473                 :          15 :                 csecond = remove_nulling_relids(csecond, fjrelids, NULL);
    2474                 :             : 
    2475   [ +  +  +  - ]:          15 :                 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
    2476                 :             :                 {
    2477                 :           5 :                     coal_idx = foreach_current_index(lc2);
    2478                 :           5 :                     match = true;
    2479                 :           5 :                     break;
    2480                 :             :                 }
    2481                 :             :             }
    2482                 :             :         }
    2483         [ +  + ]:         220 :         if (!match)
    2484                 :         215 :             continue;           /* no match, so ignore this EC */
    2485                 :             : 
    2486                 :             :         /*
    2487                 :             :          * Yes it does!  Try to generate clauses LEFTVAR = CONSTANT and
    2488                 :             :          * RIGHTVAR = CONSTANT for each CONSTANT in the EC.  Note that we must
    2489                 :             :          * succeed with at least one constant for each var before we can
    2490                 :             :          * decide to throw away the outer-join clause.
    2491                 :             :          */
    2492                 :           5 :         matchleft = matchright = false;
    2493   [ +  -  +  +  :          15 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
    2494                 :             :         {
    2495                 :          10 :             EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
    2496                 :             :             Oid         eq_op;
    2497                 :             :             RestrictInfo *newrinfo;
    2498                 :             :             JoinDomain *jdomain;
    2499                 :             : 
    2500         [ +  + ]:          10 :             if (!cur_em->em_is_const)
    2501                 :           5 :                 continue;       /* ignore non-const members */
    2502                 :           5 :             eq_op = select_equality_operator(cur_ec,
    2503                 :             :                                              left_type,
    2504                 :             :                                              cur_em->em_datatype);
    2505         [ +  - ]:           5 :             if (OidIsValid(eq_op))
    2506                 :             :             {
    2507                 :           5 :                 newrinfo = build_implied_join_equality(root,
    2508                 :             :                                                        eq_op,
    2509                 :             :                                                        cur_ec->ec_collation,
    2510                 :             :                                                        leftvar,
    2511                 :             :                                                        cur_em->em_expr,
    2512                 :             :                                                        bms_copy(left_relids),
    2513                 :             :                                                        cur_ec->ec_min_security);
    2514                 :             :                 /* This equality holds within the lefthand child JoinDomain */
    2515                 :           5 :                 jdomain = find_join_domain(root, sjinfo->syn_lefthand);
    2516         [ +  - ]:           5 :                 if (process_equivalence(root, &newrinfo, jdomain))
    2517                 :           5 :                     matchleft = true;
    2518                 :             :             }
    2519                 :           5 :             eq_op = select_equality_operator(cur_ec,
    2520                 :             :                                              right_type,
    2521                 :             :                                              cur_em->em_datatype);
    2522         [ +  - ]:           5 :             if (OidIsValid(eq_op))
    2523                 :             :             {
    2524                 :           5 :                 newrinfo = build_implied_join_equality(root,
    2525                 :             :                                                        eq_op,
    2526                 :             :                                                        cur_ec->ec_collation,
    2527                 :             :                                                        rightvar,
    2528                 :             :                                                        cur_em->em_expr,
    2529                 :             :                                                        bms_copy(right_relids),
    2530                 :             :                                                        cur_ec->ec_min_security);
    2531                 :             :                 /* This equality holds within the righthand child JoinDomain */
    2532                 :           5 :                 jdomain = find_join_domain(root, sjinfo->syn_righthand);
    2533         [ +  - ]:           5 :                 if (process_equivalence(root, &newrinfo, jdomain))
    2534                 :           5 :                     matchright = true;
    2535                 :             :             }
    2536                 :             :         }
    2537                 :             : 
    2538                 :             :         /*
    2539                 :             :          * If we were able to equate both vars to constants, we're done, and
    2540                 :             :          * we can throw away the full-join clause as redundant.  Moreover, we
    2541                 :             :          * can remove the COALESCE entry from the EC, since the added
    2542                 :             :          * restrictions ensure it will always have the expected value. (We
    2543                 :             :          * don't bother trying to update ec_relids or ec_sources.)
    2544                 :             :          */
    2545   [ +  -  +  - ]:           5 :         if (matchleft && matchright)
    2546                 :             :         {
    2547                 :           5 :             cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
    2548                 :           5 :             return true;
    2549                 :             :         }
    2550                 :             : 
    2551                 :             :         /*
    2552                 :             :          * Otherwise, fall out of the search loop, since we know the COALESCE
    2553                 :             :          * appears in at most one EC (XXX might stop being true if we allow
    2554                 :             :          * stripping of coercions above?)
    2555                 :             :          */
    2556                 :           0 :         break;
    2557                 :             :     }
    2558                 :             : 
    2559                 :        1040 :     return false;               /* failed to make any deduction */
    2560                 :             : }
    2561                 :             : 
    2562                 :             : /*
    2563                 :             :  * find_join_domain
    2564                 :             :  *    Find the highest JoinDomain enclosed within the given relid set.
    2565                 :             :  *
    2566                 :             :  * (We could avoid this search at the cost of complicating APIs elsewhere,
    2567                 :             :  * which doesn't seem worth it.)
    2568                 :             :  */
    2569                 :             : static JoinDomain *
    2570                 :        1702 : find_join_domain(PlannerInfo *root, Relids relids)
    2571                 :             : {
    2572                 :             :     ListCell   *lc;
    2573                 :             : 
    2574   [ +  -  +  -  :        3491 :     foreach(lc, root->join_domains)
                   +  - ]
    2575                 :             :     {
    2576                 :        3491 :         JoinDomain *jdomain = (JoinDomain *) lfirst(lc);
    2577                 :             : 
    2578         [ +  + ]:        3491 :         if (bms_is_subset(jdomain->jd_relids, relids))
    2579                 :        1702 :             return jdomain;
    2580                 :             :     }
    2581         [ #  # ]:           0 :     elog(ERROR, "failed to find appropriate JoinDomain");
    2582                 :             :     return NULL;                /* keep compiler quiet */
    2583                 :             : }
    2584                 :             : 
    2585                 :             : 
    2586                 :             : /*
    2587                 :             :  * exprs_known_equal
    2588                 :             :  *    Detect whether two expressions are known equal due to equivalence
    2589                 :             :  *    relationships.
    2590                 :             :  *
    2591                 :             :  * If opfamily is given, the expressions must be known equal per the semantics
    2592                 :             :  * of that opfamily (note it has to be a btree opfamily, since those are the
    2593                 :             :  * only opfamilies equivclass.c deals with).  If opfamily is InvalidOid, we'll
    2594                 :             :  * return true if they're equal according to any opfamily, which is fuzzy but
    2595                 :             :  * OK for estimation purposes.
    2596                 :             :  *
    2597                 :             :  * Note: does not bother to check for "equal(item1, item2)"; caller must
    2598                 :             :  * check that case if it's possible to pass identical items.
    2599                 :             :  */
    2600                 :             : bool
    2601                 :       25396 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
    2602                 :             : {
    2603                 :             :     ListCell   *lc1;
    2604                 :             : 
    2605   [ +  +  +  +  :      195323 :     foreach(lc1, root->eq_classes)
                   +  + ]
    2606                 :             :     {
    2607                 :      172763 :         EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
    2608                 :      172763 :         bool        item1member = false;
    2609                 :      172763 :         bool        item2member = false;
    2610                 :             :         ListCell   *lc2;
    2611                 :             : 
    2612                 :             :         /* Never match to a volatile EC */
    2613         [ -  + ]:      172763 :         if (ec->ec_has_volatile)
    2614                 :           0 :             continue;
    2615                 :             : 
    2616                 :             :         /*
    2617                 :             :          * It's okay to consider ec_broken ECs here.  Brokenness just means we
    2618                 :             :          * couldn't derive all the implied clauses we'd have liked to; it does
    2619                 :             :          * not invalidate our knowledge that the members are equal.
    2620                 :             :          */
    2621                 :             : 
    2622                 :             :         /* Ignore if this EC doesn't use specified opfamily */
    2623         [ +  + ]:      172763 :         if (OidIsValid(opfamily) &&
    2624         [ +  + ]:         550 :             !list_member_oid(ec->ec_opfamilies, opfamily))
    2625                 :         190 :             continue;
    2626                 :             : 
    2627                 :             :         /* Ignore children here */
    2628   [ +  -  +  +  :      413209 :         foreach(lc2, ec->ec_members)
                   +  + ]
    2629                 :             :         {
    2630                 :      243472 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2631                 :             : 
    2632                 :             :             /* Child members should not exist in ec_members */
    2633                 :             :             Assert(!em->em_is_child);
    2634         [ +  + ]:      243472 :             if (equal(item1, em->em_expr))
    2635                 :       12976 :                 item1member = true;
    2636         [ +  + ]:      230496 :             else if (equal(item2, em->em_expr))
    2637                 :       20959 :                 item2member = true;
    2638                 :             :             /* Exit as soon as equality is proven */
    2639   [ +  +  +  + ]:      243472 :             if (item1member && item2member)
    2640                 :        2836 :                 return true;
    2641                 :             :         }
    2642                 :             :     }
    2643                 :       22560 :     return false;
    2644                 :             : }
    2645                 :             : 
    2646                 :             : 
    2647                 :             : /*
    2648                 :             :  * match_eclasses_to_foreign_key_col
    2649                 :             :  *    See whether a foreign key column match is proven by any eclass.
    2650                 :             :  *
    2651                 :             :  * If the referenced and referencing Vars of the fkey's colno'th column are
    2652                 :             :  * known equal due to any eclass, return that eclass; otherwise return NULL.
    2653                 :             :  * (In principle there might be more than one matching eclass if multiple
    2654                 :             :  * collations are involved, but since collation doesn't matter for equality,
    2655                 :             :  * we ignore that fine point here.)  This is much like exprs_known_equal,
    2656                 :             :  * except for the format of the input.
    2657                 :             :  *
    2658                 :             :  * On success, we also set fkinfo->eclass[colno] to the matching eclass,
    2659                 :             :  * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
    2660                 :             :  * referencing Var.
    2661                 :             :  */
    2662                 :             : EquivalenceClass *
    2663                 :        2191 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
    2664                 :             :                                   ForeignKeyOptInfo *fkinfo,
    2665                 :             :                                   int colno)
    2666                 :             : {
    2667                 :        2191 :     Index       var1varno = fkinfo->con_relid;
    2668                 :        2191 :     AttrNumber  var1attno = fkinfo->conkey[colno];
    2669                 :        2191 :     Index       var2varno = fkinfo->ref_relid;
    2670                 :        2191 :     AttrNumber  var2attno = fkinfo->confkey[colno];
    2671                 :        2191 :     Oid         eqop = fkinfo->conpfeqop[colno];
    2672                 :        2191 :     RelOptInfo *rel1 = root->simple_rel_array[var1varno];
    2673                 :        2191 :     RelOptInfo *rel2 = root->simple_rel_array[var2varno];
    2674                 :        2191 :     List       *opfamilies = NIL;   /* compute only if needed */
    2675                 :             :     Bitmapset  *matching_ecs;
    2676                 :             :     int         i;
    2677                 :             : 
    2678                 :             :     /* Consider only eclasses mentioning both relations */
    2679                 :             :     Assert(root->ec_merging_done);
    2680                 :             :     Assert(IS_SIMPLE_REL(rel1));
    2681                 :             :     Assert(IS_SIMPLE_REL(rel2));
    2682                 :        2191 :     matching_ecs = bms_intersect(rel1->eclass_indexes,
    2683                 :        2191 :                                  rel2->eclass_indexes);
    2684                 :             : 
    2685                 :        2191 :     i = -1;
    2686         [ +  + ]:        2271 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2687                 :             :     {
    2688                 :         653 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    2689                 :             :                                                              i);
    2690                 :         653 :         EquivalenceMember *item1_em = NULL;
    2691                 :         653 :         EquivalenceMember *item2_em = NULL;
    2692                 :             :         ListCell   *lc2;
    2693                 :             : 
    2694                 :             :         /* Never match to a volatile EC */
    2695         [ -  + ]:         653 :         if (ec->ec_has_volatile)
    2696                 :           0 :             continue;
    2697                 :             : 
    2698                 :             :         /*
    2699                 :             :          * It's okay to consider "broken" ECs here, see exprs_known_equal.
    2700                 :             :          * Ignore children here.
    2701                 :             :          */
    2702   [ +  -  +  +  :        1511 :         foreach(lc2, ec->ec_members)
                   +  + ]
    2703                 :             :         {
    2704                 :        1431 :             EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
    2705                 :             :             Var        *var;
    2706                 :             : 
    2707                 :             :             /* Child members should not exist in ec_members */
    2708                 :             :             Assert(!em->em_is_child);
    2709                 :             : 
    2710                 :             :             /* EM must be a Var, possibly with RelabelType */
    2711                 :        1431 :             var = (Var *) em->em_expr;
    2712   [ +  -  -  + ]:        1431 :             while (var && IsA(var, RelabelType))
    2713                 :           0 :                 var = (Var *) ((RelabelType *) var)->arg;
    2714   [ +  -  +  + ]:        1431 :             if (!(var && IsA(var, Var)))
    2715                 :          15 :                 continue;
    2716                 :             : 
    2717                 :             :             /* Match? */
    2718   [ +  +  +  + ]:        1416 :             if (var->varno == var1varno && var->varattno == var1attno)
    2719                 :         573 :                 item1_em = em;
    2720   [ +  +  +  + ]:         843 :             else if (var->varno == var2varno && var->varattno == var2attno)
    2721                 :         573 :                 item2_em = em;
    2722                 :             : 
    2723                 :             :             /* Have we found both PK and FK column in this EC? */
    2724   [ +  +  +  + ]:        1416 :             if (item1_em && item2_em)
    2725                 :             :             {
    2726                 :             :                 /*
    2727                 :             :                  * Succeed if eqop matches EC's opfamilies.  We could test
    2728                 :             :                  * this before scanning the members, but it's probably cheaper
    2729                 :             :                  * to test for member matches first.
    2730                 :             :                  */
    2731         [ +  - ]:         573 :                 if (opfamilies == NIL)  /* compute if we didn't already */
    2732                 :         573 :                     opfamilies = get_mergejoin_opfamilies(eqop);
    2733         [ +  - ]:         573 :                 if (equal(opfamilies, ec->ec_opfamilies))
    2734                 :             :                 {
    2735                 :         573 :                     fkinfo->eclass[colno] = ec;
    2736                 :         573 :                     fkinfo->fk_eclass_member[colno] = item2_em;
    2737                 :         573 :                     return ec;
    2738                 :             :                 }
    2739                 :             :                 /* Otherwise, done with this EC, move on to the next */
    2740                 :           0 :                 break;
    2741                 :             :             }
    2742                 :             :         }
    2743                 :             :     }
    2744                 :        1618 :     return NULL;
    2745                 :             : }
    2746                 :             : 
    2747                 :             : /*
    2748                 :             :  * find_derived_clause_for_ec_member
    2749                 :             :  *    Search for a previously-derived clause mentioning the given EM.
    2750                 :             :  *
    2751                 :             :  * The eclass should be an ec_has_const EC, of which the EM is a non-const
    2752                 :             :  * member.  This should ensure there is just one derived clause mentioning
    2753                 :             :  * the EM (and equating it to a constant).
    2754                 :             :  * Returns NULL if no such clause can be found.
    2755                 :             :  */
    2756                 :             : RestrictInfo *
    2757                 :           5 : find_derived_clause_for_ec_member(PlannerInfo *root,
    2758                 :             :                                   EquivalenceClass *ec,
    2759                 :             :                                   EquivalenceMember *em)
    2760                 :             : {
    2761                 :             :     Assert(ec->ec_has_const);
    2762                 :             :     Assert(!em->em_is_const);
    2763                 :             : 
    2764                 :           5 :     return ec_search_derived_clause_for_ems(root, ec, em, NULL, NULL);
    2765                 :             : }
    2766                 :             : 
    2767                 :             : 
    2768                 :             : /*
    2769                 :             :  * add_child_rel_equivalences
    2770                 :             :  *    Search for EC members that reference the root parent of child_rel, and
    2771                 :             :  *    add transformed members referencing the child_rel.
    2772                 :             :  *
    2773                 :             :  * Note that this function won't be called at all unless we have at least some
    2774                 :             :  * reason to believe that the EC members it generates will be useful.
    2775                 :             :  *
    2776                 :             :  * parent_rel and child_rel could be derived from appinfo, but since the
    2777                 :             :  * caller has already computed them, we might as well just pass them in.
    2778                 :             :  *
    2779                 :             :  * The passed-in AppendRelInfo is not used when the parent_rel is not a
    2780                 :             :  * top-level baserel, since it shows the mapping from the parent_rel but
    2781                 :             :  * we need to translate EC expressions that refer to the top-level parent.
    2782                 :             :  * Using it is faster than using adjust_appendrel_attrs_multilevel(), though,
    2783                 :             :  * so we prefer it when we can.
    2784                 :             :  */
    2785                 :             : void
    2786                 :       28738 : add_child_rel_equivalences(PlannerInfo *root,
    2787                 :             :                            AppendRelInfo *appinfo,
    2788                 :             :                            RelOptInfo *parent_rel,
    2789                 :             :                            RelOptInfo *child_rel)
    2790                 :             : {
    2791                 :       28738 :     Relids      top_parent_relids = child_rel->top_parent_relids;
    2792                 :       28738 :     Relids      child_relids = child_rel->relids;
    2793                 :             :     int         i;
    2794                 :             : 
    2795                 :             :     /*
    2796                 :             :      * EC merging should be complete already, so we can use the parent rel's
    2797                 :             :      * eclass_indexes to avoid searching all of root->eq_classes.
    2798                 :             :      */
    2799                 :             :     Assert(root->ec_merging_done);
    2800                 :             :     Assert(IS_SIMPLE_REL(parent_rel));
    2801                 :             : 
    2802                 :       28738 :     i = -1;
    2803         [ +  + ]:       81900 :     while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
    2804                 :             :     {
    2805                 :       53162 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2806                 :             : 
    2807                 :             :         /*
    2808                 :             :          * If this EC contains a volatile expression, then generating child
    2809                 :             :          * EMs would be downright dangerous, so skip it.  We rely on a
    2810                 :             :          * volatile EC having only one EM.
    2811                 :             :          */
    2812         [ -  + ]:       53162 :         if (cur_ec->ec_has_volatile)
    2813                 :           0 :             continue;
    2814                 :             : 
    2815                 :             :         /* Sanity check eclass_indexes only contain ECs for parent_rel */
    2816                 :             :         Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
    2817                 :             : 
    2818   [ +  -  +  +  :      182062 :         foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
                   +  + ]
    2819                 :             :         {
    2820         [ +  + ]:       75738 :             if (cur_em->em_is_const)
    2821                 :        2762 :                 continue;       /* ignore consts here */
    2822                 :             : 
    2823                 :             :             /* Child members should not exist in ec_members */
    2824                 :             :             Assert(!cur_em->em_is_child);
    2825                 :             : 
    2826                 :             :             /*
    2827                 :             :              * Consider only members that reference and can be computed at
    2828                 :             :              * child's topmost parent rel.  In particular we want to exclude
    2829                 :             :              * parent-rel Vars that have nonempty varnullingrels.  Translating
    2830                 :             :              * those might fail, if the transformed expression wouldn't be a
    2831                 :             :              * simple Var; and in any case it wouldn't produce a member that
    2832                 :             :              * has any use in creating plans for the child rel.
    2833                 :             :              */
    2834         [ +  + ]:       72976 :             if (bms_is_subset(cur_em->em_relids, top_parent_relids) &&
    2835         [ +  - ]:       51253 :                 !bms_is_empty(cur_em->em_relids))
    2836                 :             :             {
    2837                 :             :                 /* OK, generate transformed child version */
    2838                 :             :                 Expr       *child_expr;
    2839                 :             :                 Relids      new_relids;
    2840                 :             : 
    2841         [ +  + ]:       51253 :                 if (parent_rel->reloptkind == RELOPT_BASEREL)
    2842                 :             :                 {
    2843                 :             :                     /* Simple single-level transformation */
    2844                 :             :                     child_expr = (Expr *)
    2845                 :       44056 :                         adjust_appendrel_attrs(root,
    2846                 :       44056 :                                                (Node *) cur_em->em_expr,
    2847                 :             :                                                1, &appinfo);
    2848                 :             :                 }
    2849                 :             :                 else
    2850                 :             :                 {
    2851                 :             :                     /* Must do multi-level transformation */
    2852                 :             :                     child_expr = (Expr *)
    2853                 :        7197 :                         adjust_appendrel_attrs_multilevel(root,
    2854                 :        7197 :                                                           (Node *) cur_em->em_expr,
    2855                 :             :                                                           child_rel,
    2856                 :        7197 :                                                           child_rel->top_parent);
    2857                 :             :                 }
    2858                 :             : 
    2859                 :             :                 /*
    2860                 :             :                  * Transform em_relids to match.  Note we do *not* do
    2861                 :             :                  * pull_varnos(child_expr) here, as for example the
    2862                 :             :                  * transformation might have substituted a constant, but we
    2863                 :             :                  * don't want the child member to be marked as constant.
    2864                 :             :                  */
    2865                 :       51253 :                 new_relids = bms_difference(cur_em->em_relids,
    2866                 :             :                                             top_parent_relids);
    2867                 :       51253 :                 new_relids = bms_add_members(new_relids, child_relids);
    2868                 :             : 
    2869                 :       51253 :                 add_child_eq_member(root,
    2870                 :             :                                     cur_ec,
    2871                 :             :                                     i,
    2872                 :             :                                     child_expr,
    2873                 :             :                                     new_relids,
    2874                 :             :                                     cur_em->em_jdomain,
    2875                 :             :                                     cur_em,
    2876                 :             :                                     cur_em->em_datatype,
    2877                 :             :                                     child_rel->relid);
    2878                 :             :             }
    2879                 :             :         }
    2880                 :             :     }
    2881                 :       28738 : }
    2882                 :             : 
    2883                 :             : /*
    2884                 :             :  * add_child_join_rel_equivalences
    2885                 :             :  *    Like add_child_rel_equivalences(), but for joinrels
    2886                 :             :  *
    2887                 :             :  * Here we find the ECs relevant to the top parent joinrel and add transformed
    2888                 :             :  * member expressions that refer to this child joinrel.
    2889                 :             :  *
    2890                 :             :  * Note that this function won't be called at all unless we have at least some
    2891                 :             :  * reason to believe that the EC members it generates will be useful.
    2892                 :             :  */
    2893                 :             : void
    2894                 :       14885 : add_child_join_rel_equivalences(PlannerInfo *root,
    2895                 :             :                                 int nappinfos, AppendRelInfo **appinfos,
    2896                 :             :                                 RelOptInfo *parent_joinrel,
    2897                 :             :                                 RelOptInfo *child_joinrel)
    2898                 :             : {
    2899                 :       14885 :     Relids      top_parent_relids = child_joinrel->top_parent_relids;
    2900                 :       14885 :     Relids      child_relids = child_joinrel->relids;
    2901                 :             :     Bitmapset  *matching_ecs;
    2902                 :             :     MemoryContext oldcontext;
    2903                 :             :     int         i;
    2904                 :             : 
    2905                 :             :     Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
    2906                 :             : 
    2907                 :             :     /* We need consider only ECs that mention the parent joinrel */
    2908                 :       14885 :     matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
    2909                 :             : 
    2910                 :             :     /*
    2911                 :             :      * If we're being called during GEQO join planning, we still have to
    2912                 :             :      * create any new EC members in the main planner context, to avoid having
    2913                 :             :      * a corrupt EC data structure after the GEQO context is reset.  This is
    2914                 :             :      * problematic since we'll leak memory across repeated GEQO cycles.  For
    2915                 :             :      * now, though, bloat is better than crash.  If it becomes a real issue
    2916                 :             :      * we'll have to do something to avoid generating duplicate EC members.
    2917                 :             :      */
    2918                 :       14885 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    2919                 :             : 
    2920                 :       14885 :     i = -1;
    2921         [ +  + ]:       39801 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    2922                 :             :     {
    2923                 :       24916 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    2924                 :             : 
    2925                 :             :         /*
    2926                 :             :          * If this EC contains a volatile expression, then generating child
    2927                 :             :          * EMs would be downright dangerous, so skip it.  We rely on a
    2928                 :             :          * volatile EC having only one EM.
    2929                 :             :          */
    2930         [ -  + ]:       24916 :         if (cur_ec->ec_has_volatile)
    2931                 :           0 :             continue;
    2932                 :             : 
    2933                 :             :         /* Sanity check on get_eclass_indexes_for_relids result */
    2934                 :             :         Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
    2935                 :             : 
    2936   [ +  -  +  +  :       92622 :         foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
                   +  + ]
    2937                 :             :         {
    2938         [ +  + ]:       42790 :             if (cur_em->em_is_const)
    2939                 :        1898 :                 continue;       /* ignore consts here */
    2940                 :             : 
    2941                 :             :             /* Child members should not exist in ec_members */
    2942                 :             :             Assert(!cur_em->em_is_child);
    2943                 :             : 
    2944                 :             :             /*
    2945                 :             :              * We may ignore expressions that reference a single baserel,
    2946                 :             :              * because add_child_rel_equivalences should have handled them.
    2947                 :             :              */
    2948         [ +  + ]:       40892 :             if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
    2949                 :       38715 :                 continue;
    2950                 :             : 
    2951                 :             :             /* Does this member reference child's topmost parent rel? */
    2952         [ +  - ]:        2177 :             if (bms_overlap(cur_em->em_relids, top_parent_relids))
    2953                 :             :             {
    2954                 :             :                 /* Yes, generate transformed child version */
    2955                 :             :                 Expr       *child_expr;
    2956                 :             :                 Relids      new_relids;
    2957                 :             : 
    2958         [ +  + ]:        2177 :                 if (parent_joinrel->reloptkind == RELOPT_JOINREL)
    2959                 :             :                 {
    2960                 :             :                     /* Simple single-level transformation */
    2961                 :             :                     child_expr = (Expr *)
    2962                 :        2097 :                         adjust_appendrel_attrs(root,
    2963                 :        2097 :                                                (Node *) cur_em->em_expr,
    2964                 :             :                                                nappinfos, appinfos);
    2965                 :             :                 }
    2966                 :             :                 else
    2967                 :             :                 {
    2968                 :             :                     /* Must do multi-level transformation */
    2969                 :             :                     Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
    2970                 :             :                     child_expr = (Expr *)
    2971                 :          80 :                         adjust_appendrel_attrs_multilevel(root,
    2972                 :          80 :                                                           (Node *) cur_em->em_expr,
    2973                 :             :                                                           child_joinrel,
    2974                 :          80 :                                                           child_joinrel->top_parent);
    2975                 :             :                 }
    2976                 :             : 
    2977                 :             :                 /*
    2978                 :             :                  * Transform em_relids to match.  Note we do *not* do
    2979                 :             :                  * pull_varnos(child_expr) here, as for example the
    2980                 :             :                  * transformation might have substituted a constant, but we
    2981                 :             :                  * don't want the child member to be marked as constant.
    2982                 :             :                  */
    2983                 :        2177 :                 new_relids = bms_difference(cur_em->em_relids,
    2984                 :             :                                             top_parent_relids);
    2985                 :        2177 :                 new_relids = bms_add_members(new_relids, child_relids);
    2986                 :             : 
    2987                 :             :                 /*
    2988                 :             :                  * Add new child member to the EquivalenceClass.  Because this
    2989                 :             :                  * is a RELOPT_OTHER_JOINREL which has multiple component
    2990                 :             :                  * relids, there is no ideal place to store these members in
    2991                 :             :                  * the class.  Ordinarily, child members are stored in the
    2992                 :             :                  * ec_childmembers[] array element corresponding to their
    2993                 :             :                  * relid, however, here we have multiple component relids, so
    2994                 :             :                  * there's no single ec_childmembers[] array element to store
    2995                 :             :                  * this member.  So that we still correctly find this member
    2996                 :             :                  * in loops iterating over an EquivalenceMemberIterator, we
    2997                 :             :                  * opt to store the member in the ec_childmembers array in
    2998                 :             :                  * only the first component relid slot of the array.  This
    2999                 :             :                  * allows the member to be found, providing callers of
    3000                 :             :                  * setup_eclass_member_iterator() specify all the component
    3001                 :             :                  * relids for the RELOPT_OTHER_JOINREL, which they do.  If we
    3002                 :             :                  * opted to store the member in each ec_childmembers[] element
    3003                 :             :                  * for all the component relids, then that would just result
    3004                 :             :                  * in eclass_member_iterator_next() finding the member
    3005                 :             :                  * multiple times, which is a waste of effort.
    3006                 :             :                  */
    3007                 :        2177 :                 add_child_eq_member(root,
    3008                 :             :                                     cur_ec,
    3009                 :             :                                     -1,
    3010                 :             :                                     child_expr,
    3011                 :             :                                     new_relids,
    3012                 :             :                                     cur_em->em_jdomain,
    3013                 :             :                                     cur_em,
    3014                 :             :                                     cur_em->em_datatype,
    3015                 :        2177 :                                     bms_next_member(child_joinrel->relids, -1));
    3016                 :             :             }
    3017                 :             :         }
    3018                 :             :     }
    3019                 :             : 
    3020                 :       14885 :     MemoryContextSwitchTo(oldcontext);
    3021                 :       14885 : }
    3022                 :             : 
    3023                 :             : /*
    3024                 :             :  * add_setop_child_rel_equivalences
    3025                 :             :  *      Add equivalence members for each non-resjunk target in 'child_tlist'
    3026                 :             :  *      to the EquivalenceClass in the corresponding setop_pathkey's pk_eclass.
    3027                 :             :  *
    3028                 :             :  * 'root' is the PlannerInfo belonging to the top-level set operation.
    3029                 :             :  * 'child_rel' is the RelOptInfo of the child relation we're adding
    3030                 :             :  * EquivalenceMembers for.
    3031                 :             :  * 'child_tlist' is the target list for the setop child relation.  The target
    3032                 :             :  * list expressions are what we add as EquivalenceMembers.
    3033                 :             :  * 'setop_pathkeys' is a list of PathKeys which must contain an entry for each
    3034                 :             :  * non-resjunk target in 'child_tlist'.
    3035                 :             :  */
    3036                 :             : void
    3037                 :       10328 : add_setop_child_rel_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
    3038                 :             :                                  List *child_tlist, List *setop_pathkeys)
    3039                 :             : {
    3040                 :             :     ListCell   *lc;
    3041                 :       10328 :     ListCell   *lc2 = list_head(setop_pathkeys);
    3042                 :             : 
    3043   [ +  -  +  +  :       41072 :     foreach(lc, child_tlist)
                   +  + ]
    3044                 :             :     {
    3045                 :       30744 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
    3046                 :             :         EquivalenceMember *parent_em;
    3047                 :             :         PathKey    *pk;
    3048                 :             : 
    3049         [ -  + ]:       30744 :         if (tle->resjunk)
    3050                 :           0 :             continue;
    3051                 :             : 
    3052         [ -  + ]:       30744 :         if (lc2 == NULL)
    3053         [ #  # ]:           0 :             elog(ERROR, "too few pathkeys for set operation");
    3054                 :             : 
    3055                 :       30744 :         pk = lfirst_node(PathKey, lc2);
    3056                 :       30744 :         parent_em = linitial(pk->pk_eclass->ec_members);
    3057                 :             : 
    3058                 :             :         /*
    3059                 :             :          * We can safely pass the parent member as the first member in the
    3060                 :             :          * ec_members list as this is added first in generate_union_paths,
    3061                 :             :          * likewise, the JoinDomain can be that of the initial member of the
    3062                 :             :          * Pathkey's EquivalenceClass.  We pass -1 for ec_index since we
    3063                 :             :          * maintain the eclass_indexes for the child_rel after the loop.
    3064                 :             :          */
    3065                 :       30744 :         add_child_eq_member(root,
    3066                 :             :                             pk->pk_eclass,
    3067                 :             :                             -1,
    3068                 :             :                             tle->expr,
    3069                 :             :                             child_rel->relids,
    3070                 :             :                             parent_em->em_jdomain,
    3071                 :             :                             parent_em,
    3072                 :       30744 :                             exprType((Node *) tle->expr),
    3073                 :             :                             child_rel->relid);
    3074                 :             : 
    3075                 :       30744 :         lc2 = lnext(setop_pathkeys, lc2);
    3076                 :             :     }
    3077                 :             : 
    3078                 :             :     /*
    3079                 :             :      * transformSetOperationStmt() ensures that the targetlist never contains
    3080                 :             :      * any resjunk columns, so all eclasses that exist in 'root' must have
    3081                 :             :      * received a new member in the loop above.  Add them to the child_rel's
    3082                 :             :      * eclass_indexes.
    3083                 :             :      */
    3084                 :       10328 :     child_rel->eclass_indexes = bms_add_range(child_rel->eclass_indexes, 0,
    3085                 :       10328 :                                               list_length(root->eq_classes) - 1);
    3086                 :       10328 : }
    3087                 :             : 
    3088                 :             : /*
    3089                 :             :  * setup_eclass_member_iterator
    3090                 :             :  *    Setup an EquivalenceMemberIterator 'it' to iterate over all parent
    3091                 :             :  *    EquivalenceMembers and child members belonging to the given 'ec'.
    3092                 :             :  *
    3093                 :             :  * This iterator returns:
    3094                 :             :  *  - All parent members stored directly in ec_members for 'ec', and;
    3095                 :             :  *  - Any child member added to the given ec by add_child_eq_member() where
    3096                 :             :  *    the child_relid specified in the add_child_eq_member() call is a member
    3097                 :             :  *    of the 'child_relids' parameter.
    3098                 :             :  *
    3099                 :             :  * Note:
    3100                 :             :  * The given 'child_relids' must remain allocated and not be changed for the
    3101                 :             :  * lifetime of the iterator.
    3102                 :             :  *
    3103                 :             :  * Parameters:
    3104                 :             :  *  'it' is a pointer to the iterator to set up.  Normally stack allocated.
    3105                 :             :  *  'ec' is the EquivalenceClass from which to iterate members for.
    3106                 :             :  *  'child_relids' is the relids to return child members for.
    3107                 :             :  */
    3108                 :             : void
    3109                 :     4000962 : setup_eclass_member_iterator(EquivalenceMemberIterator *it,
    3110                 :             :                              EquivalenceClass *ec, Relids child_relids)
    3111                 :             : {
    3112                 :     4000962 :     it->ec = ec;
    3113                 :             :     /* no need to set this if the class has no child members array set */
    3114         [ +  + ]:     4000962 :     it->child_relids = ec->ec_childmembers != NULL ? child_relids : NULL;
    3115                 :     4000962 :     it->current_relid = -1;
    3116                 :     4000962 :     it->current_list = ec->ec_members;
    3117                 :     4000962 :     it->current_cell = list_head(it->current_list);
    3118                 :     4000962 : }
    3119                 :             : 
    3120                 :             : /*
    3121                 :             :  * eclass_member_iterator_next
    3122                 :             :  *    Get the next EquivalenceMember from the EquivalenceMemberIterator 'it',
    3123                 :             :  *    as setup by setup_eclass_member_iterator().  NULL is returned if there
    3124                 :             :  *    are no members left, after which callers must not call
    3125                 :             :  *    eclass_member_iterator_next() again for the given iterator.
    3126                 :             :  */
    3127                 :             : EquivalenceMember *
    3128                 :     9341757 : eclass_member_iterator_next(EquivalenceMemberIterator *it)
    3129                 :             : {
    3130         [ +  - ]:     9341757 :     while (it->current_list != NULL)
    3131                 :             :     {
    3132         [ +  + ]:     9341757 :         while (it->current_cell != NULL)
    3133                 :             :         {
    3134                 :             :             EquivalenceMember *em;
    3135                 :             : 
    3136                 :     6469383 :     nextcell:
    3137                 :     6578065 :             em = lfirst_node(EquivalenceMember, it->current_cell);
    3138                 :     6578065 :             it->current_cell = lnext(it->current_list, it->current_cell);
    3139                 :     6578065 :             return em;
    3140                 :             :         }
    3141                 :             : 
    3142                 :             :         /* Search for the next list to return members from */
    3143         [ +  + ]:     2988248 :         while ((it->current_relid = bms_next_member(it->child_relids, it->current_relid)) > 0)
    3144                 :             :         {
    3145                 :             :             /*
    3146                 :             :              * Be paranoid in case we're given relids above what we've sized
    3147                 :             :              * the ec_childmembers array to.
    3148                 :             :              */
    3149         [ -  + ]:      224556 :             if (it->current_relid >= it->ec->ec_childmembers_size)
    3150                 :           0 :                 return NULL;
    3151                 :             : 
    3152                 :      224556 :             it->current_list = it->ec->ec_childmembers[it->current_relid];
    3153                 :             : 
    3154                 :             :             /* If there are members in this list, use it. */
    3155         [ +  + ]:      224556 :             if (it->current_list != NIL)
    3156                 :             :             {
    3157                 :             :                 /* point current_cell to the head of this list */
    3158                 :      108682 :                 it->current_cell = list_head(it->current_list);
    3159                 :      108682 :                 goto nextcell;
    3160                 :             :             }
    3161                 :             :         }
    3162                 :     2763692 :         return NULL;
    3163                 :             :     }
    3164                 :             : 
    3165                 :           0 :     return NULL;
    3166                 :             : }
    3167                 :             : 
    3168                 :             : /*
    3169                 :             :  * generate_implied_equalities_for_column
    3170                 :             :  *    Create EC-derived joinclauses usable with a specific column.
    3171                 :             :  *
    3172                 :             :  * This is used by indxpath.c to extract potentially indexable joinclauses
    3173                 :             :  * from ECs, and can be used by foreign data wrappers for similar purposes.
    3174                 :             :  * We assume that only expressions in Vars of a single table are of interest,
    3175                 :             :  * but the caller provides a callback function to identify exactly which
    3176                 :             :  * such expressions it would like to know about.
    3177                 :             :  *
    3178                 :             :  * We assume that any given table/index column could appear in only one EC.
    3179                 :             :  * (This should be true in all but the most pathological cases, and if it
    3180                 :             :  * isn't, we stop on the first match anyway.)  Therefore, what we return
    3181                 :             :  * is a redundant list of clauses equating the table/index column to each of
    3182                 :             :  * the other-relation values it is known to be equal to.  Any one of
    3183                 :             :  * these clauses can be used to create a parameterized path, and there
    3184                 :             :  * is no value in using more than one.  (But it *is* worthwhile to create
    3185                 :             :  * a separate parameterized path for each one, since that leads to different
    3186                 :             :  * join orders.)
    3187                 :             :  *
    3188                 :             :  * The caller can pass a Relids set of rels we aren't interested in joining
    3189                 :             :  * to, so as to save the work of creating useless clauses.
    3190                 :             :  */
    3191                 :             : List *
    3192                 :      471280 : generate_implied_equalities_for_column(PlannerInfo *root,
    3193                 :             :                                        RelOptInfo *rel,
    3194                 :             :                                        ec_matches_callback_type callback,
    3195                 :             :                                        void *callback_arg,
    3196                 :             :                                        Relids prohibited_rels)
    3197                 :             : {
    3198                 :      471280 :     List       *result = NIL;
    3199                 :      471280 :     bool        is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
    3200                 :             :     Relids      parent_relids;
    3201                 :             :     int         i;
    3202                 :             : 
    3203                 :             :     /* Should be OK to rely on eclass_indexes */
    3204                 :             :     Assert(root->ec_merging_done);
    3205                 :             : 
    3206                 :             :     /* Indexes are available only on base or "other" member relations. */
    3207                 :             :     Assert(IS_SIMPLE_REL(rel));
    3208                 :             : 
    3209                 :             :     /* If it's a child rel, we'll need to know what its parent(s) are */
    3210         [ +  + ]:      471280 :     if (is_child_rel)
    3211                 :       10172 :         parent_relids = find_childrel_parents(root, rel);
    3212                 :             :     else
    3213                 :      461108 :         parent_relids = NULL;   /* not used, but keep compiler quiet */
    3214                 :             : 
    3215                 :      471280 :     i = -1;
    3216         [ +  + ]:     1353638 :     while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
    3217                 :             :     {
    3218                 :      978939 :         EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
    3219                 :             :         EquivalenceMemberIterator it;
    3220                 :             :         EquivalenceMember *cur_em;
    3221                 :             :         ListCell   *lc2;
    3222                 :             : 
    3223                 :             :         /* Sanity check eclass_indexes only contain ECs for rel */
    3224                 :             :         Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
    3225                 :             : 
    3226                 :             :         /*
    3227                 :             :          * Won't generate joinclauses if const or single-member (the latter
    3228                 :             :          * test covers the volatile case too)
    3229                 :             :          */
    3230   [ +  +  +  + ]:      978939 :         if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
    3231                 :      882198 :             continue;
    3232                 :             : 
    3233                 :             :         /*
    3234                 :             :          * Scan members, looking for a match to the target column.  Note that
    3235                 :             :          * child EC members are considered, but only when they belong to the
    3236                 :             :          * target relation.  (Unlike regular members, the same expression
    3237                 :             :          * could be a child member of more than one EC.  Therefore, it's
    3238                 :             :          * potentially order-dependent which EC a child relation's target
    3239                 :             :          * column gets matched to.  This is annoying but it only happens in
    3240                 :             :          * corner cases, so for now we live with just reporting the first
    3241                 :             :          * match.  See also get_eclass_for_sort_expr.)
    3242                 :             :          */
    3243                 :      463494 :         setup_eclass_member_iterator(&it, cur_ec, rel->relids);
    3244         [ +  + ]:     1741483 :         while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
    3245                 :             :         {
    3246   [ +  +  +  + ]:     1374986 :             if (bms_equal(cur_em->em_relids, rel->relids) &&
    3247                 :      463750 :                 callback(root, rel, cur_ec, cur_em, callback_arg))
    3248                 :       96741 :                 break;
    3249                 :             :         }
    3250                 :             : 
    3251         [ +  + ]:      463494 :         if (!cur_em)
    3252                 :      366753 :             continue;
    3253                 :             : 
    3254                 :             :         /*
    3255                 :             :          * Found our match.  Scan the other EC members and attempt to generate
    3256                 :             :          * joinclauses.  Ignore children here.
    3257                 :             :          */
    3258   [ +  -  +  +  :      295549 :         foreach(lc2, cur_ec->ec_members)
                   +  + ]
    3259                 :             :         {
    3260                 :      198808 :             EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
    3261                 :             :             Oid         eq_op;
    3262                 :             :             RestrictInfo *rinfo;
    3263                 :             : 
    3264                 :             :             /* Child members should not exist in ec_members */
    3265                 :             :             Assert(!other_em->em_is_child);
    3266                 :             : 
    3267                 :             :             /* Make sure it'll be a join to a different rel */
    3268   [ +  +  +  + ]:      303602 :             if (other_em == cur_em ||
    3269                 :      104794 :                 bms_overlap(other_em->em_relids, rel->relids))
    3270                 :       94099 :                 continue;
    3271                 :             : 
    3272                 :             :             /* Forget it if caller doesn't want joins to this rel */
    3273         [ +  + ]:      104709 :             if (bms_overlap(other_em->em_relids, prohibited_rels))
    3274                 :         130 :                 continue;
    3275                 :             : 
    3276                 :             :             /*
    3277                 :             :              * Also, if this is a child rel, avoid generating a useless join
    3278                 :             :              * to its parent rel(s).
    3279                 :             :              */
    3280   [ +  +  +  + ]:      110650 :             if (is_child_rel &&
    3281                 :        6071 :                 bms_overlap(parent_relids, other_em->em_relids))
    3282                 :        2797 :                 continue;
    3283                 :             : 
    3284                 :      101782 :             eq_op = select_equality_operator(cur_ec,
    3285                 :             :                                              cur_em->em_datatype,
    3286                 :             :                                              other_em->em_datatype);
    3287         [ -  + ]:      101782 :             if (!OidIsValid(eq_op))
    3288                 :           0 :                 continue;
    3289                 :             : 
    3290                 :             :             /* set parent_ec to mark as redundant with other joinclauses */
    3291                 :      101782 :             rinfo = create_join_clause(root, cur_ec, eq_op,
    3292                 :             :                                        cur_em, other_em,
    3293                 :             :                                        cur_ec);
    3294                 :             : 
    3295                 :      101782 :             result = lappend(result, rinfo);
    3296                 :             :         }
    3297                 :             : 
    3298                 :             :         /*
    3299                 :             :          * If somehow we failed to create any join clauses, we might as well
    3300                 :             :          * keep scanning the ECs for another match.  But if we did make any,
    3301                 :             :          * we're done, because we don't want to return non-redundant clauses.
    3302                 :             :          */
    3303         [ +  + ]:       96741 :         if (result)
    3304                 :       96581 :             break;
    3305                 :             :     }
    3306                 :             : 
    3307                 :      471280 :     return result;
    3308                 :             : }
    3309                 :             : 
    3310                 :             : /*
    3311                 :             :  * have_relevant_eclass_joinclause
    3312                 :             :  *      Detect whether there is an EquivalenceClass that could produce
    3313                 :             :  *      a joinclause involving the two given relations.
    3314                 :             :  *
    3315                 :             :  * This is essentially a very cut-down version of
    3316                 :             :  * generate_join_implied_equalities().  Note it's OK to occasionally say "yes"
    3317                 :             :  * incorrectly.  Hence we don't bother with details like whether the lack of a
    3318                 :             :  * cross-type operator might prevent the clause from actually being generated.
    3319                 :             :  * False negatives are not always fatal either: they will discourage, but not
    3320                 :             :  * completely prevent, investigation of particular join pathways.
    3321                 :             :  */
    3322                 :             : bool
    3323                 :      170450 : have_relevant_eclass_joinclause(PlannerInfo *root,
    3324                 :             :                                 RelOptInfo *rel1, RelOptInfo *rel2)
    3325                 :             : {
    3326                 :             :     Bitmapset  *matching_ecs;
    3327                 :             :     int         i;
    3328                 :             : 
    3329                 :             :     /*
    3330                 :             :      * Examine only eclasses mentioning both rel1 and rel2.
    3331                 :             :      *
    3332                 :             :      * Note that we do not consider the possibility of an eclass generating
    3333                 :             :      * "join" clauses that mention just one of the rels plus an outer join
    3334                 :             :      * that could be formed from them.  Although such clauses must be
    3335                 :             :      * correctly enforced when we form the outer join, they don't seem like
    3336                 :             :      * sufficient reason to prioritize this join over other ones.  The join
    3337                 :             :      * ordering rules will force the join to be made when necessary.
    3338                 :             :      */
    3339                 :      170450 :     matching_ecs = get_common_eclass_indexes(root, rel1->relids,
    3340                 :             :                                              rel2->relids);
    3341                 :             : 
    3342                 :      170450 :     i = -1;
    3343         [ +  + ]:      170540 :     while ((i = bms_next_member(matching_ecs, i)) >= 0)
    3344                 :             :     {
    3345                 :      145506 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    3346                 :             :                                                              i);
    3347                 :             : 
    3348                 :             :         /*
    3349                 :             :          * Sanity check that get_common_eclass_indexes gave only ECs
    3350                 :             :          * containing both rels.
    3351                 :             :          */
    3352                 :             :         Assert(bms_overlap(rel1->relids, ec->ec_relids));
    3353                 :             :         Assert(bms_overlap(rel2->relids, ec->ec_relids));
    3354                 :             : 
    3355                 :             :         /*
    3356                 :             :          * Won't generate joinclauses if single-member (this test covers the
    3357                 :             :          * volatile case too)
    3358                 :             :          */
    3359         [ +  + ]:      145506 :         if (list_length(ec->ec_members) <= 1)
    3360                 :          90 :             continue;
    3361                 :             : 
    3362                 :             :         /*
    3363                 :             :          * We do not need to examine the individual members of the EC, because
    3364                 :             :          * all that we care about is whether each rel overlaps the relids of
    3365                 :             :          * at least one member, and get_common_eclass_indexes() and the single
    3366                 :             :          * member check above are sufficient to prove that.  (As with
    3367                 :             :          * have_relevant_joinclause(), it is not necessary that the EC be able
    3368                 :             :          * to form a joinclause relating exactly the two given rels, only that
    3369                 :             :          * it be able to form a joinclause mentioning both, and this will
    3370                 :             :          * surely be true if both of them overlap ec_relids.)
    3371                 :             :          *
    3372                 :             :          * Note we don't test ec_broken; if we did, we'd need a separate code
    3373                 :             :          * path to look through ec_sources.  Checking the membership anyway is
    3374                 :             :          * OK as a possibly-overoptimistic heuristic.
    3375                 :             :          *
    3376                 :             :          * We don't test ec_has_const either, even though a const eclass won't
    3377                 :             :          * generate real join clauses.  This is because if we had "WHERE a.x =
    3378                 :             :          * b.y and a.x = 42", it is worth considering a join between a and b,
    3379                 :             :          * since the join result is likely to be small even though it'll end
    3380                 :             :          * up being an unqualified nestloop.
    3381                 :             :          */
    3382                 :             : 
    3383                 :      145416 :         return true;
    3384                 :             :     }
    3385                 :             : 
    3386                 :       25034 :     return false;
    3387                 :             : }
    3388                 :             : 
    3389                 :             : 
    3390                 :             : /*
    3391                 :             :  * has_relevant_eclass_joinclause
    3392                 :             :  *      Detect whether there is an EquivalenceClass that could produce
    3393                 :             :  *      a joinclause involving the given relation and anything else.
    3394                 :             :  *
    3395                 :             :  * This is the same as have_relevant_eclass_joinclause with the other rel
    3396                 :             :  * implicitly defined as "everything else in the query".
    3397                 :             :  */
    3398                 :             : bool
    3399                 :      179788 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
    3400                 :             : {
    3401                 :             :     Bitmapset  *matched_ecs;
    3402                 :             :     int         i;
    3403                 :             : 
    3404                 :             :     /* Examine only eclasses mentioning rel1 */
    3405                 :      179788 :     matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
    3406                 :             : 
    3407                 :      179788 :     i = -1;
    3408         [ +  + ]:      609563 :     while ((i = bms_next_member(matched_ecs, i)) >= 0)
    3409                 :             :     {
    3410                 :      501225 :         EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
    3411                 :             :                                                              i);
    3412                 :             : 
    3413                 :             :         /*
    3414                 :             :          * Won't generate joinclauses if single-member (this test covers the
    3415                 :             :          * volatile case too)
    3416                 :             :          */
    3417         [ +  + ]:      501225 :         if (list_length(ec->ec_members) <= 1)
    3418                 :      218591 :             continue;
    3419                 :             : 
    3420                 :             :         /*
    3421                 :             :          * Per the comment in have_relevant_eclass_joinclause, it's sufficient
    3422                 :             :          * to find an EC that mentions both this rel and some other rel.
    3423                 :             :          */
    3424         [ +  + ]:      282634 :         if (!bms_is_subset(ec->ec_relids, rel1->relids))
    3425                 :       71450 :             return true;
    3426                 :             :     }
    3427                 :             : 
    3428                 :      108338 :     return false;
    3429                 :             : }
    3430                 :             : 
    3431                 :             : 
    3432                 :             : /*
    3433                 :             :  * eclass_useful_for_merging
    3434                 :             :  *    Detect whether the EC could produce any mergejoinable join clauses
    3435                 :             :  *    against the specified relation.
    3436                 :             :  *
    3437                 :             :  * This is just a heuristic test and doesn't have to be exact; it's better
    3438                 :             :  * to say "yes" incorrectly than "no".  Hence we don't bother with details
    3439                 :             :  * like whether the lack of a cross-type operator might prevent the clause
    3440                 :             :  * from actually being generated.
    3441                 :             :  */
    3442                 :             : bool
    3443                 :      630935 : eclass_useful_for_merging(PlannerInfo *root,
    3444                 :             :                           EquivalenceClass *eclass,
    3445                 :             :                           RelOptInfo *rel)
    3446                 :             : {
    3447                 :             :     Relids      relids;
    3448                 :             :     ListCell   *lc;
    3449                 :             : 
    3450                 :             :     Assert(!eclass->ec_merged);
    3451                 :             : 
    3452                 :             :     /*
    3453                 :             :      * Won't generate joinclauses if const or single-member (the latter test
    3454                 :             :      * covers the volatile case too)
    3455                 :             :      */
    3456   [ +  +  +  + ]:      630935 :     if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
    3457                 :       30944 :         return false;
    3458                 :             : 
    3459                 :             :     /*
    3460                 :             :      * Note we don't test ec_broken; if we did, we'd need a separate code path
    3461                 :             :      * to look through ec_sources.  Checking the members anyway is OK as a
    3462                 :             :      * possibly-overoptimistic heuristic.
    3463                 :             :      */
    3464                 :             : 
    3465                 :             :     /* If specified rel is a child, we must consider the topmost parent rel */
    3466   [ +  +  +  +  :      599991 :     if (IS_OTHER_REL(rel))
                   -  + ]
    3467                 :             :     {
    3468                 :             :         Assert(!bms_is_empty(rel->top_parent_relids));
    3469                 :        4692 :         relids = rel->top_parent_relids;
    3470                 :             :     }
    3471                 :             :     else
    3472                 :      595299 :         relids = rel->relids;
    3473                 :             : 
    3474                 :             :     /* If rel already includes all members of eclass, no point in searching */
    3475         [ +  + ]:      599991 :     if (bms_is_subset(eclass->ec_relids, relids))
    3476                 :      227094 :         return false;
    3477                 :             : 
    3478                 :             :     /*
    3479                 :             :      * To join, we need a member not in the given rel.  Ignore children here.
    3480                 :             :      */
    3481   [ +  -  +  +  :      587957 :     foreach(lc, eclass->ec_members)
                   +  + ]
    3482                 :             :     {
    3483                 :      587432 :         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
    3484                 :             : 
    3485                 :             :         /* Child members should not exist in ec_members */
    3486                 :             :         Assert(!cur_em->em_is_child);
    3487                 :             : 
    3488         [ +  + ]:      587432 :         if (!bms_overlap(cur_em->em_relids, relids))
    3489                 :      372372 :             return true;
    3490                 :             :     }
    3491                 :             : 
    3492                 :         525 :     return false;
    3493                 :             : }
    3494                 :             : 
    3495                 :             : 
    3496                 :             : /*
    3497                 :             :  * is_redundant_derived_clause
    3498                 :             :  *      Test whether rinfo is derived from same EC as any clause in clauselist;
    3499                 :             :  *      if so, it can be presumed to represent a condition that's redundant
    3500                 :             :  *      with that member of the list.
    3501                 :             :  */
    3502                 :             : bool
    3503                 :          70 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
    3504                 :             : {
    3505                 :          70 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    3506                 :             :     ListCell   *lc;
    3507                 :             : 
    3508                 :             :     /* Fail if it's not a potentially-redundant clause from some EC */
    3509         [ +  - ]:          70 :     if (parent_ec == NULL)
    3510                 :          70 :         return false;
    3511                 :             : 
    3512   [ #  #  #  #  :           0 :     foreach(lc, clauselist)
                   #  # ]
    3513                 :             :     {
    3514                 :           0 :         RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
    3515                 :             : 
    3516         [ #  # ]:           0 :         if (otherrinfo->parent_ec == parent_ec)
    3517                 :           0 :             return true;
    3518                 :             :     }
    3519                 :             : 
    3520                 :           0 :     return false;
    3521                 :             : }
    3522                 :             : 
    3523                 :             : /*
    3524                 :             :  * is_redundant_with_indexclauses
    3525                 :             :  *      Test whether rinfo is redundant with any clause in the IndexClause
    3526                 :             :  *      list.  Here, for convenience, we test both simple identity and
    3527                 :             :  *      whether it is derived from the same EC as any member of the list.
    3528                 :             :  */
    3529                 :             : bool
    3530                 :     1158875 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
    3531                 :             : {
    3532                 :     1158875 :     EquivalenceClass *parent_ec = rinfo->parent_ec;
    3533                 :             :     ListCell   *lc;
    3534                 :             : 
    3535   [ +  +  +  +  :     1612322 :     foreach(lc, indexclauses)
                   +  + ]
    3536                 :             :     {
    3537                 :     1173728 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    3538                 :     1173728 :         RestrictInfo *otherrinfo = iclause->rinfo;
    3539                 :             : 
    3540                 :             :         /* If indexclause is lossy, it won't enforce the condition exactly */
    3541         [ +  + ]:     1173728 :         if (iclause->lossy)
    3542                 :       33284 :             continue;
    3543                 :             : 
    3544                 :             :         /* Match if it's same clause (pointer equality should be enough) */
    3545         [ +  + ]:     1140444 :         if (rinfo == otherrinfo)
    3546                 :      720281 :             return true;
    3547                 :             :         /* Match if derived from same EC */
    3548   [ +  +  +  + ]:      420490 :         if (parent_ec && otherrinfo->parent_ec == parent_ec)
    3549                 :         327 :             return true;
    3550                 :             : 
    3551                 :             :         /*
    3552                 :             :          * No need to look at the derived clauses in iclause->indexquals; they
    3553                 :             :          * couldn't match if the parent clause didn't.
    3554                 :             :          */
    3555                 :             :     }
    3556                 :             : 
    3557                 :      438594 :     return false;
    3558                 :             : }
    3559                 :             : 
    3560                 :             : /*
    3561                 :             :  * get_eclass_indexes_for_relids
    3562                 :             :  *      Build and return a Bitmapset containing the indexes into root's
    3563                 :             :  *      eq_classes list for all eclasses that mention any of these relids
    3564                 :             :  */
    3565                 :             : static Bitmapset *
    3566                 :      952211 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
    3567                 :             : {
    3568                 :      952211 :     Bitmapset  *ec_indexes = NULL;
    3569                 :      952211 :     int         i = -1;
    3570                 :             : 
    3571                 :             :     /* Should be OK to rely on eclass_indexes */
    3572                 :             :     Assert(root->ec_merging_done);
    3573                 :             : 
    3574         [ +  + ]:     2935830 :     while ((i = bms_next_member(relids, i)) > 0)
    3575                 :             :     {
    3576                 :     1983619 :         RelOptInfo *rel = root->simple_rel_array[i];
    3577                 :             : 
    3578                 :             :         /* ignore the RTE_GROUP RTE */
    3579         [ -  + ]:     1983619 :         if (i == root->group_rtindex)
    3580                 :           0 :             continue;
    3581                 :             : 
    3582         [ +  + ]:     1983619 :         if (rel == NULL)        /* must be an outer join */
    3583                 :             :         {
    3584                 :             :             Assert(bms_is_member(i, root->outer_join_rels));
    3585                 :      215649 :             continue;
    3586                 :             :         }
    3587                 :             : 
    3588                 :     1767970 :         ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
    3589                 :             :     }
    3590                 :      952211 :     return ec_indexes;
    3591                 :             : }
    3592                 :             : 
    3593                 :             : /*
    3594                 :             :  * get_common_eclass_indexes
    3595                 :             :  *      Build and return a Bitmapset containing the indexes into root's
    3596                 :             :  *      eq_classes list for all eclasses that mention rels in both
    3597                 :             :  *      relids1 and relids2.
    3598                 :             :  */
    3599                 :             : static Bitmapset *
    3600                 :      559091 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
    3601                 :             : {
    3602                 :             :     Bitmapset  *rel1ecs;
    3603                 :             :     Bitmapset  *rel2ecs;
    3604                 :             :     int         relid;
    3605                 :             : 
    3606                 :      559091 :     rel1ecs = get_eclass_indexes_for_relids(root, relids1);
    3607                 :             : 
    3608                 :             :     /*
    3609                 :             :      * We can get away with just using the relation's eclass_indexes directly
    3610                 :             :      * when relids2 is a singleton set.
    3611                 :             :      */
    3612         [ +  + ]:      559091 :     if (bms_get_singleton_member(relids2, &relid))
    3613                 :      423649 :         rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
    3614                 :             :     else
    3615                 :      135442 :         rel2ecs = get_eclass_indexes_for_relids(root, relids2);
    3616                 :             : 
    3617                 :             :     /* Calculate and return the common EC indexes, recycling the left input. */
    3618                 :      559091 :     return bms_int_members(rel1ecs, rel2ecs);
    3619                 :             : }
    3620                 :             : 
    3621                 :             : /*
    3622                 :             :  * ec_build_derives_hash
    3623                 :             :  *    Construct the auxiliary hash table for derived clause lookups.
    3624                 :             :  */
    3625                 :             : static void
    3626                 :           0 : ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec)
    3627                 :             : {
    3628                 :             :     Assert(!ec->ec_derives_hash);
    3629                 :             : 
    3630                 :             :     /*
    3631                 :             :      * Create the hash table.
    3632                 :             :      *
    3633                 :             :      * We pass list_length(ec->ec_derives_list) as the initial size.
    3634                 :             :      * Simplehash will divide this by the fillfactor (typically 0.9) and round
    3635                 :             :      * up to the next power of two, so this will usually give us at least 64
    3636                 :             :      * buckets around the threshold. That avoids immediate resizing without
    3637                 :             :      * hardcoding a specific size.
    3638                 :             :      */
    3639                 :           0 :     ec->ec_derives_hash = derives_create(root->planner_cxt,
    3640                 :           0 :                                          list_length(ec->ec_derives_list),
    3641                 :             :                                          NULL);
    3642                 :             : 
    3643   [ #  #  #  #  :           0 :     foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
                   #  # ]
    3644                 :           0 :         ec_add_clause_to_derives_hash(ec, rinfo);
    3645                 :           0 : }
    3646                 :             : 
    3647                 :             : /*
    3648                 :             :  * ec_add_derived_clause
    3649                 :             :  *      Add a clause to the set of derived clauses for the given
    3650                 :             :  *      EquivalenceClass. Always appends to ec_derives_list; also adds
    3651                 :             :  *      to ec_derives_hash if it exists.
    3652                 :             :  *
    3653                 :             :  * Also asserts expected invariants of derived clauses.
    3654                 :             :  */
    3655                 :             : static void
    3656                 :       94578 : ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause)
    3657                 :             : {
    3658                 :             :     /*
    3659                 :             :      * Constant, if present, is always placed on the RHS; see
    3660                 :             :      * generate_base_implied_equalities_const(). LHS is never a constant.
    3661                 :             :      */
    3662                 :             :     Assert(!clause->left_em->em_is_const);
    3663                 :             : 
    3664                 :             :     /*
    3665                 :             :      * Clauses containing a constant are never considered redundant, so
    3666                 :             :      * parent_ec is not set.
    3667                 :             :      */
    3668                 :             :     Assert(!clause->parent_ec || !clause->right_em->em_is_const);
    3669                 :             : 
    3670                 :       94578 :     ec->ec_derives_list = lappend(ec->ec_derives_list, clause);
    3671         [ -  + ]:       94578 :     if (ec->ec_derives_hash)
    3672                 :           0 :         ec_add_clause_to_derives_hash(ec, clause);
    3673                 :       94578 : }
    3674                 :             : 
    3675                 :             : /*
    3676                 :             :  * ec_add_derived_clauses
    3677                 :             :  *      Add a list of clauses to the set of clauses derived from the given
    3678                 :             :  *      EquivalenceClass; adding to the list and hash table if needed.
    3679                 :             :  *
    3680                 :             :  * This function is similar to ec_add_derived_clause() but optimized for adding
    3681                 :             :  * multiple clauses at a time to the ec_derives_list.  The assertions from
    3682                 :             :  * ec_add_derived_clause() are not repeated here, as the input clauses are
    3683                 :             :  * assumed to have already been validated.
    3684                 :             :  */
    3685                 :             : static void
    3686                 :          33 : ec_add_derived_clauses(EquivalenceClass *ec, List *clauses)
    3687                 :             : {
    3688                 :          33 :     ec->ec_derives_list = list_concat(ec->ec_derives_list, clauses);
    3689         [ -  + ]:          33 :     if (ec->ec_derives_hash)
    3690   [ #  #  #  #  :           0 :         foreach_node(RestrictInfo, rinfo, clauses)
                   #  # ]
    3691                 :           0 :             ec_add_clause_to_derives_hash(ec, rinfo);
    3692                 :          33 : }
    3693                 :             : 
    3694                 :             : /*
    3695                 :             :  * fill_ec_derives_key
    3696                 :             :  *      Compute a canonical key for ec_derives_hash lookup or insertion.
    3697                 :             :  *
    3698                 :             :  * Derived clauses are looked up using a pair of EquivalenceMembers and a
    3699                 :             :  * parent EquivalenceClass. To avoid storing or searching for both EM orderings,
    3700                 :             :  * we canonicalize the key:
    3701                 :             :  *
    3702                 :             :  * - For clauses involving two non-constant EMs, em1 is set to the EM with lower
    3703                 :             :  *   memory address and em2 is set to the other one.
    3704                 :             :  * - For clauses involving a constant EM, the caller must pass the non-constant
    3705                 :             :  *   EM as leftem and NULL as rightem; we then set em1 = NULL and em2 = leftem.
    3706                 :             :  */
    3707                 :             : static inline void
    3708                 :           0 : fill_ec_derives_key(ECDerivesKey *key,
    3709                 :             :                     EquivalenceMember *leftem,
    3710                 :             :                     EquivalenceMember *rightem,
    3711                 :             :                     EquivalenceClass *parent_ec)
    3712                 :             : {
    3713                 :             :     Assert(leftem);             /* Always required for lookup or insertion */
    3714                 :             : 
    3715         [ #  # ]:           0 :     if (rightem == NULL)
    3716                 :             :     {
    3717                 :           0 :         key->em1 = NULL;
    3718                 :           0 :         key->em2 = leftem;
    3719                 :             :     }
    3720         [ #  # ]:           0 :     else if (leftem < rightem)
    3721                 :             :     {
    3722                 :           0 :         key->em1 = leftem;
    3723                 :           0 :         key->em2 = rightem;
    3724                 :             :     }
    3725                 :             :     else
    3726                 :             :     {
    3727                 :           0 :         key->em1 = rightem;
    3728                 :           0 :         key->em2 = leftem;
    3729                 :             :     }
    3730                 :           0 :     key->parent_ec = parent_ec;
    3731                 :           0 : }
    3732                 :             : 
    3733                 :             : /*
    3734                 :             :  * ec_add_clause_to_derives_hash
    3735                 :             :  *      Add a derived clause to ec_derives_hash in the given EquivalenceClass.
    3736                 :             :  *
    3737                 :             :  * Each clause is associated with a canonicalized key. For constant-containing
    3738                 :             :  * clauses, only the non-constant EM is used for lookup; see comments in
    3739                 :             :  * fill_ec_derives_key().
    3740                 :             :  */
    3741                 :             : static void
    3742                 :           0 : ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo)
    3743                 :             : {
    3744                 :             :     ECDerivesKey key;
    3745                 :             :     ECDerivesEntry *entry;
    3746                 :             :     bool        found;
    3747                 :             : 
    3748                 :             :     /*
    3749                 :             :      * Constants are always placed on the RHS; see
    3750                 :             :      * generate_base_implied_equalities_const().
    3751                 :             :      */
    3752                 :             :     Assert(!rinfo->left_em->em_is_const);
    3753                 :             : 
    3754                 :             :     /*
    3755                 :             :      * Clauses containing a constant are never considered redundant, so
    3756                 :             :      * parent_ec is not set.
    3757                 :             :      */
    3758                 :             :     Assert(!rinfo->parent_ec || !rinfo->right_em->em_is_const);
    3759                 :             : 
    3760                 :             :     /*
    3761                 :             :      * See fill_ec_derives_key() for details: we use a canonicalized key to
    3762                 :             :      * avoid storing both EM orderings. For constant EMs, only the
    3763                 :             :      * non-constant EM is included in the key.
    3764                 :             :      */
    3765                 :           0 :     fill_ec_derives_key(&key,
    3766                 :             :                         rinfo->left_em,
    3767         [ #  # ]:           0 :                         rinfo->right_em->em_is_const ? NULL : rinfo->right_em,
    3768                 :             :                         rinfo->parent_ec);
    3769                 :           0 :     entry = derives_insert(ec->ec_derives_hash, key, &found);
    3770                 :             :     Assert(!found);
    3771                 :           0 :     entry->rinfo = rinfo;
    3772                 :           0 : }
    3773                 :             : 
    3774                 :             : /*
    3775                 :             :  * ec_clear_derived_clauses
    3776                 :             :  *      Reset ec_derives_list and ec_derives_hash.
    3777                 :             :  *
    3778                 :             :  * We destroy the hash table explicitly, since it may consume significant
    3779                 :             :  * space. The list holds the same set of entries and can become equally large
    3780                 :             :  * when thousands of partitions are involved, so we free it as well -- even
    3781                 :             :  * though we do not typically free lists.
    3782                 :             :  */
    3783                 :             : static void
    3784                 :          33 : ec_clear_derived_clauses(EquivalenceClass *ec)
    3785                 :             : {
    3786                 :          33 :     list_free(ec->ec_derives_list);
    3787                 :          33 :     ec->ec_derives_list = NIL;
    3788                 :             : 
    3789         [ -  + ]:          33 :     if (ec->ec_derives_hash)
    3790                 :             :     {
    3791                 :           0 :         derives_destroy(ec->ec_derives_hash);
    3792                 :           0 :         ec->ec_derives_hash = NULL;
    3793                 :             :     }
    3794                 :          33 : }
    3795                 :             : 
    3796                 :             : /*
    3797                 :             :  * ec_search_clause_for_ems
    3798                 :             :  *      Search for an existing RestrictInfo that equates the given pair
    3799                 :             :  *      of EquivalenceMembers, either from ec_sources or ec_derives.
    3800                 :             :  *
    3801                 :             :  * Returns a clause with matching operands in either given order or commuted
    3802                 :             :  * order. We used to require matching operator OIDs, but dropped that since any
    3803                 :             :  * semantically different operator here would indicate a broken operator family.
    3804                 :             :  *
    3805                 :             :  * Returns NULL if no matching clause is found.
    3806                 :             :  */
    3807                 :             : static RestrictInfo *
    3808                 :      415274 : ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
    3809                 :             :                          EquivalenceMember *leftem, EquivalenceMember *rightem,
    3810                 :             :                          EquivalenceClass *parent_ec)
    3811                 :             : {
    3812                 :             :     /* Check original source clauses */
    3813   [ +  -  +  +  :     1315656 :     foreach_node(RestrictInfo, rinfo, ec->ec_sources)
                   +  + ]
    3814                 :             :     {
    3815         [ +  + ]:      487690 :         if (rinfo->left_em == leftem &&
    3816         [ +  + ]:      231552 :             rinfo->right_em == rightem &&
    3817         [ +  + ]:      205002 :             rinfo->parent_ec == parent_ec)
    3818                 :        1291 :             return rinfo;
    3819         [ +  + ]:      487600 :         if (rinfo->left_em == rightem &&
    3820         [ +  + ]:      210259 :             rinfo->right_em == leftem &&
    3821         [ +  + ]:      187463 :             rinfo->parent_ec == parent_ec)
    3822                 :        1201 :             return rinfo;
    3823                 :             :     }
    3824                 :             : 
    3825                 :             :     /* Not found in ec_sources; search derived clauses */
    3826                 :      413983 :     return ec_search_derived_clause_for_ems(root, ec, leftem, rightem,
    3827                 :             :                                             parent_ec);
    3828                 :             : }
    3829                 :             : 
    3830                 :             : /*
    3831                 :             :  * ec_search_derived_clause_for_ems
    3832                 :             :  *      Search for an existing derived clause between two EquivalenceMembers.
    3833                 :             :  *
    3834                 :             :  * If the number of derived clauses exceeds a threshold, switch to hash table
    3835                 :             :  * lookup; otherwise, scan ec_derives_list linearly.
    3836                 :             :  *
    3837                 :             :  * Clauses involving constants are looked up by passing the non-constant EM
    3838                 :             :  * as leftem and setting rightem to NULL. In that case, we expect to find a
    3839                 :             :  * clause with a constant on the RHS.
    3840                 :             :  *
    3841                 :             :  * While searching the list, we compare each given EM with both sides of each
    3842                 :             :  * clause. But for hash table lookups, we construct a canonicalized key and
    3843                 :             :  * perform a single lookup.
    3844                 :             :  */
    3845                 :             : static RestrictInfo *
    3846                 :      413988 : ec_search_derived_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
    3847                 :             :                                  EquivalenceMember *leftem,
    3848                 :             :                                  EquivalenceMember *rightem,
    3849                 :             :                                  EquivalenceClass *parent_ec)
    3850                 :             : {
    3851                 :             :     /* Switch to using hash lookup when list grows "too long". */
    3852   [ +  -  -  + ]:      827976 :     if (!ec->ec_derives_hash &&
    3853                 :      413988 :         list_length(ec->ec_derives_list) >= EC_DERIVES_HASH_THRESHOLD)
    3854                 :           0 :         ec_build_derives_hash(root, ec);
    3855                 :             : 
    3856                 :             :     /* Perform hash table lookup if available */
    3857         [ -  + ]:      413988 :     if (ec->ec_derives_hash)
    3858                 :             :     {
    3859                 :             :         ECDerivesKey key;
    3860                 :             :         RestrictInfo *rinfo;
    3861                 :             :         ECDerivesEntry *entry;
    3862                 :             : 
    3863                 :           0 :         fill_ec_derives_key(&key, leftem, rightem, parent_ec);
    3864                 :           0 :         entry = derives_lookup(ec->ec_derives_hash, key);
    3865         [ #  # ]:           0 :         if (entry)
    3866                 :             :         {
    3867                 :           0 :             rinfo = entry->rinfo;
    3868                 :             :             Assert(rinfo);
    3869                 :             :             Assert(rightem || rinfo->right_em->em_is_const);
    3870                 :           0 :             return rinfo;
    3871                 :             :         }
    3872                 :             :     }
    3873                 :             :     else
    3874                 :             :     {
    3875                 :             :         /* Fallback to linear search over ec_derives_list */
    3876   [ +  +  +  +  :      591326 :         foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
                   +  + ]
    3877                 :             :         {
    3878                 :             :             /* Handle special case: lookup by non-const EM alone */
    3879         [ +  + ]:      452186 :             if (!rightem &&
    3880         [ +  - ]:           5 :                 rinfo->left_em == leftem)
    3881                 :             :             {
    3882                 :             :                 Assert(rinfo->right_em->em_is_const);
    3883                 :      344418 :                 return rinfo;
    3884                 :             :             }
    3885         [ +  + ]:      452181 :             if (rinfo->left_em == leftem &&
    3886         [ +  + ]:      185400 :                 rinfo->right_em == rightem &&
    3887         [ +  + ]:      168044 :                 rinfo->parent_ec == parent_ec)
    3888                 :      168034 :                 return rinfo;
    3889         [ +  + ]:      284147 :             if (rinfo->left_em == rightem &&
    3890         [ +  + ]:      186505 :                 rinfo->right_em == leftem &&
    3891         [ +  - ]:      176379 :                 rinfo->parent_ec == parent_ec)
    3892                 :      176379 :                 return rinfo;
    3893                 :             :         }
    3894                 :             :     }
    3895                 :             : 
    3896                 :       69570 :     return NULL;
    3897                 :             : }
        

Generated by: LCOV version 2.0-1