LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/path - equivclass.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 95.7 % 1015 971 2 42 17 954 1
Current Date: 2024-04-14 14:21:10 Functions: 100.0 % 36 36 2 34
Baseline: 16@8cea358b128 Branches: 82.0 % 964 790 5 169 1 11 778
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 87.5 % 16 14 2 14
(60,120] days: 100.0 % 3 3 3
(240..) days: 95.8 % 996 954 42 954
Function coverage date bins:
[..60] days: 100.0 % 1 1 1
(240..) days: 100.0 % 35 35 1 34
Branch coverage date bins:
[..60] days: 58.3 % 12 7 5 7
(60,120] days: 100.0 % 4 4 4
(240..) days: 82.2 % 948 779 169 1 778

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

Generated by: LCOV version 2.1-beta2-3-g6141622