LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/prep - prepjointree.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: 806555e3000d0b0e0c536c1dc65548128d457d86 vs 1d325ad99cb2dec0e8b45ba36909ee0a497d2a57 Lines: 94.1 % 1359 1279 80 53 1226 45
Current Date: 2025-12-17 08:58:58 +0900 Functions: 100.0 % 47 47 7 40 1
Baseline: lcov-20251217-005640-baseline Branches: 77.9 % 1021 795 3 223 1 19 775
Baseline Date: 2025-12-16 12:57:12 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 3 3 3
(7,30] days: 100.0 % 1 1 1
(30,360] days: 98.7 % 78 77 1 49 28
(360..) days: 93.8 % 1277 1198 79 1198
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 45 45 5 40
Branch coverage date bins:
(30,360] days: 86.4 % 44 38 3 3 19 19
(360..) days: 77.5 % 977 757 220 1 756

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * prepjointree.c
                                  4                 :                :  *    Planner preprocessing for subqueries and join tree manipulation.
                                  5                 :                :  *
                                  6                 :                :  * NOTE: the intended sequence for invoking these operations is
                                  7                 :                :  *      preprocess_relation_rtes
                                  8                 :                :  *      replace_empty_jointree
                                  9                 :                :  *      pull_up_sublinks
                                 10                 :                :  *      preprocess_function_rtes
                                 11                 :                :  *      pull_up_subqueries
                                 12                 :                :  *      flatten_simple_union_all
                                 13                 :                :  *      do expression preprocessing (including flattening JOIN alias vars)
                                 14                 :                :  *      reduce_outer_joins
                                 15                 :                :  *      remove_useless_result_rtes
                                 16                 :                :  *
                                 17                 :                :  *
                                 18                 :                :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
                                 19                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 20                 :                :  *
                                 21                 :                :  *
                                 22                 :                :  * IDENTIFICATION
                                 23                 :                :  *    src/backend/optimizer/prep/prepjointree.c
                                 24                 :                :  *
                                 25                 :                :  *-------------------------------------------------------------------------
                                 26                 :                :  */
                                 27                 :                : #include "postgres.h"
                                 28                 :                : 
                                 29                 :                : #include "access/table.h"
                                 30                 :                : #include "catalog/pg_type.h"
                                 31                 :                : #include "funcapi.h"
                                 32                 :                : #include "miscadmin.h"
                                 33                 :                : #include "nodes/makefuncs.h"
                                 34                 :                : #include "nodes/multibitmapset.h"
                                 35                 :                : #include "nodes/nodeFuncs.h"
                                 36                 :                : #include "optimizer/clauses.h"
                                 37                 :                : #include "optimizer/optimizer.h"
                                 38                 :                : #include "optimizer/placeholder.h"
                                 39                 :                : #include "optimizer/plancat.h"
                                 40                 :                : #include "optimizer/prep.h"
                                 41                 :                : #include "optimizer/subselect.h"
                                 42                 :                : #include "optimizer/tlist.h"
                                 43                 :                : #include "parser/parse_relation.h"
                                 44                 :                : #include "parser/parsetree.h"
                                 45                 :                : #include "rewrite/rewriteHandler.h"
                                 46                 :                : #include "rewrite/rewriteManip.h"
                                 47                 :                : #include "utils/rel.h"
                                 48                 :                : 
                                 49                 :                : 
                                 50                 :                : typedef struct nullingrel_info
                                 51                 :                : {
                                 52                 :                :     /*
                                 53                 :                :      * For each leaf RTE, nullingrels[rti] is the set of relids of outer joins
                                 54                 :                :      * that potentially null that RTE.
                                 55                 :                :      */
                                 56                 :                :     Relids     *nullingrels;
                                 57                 :                :     /* Length of range table (maximum index in nullingrels[]) */
                                 58                 :                :     int         rtlength;       /* used only for assertion checks */
                                 59                 :                : } nullingrel_info;
                                 60                 :                : 
                                 61                 :                : /* Options for wrapping an expression for identification purposes */
                                 62                 :                : typedef enum ReplaceWrapOption
                                 63                 :                : {
                                 64                 :                :     REPLACE_WRAP_NONE,          /* no expressions need to be wrapped */
                                 65                 :                :     REPLACE_WRAP_ALL,           /* all expressions need to be wrapped */
                                 66                 :                :     REPLACE_WRAP_VARFREE,       /* variable-free expressions need to be
                                 67                 :                :                                  * wrapped */
                                 68                 :                : } ReplaceWrapOption;
                                 69                 :                : 
                                 70                 :                : typedef struct pullup_replace_vars_context
                                 71                 :                : {
                                 72                 :                :     PlannerInfo *root;
                                 73                 :                :     List       *targetlist;     /* tlist of subquery being pulled up */
                                 74                 :                :     RangeTblEntry *target_rte;  /* RTE of subquery */
                                 75                 :                :     int         result_relation;    /* the index of the result relation in the
                                 76                 :                :                                      * rewritten query */
                                 77                 :                :     Relids      relids;         /* relids within subquery, as numbered after
                                 78                 :                :                                  * pullup (set only if target_rte->lateral) */
                                 79                 :                :     nullingrel_info *nullinfo;  /* per-RTE nullingrel info (set only if
                                 80                 :                :                                  * target_rte->lateral) */
                                 81                 :                :     bool       *outer_hasSubLinks;  /* -> outer query's hasSubLinks */
                                 82                 :                :     int         varno;          /* varno of subquery */
                                 83                 :                :     ReplaceWrapOption wrap_option;  /* do we need certain outputs to be PHVs? */
                                 84                 :                :     Node      **rv_cache;       /* cache for results with PHVs */
                                 85                 :                : } pullup_replace_vars_context;
                                 86                 :                : 
                                 87                 :                : typedef struct reduce_outer_joins_pass1_state
                                 88                 :                : {
                                 89                 :                :     Relids      relids;         /* base relids within this subtree */
                                 90                 :                :     bool        contains_outer; /* does subtree contain outer join(s)? */
                                 91                 :                :     List       *sub_states;     /* List of states for subtree components */
                                 92                 :                : } reduce_outer_joins_pass1_state;
                                 93                 :                : 
                                 94                 :                : typedef struct reduce_outer_joins_pass2_state
                                 95                 :                : {
                                 96                 :                :     Relids      inner_reduced;  /* OJ relids reduced to plain inner joins */
                                 97                 :                :     List       *partial_reduced;    /* List of partially reduced FULL joins */
                                 98                 :                : } reduce_outer_joins_pass2_state;
                                 99                 :                : 
                                100                 :                : typedef struct reduce_outer_joins_partial_state
                                101                 :                : {
                                102                 :                :     int         full_join_rti;  /* RT index of a formerly-FULL join */
                                103                 :                :     Relids      unreduced_side; /* relids in its still-nullable side */
                                104                 :                : } reduce_outer_joins_partial_state;
                                105                 :                : 
                                106                 :                : static Query *expand_virtual_generated_columns(PlannerInfo *root, Query *parse,
                                107                 :                :                                                RangeTblEntry *rte, int rt_index,
                                108                 :                :                                                Relation relation);
                                109                 :                : static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
                                110                 :                :                                                Relids *relids);
                                111                 :                : static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
                                112                 :                :                                            Node **jtlink1, Relids available_rels1,
                                113                 :                :                                            Node **jtlink2, Relids available_rels2);
                                114                 :                : static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
                                115                 :                :                                         JoinExpr *lowest_outer_join,
                                116                 :                :                                         AppendRelInfo *containing_appendrel);
                                117                 :                : static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
                                118                 :                :                                      RangeTblEntry *rte,
                                119                 :                :                                      JoinExpr *lowest_outer_join,
                                120                 :                :                                      AppendRelInfo *containing_appendrel);
                                121                 :                : static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
                                122                 :                :                                       RangeTblEntry *rte);
                                123                 :                : static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
                                124                 :                :                                        int parentRTindex, Query *setOpQuery,
                                125                 :                :                                        int childRToffset);
                                126                 :                : static void make_setop_translation_list(Query *query, int newvarno,
                                127                 :                :                                         AppendRelInfo *appinfo);
                                128                 :                : static bool is_simple_subquery(PlannerInfo *root, Query *subquery,
                                129                 :                :                                RangeTblEntry *rte,
                                130                 :                :                                JoinExpr *lowest_outer_join);
                                131                 :                : static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode,
                                132                 :                :                                    RangeTblEntry *rte);
                                133                 :                : static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte);
                                134                 :                : static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode,
                                135                 :                :                                        RangeTblEntry *rte,
                                136                 :                :                                        AppendRelInfo *containing_appendrel);
                                137                 :                : static bool is_simple_union_all(Query *subquery);
                                138                 :                : static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
                                139                 :                :                                         List *colTypes);
                                140                 :                : static bool is_safe_append_member(Query *subquery);
                                141                 :                : static bool jointree_contains_lateral_outer_refs(PlannerInfo *root,
                                142                 :                :                                                  Node *jtnode, bool restricted,
                                143                 :                :                                                  Relids safe_upper_varnos);
                                144                 :                : static void perform_pullup_replace_vars(PlannerInfo *root,
                                145                 :                :                                         pullup_replace_vars_context *rvcontext,
                                146                 :                :                                         AppendRelInfo *containing_appendrel);
                                147                 :                : static void replace_vars_in_jointree(Node *jtnode,
                                148                 :                :                                      pullup_replace_vars_context *context);
                                149                 :                : static Node *pullup_replace_vars(Node *expr,
                                150                 :                :                                  pullup_replace_vars_context *context);
                                151                 :                : static Node *pullup_replace_vars_callback(Var *var,
                                152                 :                :                                           replace_rte_variables_context *context);
                                153                 :                : static Query *pullup_replace_vars_subquery(Query *query,
                                154                 :                :                                            pullup_replace_vars_context *context);
                                155                 :                : static reduce_outer_joins_pass1_state *reduce_outer_joins_pass1(Node *jtnode);
                                156                 :                : static void reduce_outer_joins_pass2(Node *jtnode,
                                157                 :                :                                      reduce_outer_joins_pass1_state *state1,
                                158                 :                :                                      reduce_outer_joins_pass2_state *state2,
                                159                 :                :                                      PlannerInfo *root,
                                160                 :                :                                      Relids nonnullable_rels,
                                161                 :                :                                      List *forced_null_vars);
                                162                 :                : static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
                                163                 :                :                                      int rtindex, Relids relids);
                                164                 :                : static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
                                165                 :                :                                             Node **parent_quals,
                                166                 :                :                                             Relids *dropped_outer_joins);
                                167                 :                : static int  get_result_relid(PlannerInfo *root, Node *jtnode);
                                168                 :                : static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc);
                                169                 :                : static bool find_dependent_phvs(PlannerInfo *root, int varno);
                                170                 :                : static bool find_dependent_phvs_in_jointree(PlannerInfo *root,
                                171                 :                :                                             Node *node, int varno);
                                172                 :                : static void substitute_phv_relids(Node *node,
                                173                 :                :                                   int varno, Relids subrelids);
                                174                 :                : static void fix_append_rel_relids(PlannerInfo *root, int varno,
                                175                 :                :                                   Relids subrelids);
                                176                 :                : static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
                                177                 :                : static nullingrel_info *get_nullingrels(Query *parse);
                                178                 :                : static void get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels,
                                179                 :                :                                     nullingrel_info *info);
                                180                 :                : 
                                181                 :                : 
                                182                 :                : /*
                                183                 :                :  * transform_MERGE_to_join
                                184                 :                :  *      Replace a MERGE's jointree to also include the target relation.
                                185                 :                :  */
                                186                 :                : void
 1360 alvherre@alvh.no-ip.      187                 :CBC      272148 : transform_MERGE_to_join(Query *parse)
                                188                 :                : {
                                189                 :                :     RangeTblEntry *joinrte;
                                190                 :                :     JoinExpr   *joinexpr;
                                191                 :                :     bool        have_action[NUM_MERGE_MATCH_KINDS];
                                192                 :                :     JoinType    jointype;
                                193                 :                :     int         joinrti;
                                194                 :                :     List       *vars;
                                195                 :                :     RangeTblRef *rtr;
                                196                 :                :     FromExpr   *target;
                                197                 :                :     Node       *source;
                                198                 :                :     int         sourcerti;
                                199                 :                : 
                                200         [ +  + ]:         272148 :     if (parse->commandType != CMD_MERGE)
                                201                 :         271167 :         return;
                                202                 :                : 
                                203                 :                :     /* XXX probably bogus */
                                204                 :            981 :     vars = NIL;
                                205                 :                : 
                                206                 :                :     /*
                                207                 :                :      * Work out what kind of join is required.  If there any WHEN NOT MATCHED
                                208                 :                :      * BY SOURCE/TARGET actions, an outer join is required so that we process
                                209                 :                :      * all unmatched tuples from the source and/or target relations.
                                210                 :                :      * Otherwise, we can use an inner join.
                                211                 :                :      */
  627 dean.a.rasheed@gmail      212                 :            981 :     have_action[MERGE_WHEN_MATCHED] = false;
                                213                 :            981 :     have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false;
                                214                 :            981 :     have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false;
                                215                 :                : 
                                216   [ +  -  +  +  :           3456 :     foreach_node(MergeAction, action, parse->mergeActionList)
                                              +  + ]
                                217                 :                :     {
                                218         [ +  + ]:           1494 :         if (action->commandType != CMD_NOTHING)
                                219                 :           1452 :             have_action[action->matchKind] = true;
                                220                 :                :     }
                                221                 :                : 
                                222         [ +  + ]:            981 :     if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
                                223         [ +  + ]:             66 :         have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
                                224                 :             51 :         jointype = JOIN_FULL;
                                225         [ +  + ]:            930 :     else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
                                226                 :             15 :         jointype = JOIN_LEFT;
                                227         [ +  + ]:            915 :     else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
 1360 alvherre@alvh.no-ip.      228                 :            424 :         jointype = JOIN_RIGHT;
                                229                 :                :     else
                                230                 :            491 :         jointype = JOIN_INNER;
                                231                 :                : 
                                232                 :                :     /* Manufacture a join RTE to use. */
                                233                 :            981 :     joinrte = makeNode(RangeTblEntry);
                                234                 :            981 :     joinrte->rtekind = RTE_JOIN;
                                235                 :            981 :     joinrte->jointype = jointype;
                                236                 :            981 :     joinrte->joinmergedcols = 0;
                                237                 :            981 :     joinrte->joinaliasvars = vars;
                                238                 :            981 :     joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */
                                239                 :            981 :     joinrte->joinrightcols = NIL;    /* ditto */
                                240                 :            981 :     joinrte->join_using_alias = NULL;
                                241                 :                : 
                                242                 :            981 :     joinrte->alias = NULL;
                                243                 :            981 :     joinrte->eref = makeAlias("*MERGE*", NIL);
                                244                 :            981 :     joinrte->lateral = false;
                                245                 :            981 :     joinrte->inh = false;
                                246                 :            981 :     joinrte->inFromCl = true;
                                247                 :                : 
                                248                 :                :     /*
                                249                 :                :      * Add completed RTE to pstate's range table list, so that we know its
                                250                 :                :      * index.
                                251                 :                :      */
                                252                 :            981 :     parse->rtable = lappend(parse->rtable, joinrte);
                                253                 :            981 :     joinrti = list_length(parse->rtable);
                                254                 :                : 
                                255                 :                :     /*
                                256                 :                :      * Create a JOIN between the target and the source relation.
                                257                 :                :      *
                                258                 :                :      * Here the target is identified by parse->mergeTargetRelation.  For a
                                259                 :                :      * regular table, this will equal parse->resultRelation, but for a
                                260                 :                :      * trigger-updatable view, it will be the expanded view subquery that we
                                261                 :                :      * need to pull data from.
                                262                 :                :      *
                                263                 :                :      * The source relation is in parse->jointree->fromlist, but any quals in
                                264                 :                :      * parse->jointree->quals are restrictions on the target relation (if the
                                265                 :                :      * target relation is an auto-updatable view).
                                266                 :                :      */
                                267                 :                :     /* target rel, with any quals */
  627 dean.a.rasheed@gmail      268                 :            981 :     rtr = makeNode(RangeTblRef);
                                269                 :            981 :     rtr->rtindex = parse->mergeTargetRelation;
  440                           270                 :            981 :     target = makeFromExpr(list_make1(rtr), parse->jointree->quals);
                                271                 :                : 
                                272                 :                :     /* source rel (expect exactly one -- see transformMergeStmt()) */
                                273         [ -  + ]:            981 :     Assert(list_length(parse->jointree->fromlist) == 1);
                                274                 :            981 :     source = linitial(parse->jointree->fromlist);
                                275                 :                : 
                                276                 :                :     /*
                                277                 :                :      * index of source rel (expect either a RangeTblRef or a JoinExpr -- see
                                278                 :                :      * transformFromClauseItem()).
                                279                 :                :      */
                                280         [ +  + ]:            981 :     if (IsA(source, RangeTblRef))
                                281                 :            939 :         sourcerti = ((RangeTblRef *) source)->rtindex;
                                282         [ +  - ]:             42 :     else if (IsA(source, JoinExpr))
                                283                 :             42 :         sourcerti = ((JoinExpr *) source)->rtindex;
                                284                 :                :     else
                                285                 :                :     {
  440 dean.a.rasheed@gmail      286         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized source node type: %d",
                                287                 :                :              (int) nodeTag(source));
                                288                 :                :         sourcerti = 0;          /* keep compiler quiet */
                                289                 :                :     }
                                290                 :                : 
                                291                 :                :     /* Join the source and target */
 1360 alvherre@alvh.no-ip.      292                 :CBC         981 :     joinexpr = makeNode(JoinExpr);
                                293                 :            981 :     joinexpr->jointype = jointype;
                                294                 :            981 :     joinexpr->isNatural = false;
  440 dean.a.rasheed@gmail      295                 :            981 :     joinexpr->larg = (Node *) target;
                                296                 :            981 :     joinexpr->rarg = source;
 1360 alvherre@alvh.no-ip.      297                 :            981 :     joinexpr->usingClause = NIL;
                                298                 :            981 :     joinexpr->join_using_alias = NULL;
  627 dean.a.rasheed@gmail      299                 :            981 :     joinexpr->quals = parse->mergeJoinCondition;
 1360 alvherre@alvh.no-ip.      300                 :            981 :     joinexpr->alias = NULL;
                                301                 :            981 :     joinexpr->rtindex = joinrti;
                                302                 :                : 
                                303                 :                :     /* Make the new join be the sole entry in the query's jointree */
                                304                 :            981 :     parse->jointree->fromlist = list_make1(joinexpr);
                                305                 :            981 :     parse->jointree->quals = NULL;
                                306                 :                : 
                                307                 :                :     /*
                                308                 :                :      * If necessary, mark parse->targetlist entries that refer to the target
                                309                 :                :      * as nullable by the join.  Normally the targetlist will be empty for a
                                310                 :                :      * MERGE, but if the target is a trigger-updatable view, it will contain a
                                311                 :                :      * whole-row Var referring to the expanded view query.
                                312                 :                :      */
  657 dean.a.rasheed@gmail      313   [ +  +  +  + ]:            981 :     if (parse->targetList != NIL &&
                                314         [ +  + ]:             21 :         (jointype == JOIN_RIGHT || jointype == JOIN_FULL))
                                315                 :             21 :         parse->targetList = (List *)
                                316                 :             21 :             add_nulling_relids((Node *) parse->targetList,
                                317                 :             21 :                                bms_make_singleton(parse->mergeTargetRelation),
                                318                 :             21 :                                bms_make_singleton(joinrti));
                                319                 :                : 
                                320                 :                :     /*
                                321                 :                :      * If the source relation is on the outer side of the join, mark any
                                322                 :                :      * source relation Vars in the join condition, actions, and RETURNING list
                                323                 :                :      * as nullable by the join.  These Vars will be added to the targetlist by
                                324                 :                :      * preprocess_targetlist(), so it's important to mark them correctly here.
                                325                 :                :      *
                                326                 :                :      * It might seem that this is not necessary for Vars in the join
                                327                 :                :      * condition, since it is inside the join, but it is also needed above the
                                328                 :                :      * join (in the ModifyTable node) to distinguish between the MATCHED and
                                329                 :                :      * NOT MATCHED BY SOURCE cases -- see ExecMergeMatched().  Note that this
                                330                 :                :      * creates a modified copy of the join condition, for use above the join,
                                331                 :                :      * without modifying the original join condition, inside the join.
                                332                 :                :      */
  440                           333   [ +  +  +  + ]:            981 :     if (jointype == JOIN_LEFT || jointype == JOIN_FULL)
                                334                 :                :     {
                                335                 :             66 :         parse->mergeJoinCondition =
                                336                 :             66 :             add_nulling_relids(parse->mergeJoinCondition,
                                337                 :             66 :                                bms_make_singleton(sourcerti),
                                338                 :             66 :                                bms_make_singleton(joinrti));
                                339                 :                : 
                                340   [ +  -  +  +  :            315 :         foreach_node(MergeAction, action, parse->mergeActionList)
                                              +  + ]
                                341                 :                :         {
                                342                 :            183 :             action->qual =
                                343                 :            183 :                 add_nulling_relids(action->qual,
                                344                 :            183 :                                    bms_make_singleton(sourcerti),
                                345                 :            183 :                                    bms_make_singleton(joinrti));
                                346                 :                : 
                                347                 :            183 :             action->targetList = (List *)
                                348                 :            183 :                 add_nulling_relids((Node *) action->targetList,
                                349                 :            183 :                                    bms_make_singleton(sourcerti),
                                350                 :            183 :                                    bms_make_singleton(joinrti));
                                351                 :                :         }
                                352                 :                : 
                                353                 :             66 :         parse->returningList = (List *)
                                354                 :             66 :             add_nulling_relids((Node *) parse->returningList,
                                355                 :             66 :                                bms_make_singleton(sourcerti),
                                356                 :             66 :                                bms_make_singleton(joinrti));
                                357                 :                :     }
                                358                 :                : 
                                359                 :                :     /*
                                360                 :                :      * If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will
                                361                 :                :      * use the join condition to distinguish between MATCHED and NOT MATCHED
                                362                 :                :      * BY SOURCE cases.  Otherwise, it's no longer needed, and we set it to
                                363                 :                :      * NULL, saving cycles during planning and execution.
                                364                 :                :      *
                                365                 :                :      * We need to be careful though: the executor evaluates this condition
                                366                 :                :      * using the output of the join subplan node, which nulls the output from
                                367                 :                :      * the source relation when the join condition doesn't match.  That risks
                                368                 :                :      * producing incorrect results when rechecking using a "non-strict" join
                                369                 :                :      * condition, such as "src.col IS NOT DISTINCT FROM tgt.col".  To guard
                                370                 :                :      * against that, we add an additional "src IS NOT NULL" check to the join
                                371                 :                :      * condition, so that it does the right thing when performing a recheck
                                372                 :                :      * based on the output of the join subplan.
                                373                 :                :      */
                                374         [ +  + ]:            981 :     if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
                                375                 :                :     {
                                376                 :                :         Var        *var;
                                377                 :                :         NullTest   *ntest;
                                378                 :                : 
                                379                 :                :         /* source wholerow Var (nullable by the new join) */
                                380                 :             66 :         var = makeWholeRowVar(rt_fetch(sourcerti, parse->rtable),
                                381                 :                :                               sourcerti, 0, false);
                                382                 :             66 :         var->varnullingrels = bms_make_singleton(joinrti);
                                383                 :                : 
                                384                 :                :         /* "src IS NOT NULL" check */
                                385                 :             66 :         ntest = makeNode(NullTest);
                                386                 :             66 :         ntest->arg = (Expr *) var;
                                387                 :             66 :         ntest->nulltesttype = IS_NOT_NULL;
                                388                 :             66 :         ntest->argisrow = false;
                                389                 :             66 :         ntest->location = -1;
                                390                 :                : 
                                391                 :                :         /* combine it with the original join condition */
                                392                 :             66 :         parse->mergeJoinCondition =
                                393                 :             66 :             (Node *) make_and_qual((Node *) ntest, parse->mergeJoinCondition);
                                394                 :                :     }
                                395                 :                :     else
                                396                 :            915 :         parse->mergeJoinCondition = NULL;    /* join condition not needed */
                                397                 :                : }
                                398                 :                : 
                                399                 :                : /*
                                400                 :                :  * preprocess_relation_rtes
                                401                 :                :  *      Do the preprocessing work for any relation RTEs in the FROM clause.
                                402                 :                :  *
                                403                 :                :  * This scans the rangetable for relation RTEs and retrieves the necessary
                                404                 :                :  * catalog information for each relation.  Using this information, it clears
                                405                 :                :  * the inh flag for any relation that has no children, collects not-null
                                406                 :                :  * attribute numbers for any relation that has column not-null constraints, and
                                407                 :                :  * expands virtual generated columns for any relation that contains them.
                                408                 :                :  *
                                409                 :                :  * Note that expanding virtual generated columns may cause the query tree to
                                410                 :                :  * have new copies of rangetable entries.  Therefore, we have to use list_nth
                                411                 :                :  * instead of foreach when iterating over the query's rangetable.
                                412                 :                :  *
                                413                 :                :  * Returns a modified copy of the query tree, if any relations with virtual
                                414                 :                :  * generated columns are present.
                                415                 :                :  */
                                416                 :                : Query *
  148 rguo@postgresql.org       417                 :GNC      292895 : preprocess_relation_rtes(PlannerInfo *root)
                                418                 :                : {
                                419                 :         292895 :     Query      *parse = root->parse;
                                420                 :                :     int         rtable_size;
                                421                 :                :     int         rt_index;
                                422                 :                : 
                                423                 :         292895 :     rtable_size = list_length(parse->rtable);
                                424                 :                : 
                                425         [ +  + ]:         653543 :     for (rt_index = 0; rt_index < rtable_size; rt_index++)
                                426                 :                :     {
                                427                 :         360648 :         RangeTblEntry *rte = rt_fetch(rt_index + 1, parse->rtable);
                                428                 :                :         Relation    relation;
                                429                 :                : 
                                430                 :                :         /* We only care about relation RTEs. */
                                431         [ +  + ]:         360648 :         if (rte->rtekind != RTE_RELATION)
                                432                 :         116755 :             continue;
                                433                 :                : 
                                434                 :                :         /*
                                435                 :                :          * We need not lock the relation since it was already locked by the
                                436                 :                :          * rewriter.
                                437                 :                :          */
                                438                 :         243893 :         relation = table_open(rte->relid, NoLock);
                                439                 :                : 
                                440                 :                :         /*
                                441                 :                :          * Check to see if the relation actually has any children; if not,
                                442                 :                :          * clear the inh flag so we can treat it as a plain base relation.
                                443                 :                :          *
                                444                 :                :          * Note: this could give a false-positive result, if the rel once had
                                445                 :                :          * children but no longer does.  We used to be able to clear rte->inh
                                446                 :                :          * later on when we discovered that, but no more; we have to handle
                                447                 :                :          * such cases as full-fledged inheritance.
                                448                 :                :          */
                                449         [ +  + ]:         243893 :         if (rte->inh)
                                450                 :         203160 :             rte->inh = relation->rd_rel->relhassubclass;
                                451                 :                : 
                                452                 :                :         /*
                                453                 :                :          * Check to see if the relation has any column not-null constraints;
                                454                 :                :          * if so, retrieve the constraint information and store it in a
                                455                 :                :          * relation OID based hash table.
                                456                 :                :          */
                                457                 :         243893 :         get_relation_notnullatts(root, relation);
                                458                 :                : 
                                459                 :                :         /*
                                460                 :                :          * Check to see if the relation has any virtual generated columns; if
                                461                 :                :          * so, replace all Var nodes in the query that reference these columns
                                462                 :                :          * with the generation expressions.
                                463                 :                :          */
                                464                 :         243893 :         parse = expand_virtual_generated_columns(root, parse,
                                465                 :                :                                                  rte, rt_index + 1,
                                466                 :                :                                                  relation);
                                467                 :                : 
                                468                 :         243893 :         table_close(relation, NoLock);
                                469                 :                :     }
                                470                 :                : 
                                471                 :         292895 :     return parse;
                                472                 :                : }
                                473                 :                : 
                                474                 :                : /*
                                475                 :                :  * expand_virtual_generated_columns
                                476                 :                :  *      Expand virtual generated columns for the given relation.
                                477                 :                :  *
                                478                 :                :  * This checks whether the given relation has any virtual generated columns,
                                479                 :                :  * and if so, replaces all Var nodes in the query that reference those columns
                                480                 :                :  * with their generation expressions.
                                481                 :                :  *
                                482                 :                :  * Returns a modified copy of the query tree if the relation contains virtual
                                483                 :                :  * generated columns.
                                484                 :                :  */
                                485                 :                : static Query *
                                486                 :         243893 : expand_virtual_generated_columns(PlannerInfo *root, Query *parse,
                                487                 :                :                                  RangeTblEntry *rte, int rt_index,
                                488                 :                :                                  Relation relation)
                                489                 :                : {
                                490                 :                :     TupleDesc   tupdesc;
                                491                 :                : 
                                492                 :                :     /* Only normal relations can have virtual generated columns */
                                493         [ -  + ]:         243893 :     Assert(rte->rtekind == RTE_RELATION);
                                494                 :                : 
                                495                 :         243893 :     tupdesc = RelationGetDescr(relation);
                                496   [ +  +  +  + ]:         243893 :     if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
                                497                 :                :     {
                                498                 :            551 :         List       *tlist = NIL;
                                499                 :                :         pullup_replace_vars_context rvcontext;
                                500                 :                : 
                                501         [ +  + ]:           2099 :         for (int i = 0; i < tupdesc->natts; i++)
                                502                 :                :         {
                                503                 :           1548 :             Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
                                504                 :                :             TargetEntry *tle;
                                505                 :                : 
                                506         [ +  + ]:           1548 :             if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
                                507                 :                :             {
                                508                 :                :                 Node       *defexpr;
                                509                 :                : 
                                510                 :            722 :                 defexpr = build_generation_expression(relation, i + 1);
                                511                 :            722 :                 ChangeVarNodes(defexpr, 1, rt_index, 0);
                                512                 :                : 
                                513                 :            722 :                 tle = makeTargetEntry((Expr *) defexpr, i + 1, 0, false);
                                514                 :            722 :                 tlist = lappend(tlist, tle);
                                515                 :                :             }
                                516                 :                :             else
                                517                 :                :             {
                                518                 :                :                 Var        *var;
                                519                 :                : 
                                520                 :            826 :                 var = makeVar(rt_index,
                                521                 :            826 :                               i + 1,
                                522                 :                :                               attr->atttypid,
                                523                 :                :                               attr->atttypmod,
                                524                 :                :                               attr->attcollation,
                                525                 :                :                               0);
                                526                 :                : 
                                527                 :            826 :                 tle = makeTargetEntry((Expr *) var, i + 1, 0, false);
                                528                 :            826 :                 tlist = lappend(tlist, tle);
                                529                 :                :             }
                                530                 :                :         }
                                531                 :                : 
                                532         [ -  + ]:            551 :         Assert(list_length(tlist) > 0);
                                533         [ -  + ]:            551 :         Assert(!rte->lateral);
                                534                 :                : 
                                535                 :                :         /*
                                536                 :                :          * The relation's targetlist items are now in the appropriate form to
                                537                 :                :          * insert into the query, except that we may need to wrap them in
                                538                 :                :          * PlaceHolderVars.  Set up required context data for
                                539                 :                :          * pullup_replace_vars.
                                540                 :                :          */
                                541                 :            551 :         rvcontext.root = root;
                                542                 :            551 :         rvcontext.targetlist = tlist;
                                543                 :            551 :         rvcontext.target_rte = rte;
                                544                 :            551 :         rvcontext.result_relation = parse->resultRelation;
                                545                 :                :         /* won't need these values */
                                546                 :            551 :         rvcontext.relids = NULL;
                                547                 :            551 :         rvcontext.nullinfo = NULL;
                                548                 :                :         /* pass NULL for outer_hasSubLinks */
                                549                 :            551 :         rvcontext.outer_hasSubLinks = NULL;
                                550                 :            551 :         rvcontext.varno = rt_index;
                                551                 :                :         /* this flag will be set below, if needed */
                                552                 :            551 :         rvcontext.wrap_option = REPLACE_WRAP_NONE;
                                553                 :                :         /* initialize cache array with indexes 0 .. length(tlist) */
                                554                 :            551 :         rvcontext.rv_cache = palloc0((list_length(tlist) + 1) *
                                555                 :                :                                      sizeof(Node *));
                                556                 :                : 
                                557                 :                :         /*
                                558                 :                :          * If the query uses grouping sets, we need a PlaceHolderVar for each
                                559                 :                :          * expression of the relation's targetlist items.  (See comments in
                                560                 :                :          * pull_up_simple_subquery().)
                                561                 :                :          */
                                562         [ +  + ]:            551 :         if (parse->groupingSets)
                                563                 :              6 :             rvcontext.wrap_option = REPLACE_WRAP_ALL;
                                564                 :                : 
                                565                 :                :         /*
                                566                 :                :          * Apply pullup variable replacement throughout the query tree.
                                567                 :                :          */
                                568                 :            551 :         parse = (Query *) pullup_replace_vars((Node *) parse, &rvcontext);
                                569                 :                :     }
                                570                 :                : 
                                571                 :         243893 :     return parse;
                                572                 :                : }
                                573                 :                : 
                                574                 :                : /*
                                575                 :                :  * replace_empty_jointree
                                576                 :                :  *      If the Query's jointree is empty, replace it with a dummy RTE_RESULT
                                577                 :                :  *      relation.
                                578                 :                :  *
                                579                 :                :  * By doing this, we can avoid a bunch of corner cases that formerly existed
                                580                 :                :  * for SELECTs with omitted FROM clauses.  An example is that a subquery
                                581                 :                :  * with empty jointree previously could not be pulled up, because that would
                                582                 :                :  * have resulted in an empty relid set, making the subquery not uniquely
                                583                 :                :  * identifiable for join or PlaceHolderVar processing.
                                584                 :                :  *
                                585                 :                :  * Unlike most other functions in this file, this function doesn't recurse;
                                586                 :                :  * we rely on other processing to invoke it on sub-queries at suitable times.
                                587                 :                :  */
                                588                 :                : void
 2515 tgl@sss.pgh.pa.us         589                 :CBC      292895 : replace_empty_jointree(Query *parse)
                                590                 :                : {
                                591                 :                :     RangeTblEntry *rte;
                                592                 :                :     Index       rti;
                                593                 :                :     RangeTblRef *rtr;
                                594                 :                : 
                                595                 :                :     /* Nothing to do if jointree is already nonempty */
                                596         [ +  + ]:         292895 :     if (parse->jointree->fromlist != NIL)
                                597                 :         194319 :         return;
                                598                 :                : 
                                599                 :                :     /* We mustn't change it in the top level of a setop tree, either */
                                600         [ +  + ]:         102101 :     if (parse->setOperations)
                                601                 :           3525 :         return;
                                602                 :                : 
                                603                 :                :     /* Create suitable RTE */
                                604                 :          98576 :     rte = makeNode(RangeTblEntry);
                                605                 :          98576 :     rte->rtekind = RTE_RESULT;
                                606                 :          98576 :     rte->eref = makeAlias("*RESULT*", NIL);
                                607                 :                : 
                                608                 :                :     /* Add it to rangetable */
                                609                 :          98576 :     parse->rtable = lappend(parse->rtable, rte);
                                610                 :          98576 :     rti = list_length(parse->rtable);
                                611                 :                : 
                                612                 :                :     /* And jam a reference into the jointree */
                                613                 :          98576 :     rtr = makeNode(RangeTblRef);
                                614                 :          98576 :     rtr->rtindex = rti;
                                615                 :          98576 :     parse->jointree->fromlist = list_make1(rtr);
                                616                 :                : }
                                617                 :                : 
                                618                 :                : /*
                                619                 :                :  * pull_up_sublinks
                                620                 :                :  *      Attempt to pull up ANY and EXISTS SubLinks to be treated as
                                621                 :                :  *      semijoins or anti-semijoins.
                                622                 :                :  *
                                623                 :                :  * A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
                                624                 :                :  * sub-SELECT up to become a rangetable entry and treating the implied
                                625                 :                :  * comparisons as quals of a semijoin.  However, this optimization *only*
                                626                 :                :  * works at the top level of WHERE or a JOIN/ON clause, because we cannot
                                627                 :                :  * distinguish whether the ANY ought to return FALSE or NULL in cases
                                628                 :                :  * involving NULL inputs.  Also, in an outer join's ON clause we can only
                                629                 :                :  * do this if the sublink is degenerate (ie, references only the nullable
                                630                 :                :  * side of the join).  In that case it is legal to push the semijoin
                                631                 :                :  * down into the nullable side of the join.  If the sublink references any
                                632                 :                :  * nonnullable-side variables then it would have to be evaluated as part
                                633                 :                :  * of the outer join, which makes things way too complicated.
                                634                 :                :  *
                                635                 :                :  * Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
                                636                 :                :  * by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
                                637                 :                :  *
                                638                 :                :  * This routine searches for such clauses and does the necessary parsetree
                                639                 :                :  * transformations if any are found.
                                640                 :                :  *
                                641                 :                :  * This routine has to run before preprocess_expression(), so the quals
                                642                 :                :  * clauses are not yet reduced to implicit-AND format, and are not guaranteed
                                643                 :                :  * to be AND/OR-flat either.  That means we need to recursively search through
                                644                 :                :  * explicit AND clauses.  We stop as soon as we hit a non-AND item.
                                645                 :                :  */
                                646                 :                : void
 6331                           647                 :          19854 : pull_up_sublinks(PlannerInfo *root)
                                648                 :                : {
                                649                 :                :     Node       *jtnode;
                                650                 :                :     Relids      relids;
                                651                 :                : 
                                652                 :                :     /* Begin recursion through the jointree */
 6139                           653                 :          19854 :     jtnode = pull_up_sublinks_jointree_recurse(root,
                                654                 :          19854 :                                                (Node *) root->parse->jointree,
                                655                 :                :                                                &relids);
                                656                 :                : 
                                657                 :                :     /*
                                658                 :                :      * root->parse->jointree must always be a FromExpr, so insert a dummy one
                                659                 :                :      * if we got a bare RangeTblRef or JoinExpr out of the recursion.
                                660                 :                :      */
                                661         [ +  + ]:          19854 :     if (IsA(jtnode, FromExpr))
                                662                 :          15875 :         root->parse->jointree = (FromExpr *) jtnode;
                                663                 :                :     else
                                664                 :           3979 :         root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
 6331                           665                 :          19854 : }
                                666                 :                : 
                                667                 :                : /*
                                668                 :                :  * Recurse through jointree nodes for pull_up_sublinks()
                                669                 :                :  *
                                670                 :                :  * In addition to returning the possibly-modified jointree node, we return
                                671                 :                :  * a relids set of the contained rels into *relids.
                                672                 :                :  */
                                673                 :                : static Node *
                                674                 :          66411 : pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
                                675                 :                :                                   Relids *relids)
                                676                 :                : {
                                677                 :                :     /* Since this function recurses, it could be driven to stack overflow. */
 1091                           678                 :          66411 :     check_stack_depth();
                                679                 :                : 
 6331                           680         [ -  + ]:          66411 :     if (jtnode == NULL)
                                681                 :                :     {
 6331 tgl@sss.pgh.pa.us         682                 :UBC           0 :         *relids = NULL;
                                683                 :                :     }
 6331 tgl@sss.pgh.pa.us         684         [ +  + ]:CBC       66411 :     else if (IsA(jtnode, RangeTblRef))
                                685                 :                :     {
                                686                 :          36077 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                                687                 :                : 
                                688                 :          36077 :         *relids = bms_make_singleton(varno);
                                689                 :                :         /* jtnode is returned unmodified */
                                690                 :                :     }
                                691         [ +  + ]:          30334 :     else if (IsA(jtnode, FromExpr))
                                692                 :                :     {
                                693                 :          19968 :         FromExpr   *f = (FromExpr *) jtnode;
                                694                 :          19968 :         List       *newfromlist = NIL;
                                695                 :          19968 :         Relids      frelids = NULL;
                                696                 :                :         FromExpr   *newf;
                                697                 :                :         Node       *jtlink;
                                698                 :                :         ListCell   *l;
                                699                 :                : 
                                700                 :                :         /* First, recurse to process children and collect their relids */
                                701   [ +  -  +  +  :          41702 :         foreach(l, f->fromlist)
                                              +  + ]
                                702                 :                :         {
                                703                 :                :             Node       *newchild;
                                704                 :                :             Relids      childrelids;
                                705                 :                : 
                                706                 :          21734 :             newchild = pull_up_sublinks_jointree_recurse(root,
                                707                 :          21734 :                                                          lfirst(l),
                                708                 :                :                                                          &childrelids);
                                709                 :          21734 :             newfromlist = lappend(newfromlist, newchild);
                                710                 :          21734 :             frelids = bms_join(frelids, childrelids);
                                711                 :                :         }
                                712                 :                :         /* Build the replacement FromExpr; no quals yet */
 6139                           713                 :          19968 :         newf = makeFromExpr(newfromlist, NULL);
                                714                 :                :         /* Set up a link representing the rebuilt jointree */
                                715                 :          19968 :         jtlink = (Node *) newf;
                                716                 :                :         /* Now process qual --- all children are available for use */
 5073                           717                 :          19968 :         newf->quals = pull_up_sublinks_qual_recurse(root, f->quals,
                                718                 :                :                                                     &jtlink, frelids,
                                719                 :                :                                                     NULL, NULL);
                                720                 :                : 
                                721                 :                :         /*
                                722                 :                :          * Note that the result will be either newf, or a stack of JoinExprs
                                723                 :                :          * with newf at the base.  We rely on subsequent optimization steps to
                                724                 :                :          * flatten this and rearrange the joins as needed.
                                725                 :                :          *
                                726                 :                :          * Although we could include the pulled-up subqueries in the returned
                                727                 :                :          * relids, there's no need since upper quals couldn't refer to their
                                728                 :                :          * outputs anyway.
                                729                 :                :          */
 6331                           730                 :          19968 :         *relids = frelids;
 6139                           731                 :          19968 :         jtnode = jtlink;
                                732                 :                :     }
 6331                           733         [ +  - ]:          10366 :     else if (IsA(jtnode, JoinExpr))
                                734                 :                :     {
                                735                 :                :         JoinExpr   *j;
                                736                 :                :         Relids      leftrelids;
                                737                 :                :         Relids      rightrelids;
                                738                 :                :         Node       *jtlink;
                                739                 :                : 
                                740                 :                :         /*
                                741                 :                :          * Make a modifiable copy of join node, but don't bother copying its
                                742                 :                :          * subnodes (yet).
                                743                 :                :          */
    7 michael@paquier.xyz       744                 :GNC       10366 :         j = palloc_object(JoinExpr);
 6331 tgl@sss.pgh.pa.us         745                 :CBC       10366 :         memcpy(j, jtnode, sizeof(JoinExpr));
 6139                           746                 :          10366 :         jtlink = (Node *) j;
                                747                 :                : 
                                748                 :                :         /* Recurse to process children and collect their relids */
 6331                           749                 :          10366 :         j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
                                750                 :                :                                                     &leftrelids);
                                751                 :          10366 :         j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
                                752                 :                :                                                     &rightrelids);
                                753                 :                : 
                                754                 :                :         /*
                                755                 :                :          * Now process qual, showing appropriate child relids as available,
                                756                 :                :          * and attach any pulled-up jointree items at the right place. In the
                                757                 :                :          * inner-join case we put new JoinExprs above the existing one (much
                                758                 :                :          * as for a FromExpr-style join).  In outer-join cases the new
                                759                 :                :          * JoinExprs must go into the nullable side of the outer join. The
                                760                 :                :          * point of the available_rels machinations is to ensure that we only
                                761                 :                :          * pull up quals for which that's okay.
                                762                 :                :          *
                                763                 :                :          * We don't expect to see any pre-existing JOIN_SEMI, JOIN_ANTI,
                                764                 :                :          * JOIN_RIGHT_SEMI, or JOIN_RIGHT_ANTI jointypes here.
                                765                 :                :          */
                                766   [ +  +  +  +  :          10366 :         switch (j->jointype)
                                                 - ]
                                767                 :                :         {
                                768                 :           4676 :             case JOIN_INNER:
                                769                 :           4676 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
                                770                 :                :                                                          &jtlink,
                                771                 :                :                                                          bms_union(leftrelids,
                                772                 :                :                                                                    rightrelids),
                                773                 :                :                                                          NULL, NULL);
                                774                 :           4676 :                 break;
                                775                 :           5636 :             case JOIN_LEFT:
                                776                 :           5636 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
                                777                 :                :                                                          &j->rarg,
                                778                 :                :                                                          rightrelids,
                                779                 :                :                                                          NULL, NULL);
                                780                 :           5636 :                 break;
                                781                 :              6 :             case JOIN_FULL:
                                782                 :                :                 /* can't do anything with full-join quals */
                                783                 :              6 :                 break;
                                784                 :             48 :             case JOIN_RIGHT:
                                785                 :             48 :                 j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
                                786                 :                :                                                          &j->larg,
                                787                 :                :                                                          leftrelids,
                                788                 :                :                                                          NULL, NULL);
                                789                 :             48 :                 break;
 6331 tgl@sss.pgh.pa.us         790                 :UBC           0 :             default:
                                791         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                                792                 :                :                      (int) j->jointype);
                                793                 :                :                 break;
                                794                 :                :         }
                                795                 :                : 
                                796                 :                :         /*
                                797                 :                :          * Although we could include the pulled-up subqueries in the returned
                                798                 :                :          * relids, there's no need since upper quals couldn't refer to their
                                799                 :                :          * outputs anyway.  But we *do* need to include the join's own rtindex
                                800                 :                :          * because we haven't yet collapsed join alias variables, so upper
                                801                 :                :          * levels would mistakenly think they couldn't use references to this
                                802                 :                :          * join.
                                803                 :                :          */
 6139 tgl@sss.pgh.pa.us         804                 :CBC       10366 :         *relids = bms_join(leftrelids, rightrelids);
                                805         [ +  - ]:          10366 :         if (j->rtindex)
                                806                 :          10366 :             *relids = bms_add_member(*relids, j->rtindex);
                                807                 :          10366 :         jtnode = jtlink;
                                808                 :                :     }
                                809                 :                :     else
 6331 tgl@sss.pgh.pa.us         810         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                                811                 :                :              (int) nodeTag(jtnode));
 6331 tgl@sss.pgh.pa.us         812                 :CBC       66411 :     return jtnode;
                                813                 :                : }
                                814                 :                : 
                                815                 :                : /*
                                816                 :                :  * Recurse through top-level qual nodes for pull_up_sublinks()
                                817                 :                :  *
                                818                 :                :  * jtlink1 points to the link in the jointree where any new JoinExprs should
                                819                 :                :  * be inserted if they reference available_rels1 (i.e., available_rels1
                                820                 :                :  * denotes the relations present underneath jtlink1).  Optionally, jtlink2 can
                                821                 :                :  * point to a second link where new JoinExprs should be inserted if they
                                822                 :                :  * reference available_rels2 (pass NULL for both those arguments if not used).
                                823                 :                :  * Note that SubLinks referencing both sets of variables cannot be optimized.
                                824                 :                :  * If we find multiple pull-up-able SubLinks, they'll get stacked onto jtlink1
                                825                 :                :  * and/or jtlink2 in the order we encounter them.  We rely on subsequent
                                826                 :                :  * optimization to rearrange the stack if appropriate.
                                827                 :                :  *
                                828                 :                :  * Returns the replacement qual node, or NULL if the qual should be removed.
                                829                 :                :  */
                                830                 :                : static Node *
                                831                 :          62319 : pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
                                832                 :                :                               Node **jtlink1, Relids available_rels1,
                                833                 :                :                               Node **jtlink2, Relids available_rels2)
                                834                 :                : {
 8367                           835         [ +  + ]:          62319 :     if (node == NULL)
                                836                 :           3918 :         return NULL;
                                837         [ +  + ]:          58401 :     if (IsA(node, SubLink))
                                838                 :                :     {
 8171 bruce@momjian.us          839                 :           2896 :         SubLink    *sublink = (SubLink *) node;
                                840                 :                :         JoinExpr   *j;
                                841                 :                :         Relids      child_rels;
                                842                 :                : 
                                843                 :                :         /* Is it a convertible ANY or EXISTS clause? */
 6334 tgl@sss.pgh.pa.us         844         [ +  + ]:           2896 :         if (sublink->subLinkType == ANY_SUBLINK)
                                845                 :                :         {
                                846                 :                :             ScalarArrayOpExpr *saop;
                                847                 :                : 
  257 akorotkov@postgresql      848         [ +  + ]:           2405 :             if ((saop = convert_VALUES_to_ANY(root,
                                849                 :                :                                               sublink->testexpr,
                                850                 :           2405 :                                               (Query *) sublink->subselect)) != NULL)
                                851                 :                : 
                                852                 :                :                 /*
                                853                 :                :                  * The VALUES sequence was simplified.  Nothing more to do
                                854                 :                :                  * here.
                                855                 :                :                  */
                                856                 :             42 :                 return (Node *) saop;
                                857                 :                : 
 5073 tgl@sss.pgh.pa.us         858         [ +  + ]:           2363 :             if ((j = convert_ANY_sublink_to_join(root, sublink,
                                859                 :                :                                                  available_rels1)) != NULL)
                                860                 :                :             {
                                861                 :                :                 /* Yes; insert the new join node into the join tree */
                                862                 :           2310 :                 j->larg = *jtlink1;
                                863                 :           2310 :                 *jtlink1 = (Node *) j;
                                864                 :                :                 /* Recursively process pulled-up jointree nodes */
                                865                 :           2310 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
                                866                 :                :                                                             j->rarg,
                                867                 :                :                                                             &child_rels);
                                868                 :                : 
                                869                 :                :                 /*
                                870                 :                :                  * Now recursively process the pulled-up quals.  Any inserted
                                871                 :                :                  * joins can get stacked onto either j->larg or j->rarg,
                                872                 :                :                  * depending on which rels they reference.
                                873                 :                :                  */
                                874                 :           2310 :                 j->quals = pull_up_sublinks_qual_recurse(root,
                                875                 :                :                                                          j->quals,
                                876                 :                :                                                          &j->larg,
                                877                 :                :                                                          available_rels1,
                                878                 :                :                                                          &j->rarg,
                                879                 :                :                                                          child_rels);
                                880                 :                :                 /* Return NULL representing constant TRUE */
                                881                 :           2310 :                 return NULL;
                                882                 :                :             }
                                883   [ +  +  -  + ]:             56 :             if (available_rels2 != NULL &&
                                884                 :              3 :                 (j = convert_ANY_sublink_to_join(root, sublink,
                                885                 :                :                                                  available_rels2)) != NULL)
                                886                 :                :             {
                                887                 :                :                 /* Yes; insert the new join node into the join tree */
 5073 tgl@sss.pgh.pa.us         888                 :UBC           0 :                 j->larg = *jtlink2;
                                889                 :              0 :                 *jtlink2 = (Node *) j;
                                890                 :                :                 /* Recursively process pulled-up jointree nodes */
 5343                           891                 :              0 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
                                892                 :                :                                                             j->rarg,
                                893                 :                :                                                             &child_rels);
                                894                 :                : 
                                895                 :                :                 /*
                                896                 :                :                  * Now recursively process the pulled-up quals.  Any inserted
                                897                 :                :                  * joins can get stacked onto either j->larg or j->rarg,
                                898                 :                :                  * depending on which rels they reference.
                                899                 :                :                  */
                                900                 :              0 :                 j->quals = pull_up_sublinks_qual_recurse(root,
                                901                 :                :                                                          j->quals,
                                902                 :                :                                                          &j->larg,
                                903                 :                :                                                          available_rels2,
                                904                 :                :                                                          &j->rarg,
                                905                 :                :                                                          child_rels);
                                906                 :                :                 /* Return NULL representing constant TRUE */
 6139                           907                 :              0 :                 return NULL;
                                908                 :                :             }
                                909                 :                :         }
 6334 tgl@sss.pgh.pa.us         910         [ +  + ]:CBC         491 :         else if (sublink->subLinkType == EXISTS_SUBLINK)
                                911                 :                :         {
 5073                           912         [ +  + ]:            461 :             if ((j = convert_EXISTS_sublink_to_join(root, sublink, false,
                                913                 :                :                                                     available_rels1)) != NULL)
                                914                 :                :             {
                                915                 :                :                 /* Yes; insert the new join node into the join tree */
                                916                 :            377 :                 j->larg = *jtlink1;
                                917                 :            377 :                 *jtlink1 = (Node *) j;
                                918                 :                :                 /* Recursively process pulled-up jointree nodes */
 5343                           919                 :            377 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
                                920                 :                :                                                             j->rarg,
                                921                 :                :                                                             &child_rels);
                                922                 :                : 
                                923                 :                :                 /*
                                924                 :                :                  * Now recursively process the pulled-up quals.  Any inserted
                                925                 :                :                  * joins can get stacked onto either j->larg or j->rarg,
                                926                 :                :                  * depending on which rels they reference.
                                927                 :                :                  */
                                928                 :            377 :                 j->quals = pull_up_sublinks_qual_recurse(root,
                                929                 :                :                                                          j->quals,
                                930                 :                :                                                          &j->larg,
                                931                 :                :                                                          available_rels1,
                                932                 :                :                                                          &j->rarg,
                                933                 :                :                                                          child_rels);
                                934                 :                :                 /* Return NULL representing constant TRUE */
 5073                           935                 :            377 :                 return NULL;
                                936                 :                :             }
                                937   [ +  +  +  - ]:            100 :             if (available_rels2 != NULL &&
                                938                 :             16 :                 (j = convert_EXISTS_sublink_to_join(root, sublink, false,
                                939                 :                :                                                     available_rels2)) != NULL)
                                940                 :                :             {
                                941                 :                :                 /* Yes; insert the new join node into the join tree */
                                942                 :             16 :                 j->larg = *jtlink2;
                                943                 :             16 :                 *jtlink2 = (Node *) j;
                                944                 :                :                 /* Recursively process pulled-up jointree nodes */
                                945                 :             16 :                 j->rarg = pull_up_sublinks_jointree_recurse(root,
                                946                 :                :                                                             j->rarg,
                                947                 :                :                                                             &child_rels);
                                948                 :                : 
                                949                 :                :                 /*
                                950                 :                :                  * Now recursively process the pulled-up quals.  Any inserted
                                951                 :                :                  * joins can get stacked onto either j->larg or j->rarg,
                                952                 :                :                  * depending on which rels they reference.
                                953                 :                :                  */
                                954                 :             16 :                 j->quals = pull_up_sublinks_qual_recurse(root,
                                955                 :                :                                                          j->quals,
                                956                 :                :                                                          &j->larg,
                                957                 :                :                                                          available_rels2,
                                958                 :                :                                                          &j->rarg,
                                959                 :                :                                                          child_rels);
                                960                 :                :                 /* Return NULL representing constant TRUE */
 6139                           961                 :             16 :                 return NULL;
                                962                 :                :             }
                                963                 :                :         }
                                964                 :                :         /* Else return it unmodified */
 6334                           965                 :            151 :         return node;
                                966                 :                :     }
 2514                           967         [ +  + ]:          55505 :     if (is_notclause(node))
                                968                 :                :     {
                                969                 :                :         /* If the immediate argument of NOT is EXISTS, try to convert */
 6334                           970                 :           3786 :         SubLink    *sublink = (SubLink *) get_notclausearg((Expr *) node);
                                971                 :                :         JoinExpr   *j;
                                972                 :                :         Relids      child_rels;
                                973                 :                : 
                                974   [ +  -  +  + ]:           3786 :         if (sublink && IsA(sublink, SubLink))
                                975                 :                :         {
                                976         [ +  + ]:           1443 :             if (sublink->subLinkType == EXISTS_SUBLINK)
                                977                 :                :             {
 5073                           978         [ +  + ]:           1395 :                 if ((j = convert_EXISTS_sublink_to_join(root, sublink, true,
                                979                 :                :                                                         available_rels1)) != NULL)
                                980                 :                :                 {
                                981                 :                :                     /* Yes; insert the new join node into the join tree */
                                982                 :           1388 :                     j->larg = *jtlink1;
                                983                 :           1388 :                     *jtlink1 = (Node *) j;
                                984                 :                :                     /* Recursively process pulled-up jointree nodes */
                                985                 :           1388 :                     j->rarg = pull_up_sublinks_jointree_recurse(root,
                                986                 :                :                                                                 j->rarg,
                                987                 :                :                                                                 &child_rels);
                                988                 :                : 
                                989                 :                :                     /*
                                990                 :                :                      * Now recursively process the pulled-up quals.  Because
                                991                 :                :                      * we are underneath a NOT, we can't pull up sublinks that
                                992                 :                :                      * reference the left-hand stuff, but it's still okay to
                                993                 :                :                      * pull up sublinks referencing j->rarg.
                                994                 :                :                      */
                                995                 :           1388 :                     j->quals = pull_up_sublinks_qual_recurse(root,
                                996                 :                :                                                              j->quals,
                                997                 :                :                                                              &j->rarg,
                                998                 :                :                                                              child_rels,
                                999                 :                :                                                              NULL, NULL);
                               1000                 :                :                     /* Return NULL representing constant TRUE */
                               1001                 :           1388 :                     return NULL;
                               1002                 :                :                 }
                               1003   [ -  +  -  - ]:              7 :                 if (available_rels2 != NULL &&
 5073 tgl@sss.pgh.pa.us        1004                 :UBC           0 :                     (j = convert_EXISTS_sublink_to_join(root, sublink, true,
                               1005                 :                :                                                         available_rels2)) != NULL)
                               1006                 :                :                 {
                               1007                 :                :                     /* Yes; insert the new join node into the join tree */
                               1008                 :              0 :                     j->larg = *jtlink2;
                               1009                 :              0 :                     *jtlink2 = (Node *) j;
                               1010                 :                :                     /* Recursively process pulled-up jointree nodes */
 5343                          1011                 :              0 :                     j->rarg = pull_up_sublinks_jointree_recurse(root,
                               1012                 :                :                                                                 j->rarg,
                               1013                 :                :                                                                 &child_rels);
                               1014                 :                : 
                               1015                 :                :                     /*
                               1016                 :                :                      * Now recursively process the pulled-up quals.  Because
                               1017                 :                :                      * we are underneath a NOT, we can't pull up sublinks that
                               1018                 :                :                      * reference the left-hand stuff, but it's still okay to
                               1019                 :                :                      * pull up sublinks referencing j->rarg.
                               1020                 :                :                      */
                               1021                 :              0 :                     j->quals = pull_up_sublinks_qual_recurse(root,
                               1022                 :                :                                                              j->quals,
                               1023                 :                :                                                              &j->rarg,
                               1024                 :                :                                                              child_rels,
                               1025                 :                :                                                              NULL, NULL);
                               1026                 :                :                     /* Return NULL representing constant TRUE */
 6139                          1027                 :              0 :                     return NULL;
                               1028                 :                :                 }
                               1029                 :                :             }
                               1030                 :                :         }
                               1031                 :                :         /* Else return it unmodified */
 6334 tgl@sss.pgh.pa.us        1032                 :CBC        2398 :         return node;
                               1033                 :                :     }
 2514                          1034         [ +  + ]:          51719 :     if (is_andclause(node))
                               1035                 :                :     {
                               1036                 :                :         /* Recurse into AND clause */
 8171 bruce@momjian.us         1037                 :           9699 :         List       *newclauses = NIL;
                               1038                 :                :         ListCell   *l;
                               1039                 :                : 
 7875 neilc@samurai.com        1040   [ +  -  +  +  :          37599 :         foreach(l, ((BoolExpr *) node)->args)
                                              +  + ]
                               1041                 :                :         {
                               1042                 :          27900 :             Node       *oldclause = (Node *) lfirst(l);
                               1043                 :                :             Node       *newclause;
                               1044                 :                : 
 6139 tgl@sss.pgh.pa.us        1045                 :          27900 :             newclause = pull_up_sublinks_qual_recurse(root,
                               1046                 :                :                                                       oldclause,
                               1047                 :                :                                                       jtlink1,
                               1048                 :                :                                                       available_rels1,
                               1049                 :                :                                                       jtlink2,
                               1050                 :                :                                                       available_rels2);
                               1051         [ +  + ]:          27900 :             if (newclause)
                               1052                 :          25004 :                 newclauses = lappend(newclauses, newclause);
                               1053                 :                :         }
                               1054                 :                :         /* We might have got back fewer clauses than we started with */
                               1055         [ +  + ]:           9699 :         if (newclauses == NIL)
                               1056                 :             63 :             return NULL;
                               1057         [ +  + ]:           9636 :         else if (list_length(newclauses) == 1)
                               1058                 :            582 :             return (Node *) linitial(newclauses);
                               1059                 :                :         else
                               1060                 :           9054 :             return (Node *) make_andclause(newclauses);
                               1061                 :                :     }
                               1062                 :                :     /* Stop if not an AND */
 8367                          1063                 :          42020 :     return node;
                               1064                 :                : }
                               1065                 :                : 
                               1066                 :                : /*
                               1067                 :                :  * preprocess_function_rtes
                               1068                 :                :  *      Constant-simplify any FUNCTION RTEs in the FROM clause, and then
                               1069                 :                :  *      attempt to "inline" any that can be converted to simple subqueries.
                               1070                 :                :  *
                               1071                 :                :  * If an RTE_FUNCTION rtable entry invokes a set-returning SQL function that
                               1072                 :                :  * contains just a simple SELECT, we can convert the rtable entry to an
                               1073                 :                :  * RTE_SUBQUERY entry exposing the SELECT directly.  Other sorts of functions
                               1074                 :                :  * are also inline-able if they have a support function that can generate
                               1075                 :                :  * the replacement sub-Query.  This is especially useful if the subquery can
                               1076                 :                :  * then be "pulled up" for further optimization, but we do it even if not,
                               1077                 :                :  * to reduce executor overhead.
                               1078                 :                :  *
                               1079                 :                :  * This has to be done before we have started to do any optimization of
                               1080                 :                :  * subqueries, else any such steps wouldn't get applied to subqueries
                               1081                 :                :  * obtained via inlining.  However, we do it after pull_up_sublinks
                               1082                 :                :  * so that we can inline any functions used in SubLink subselects.
                               1083                 :                :  *
                               1084                 :                :  * The reason for applying const-simplification at this stage is that
                               1085                 :                :  * (a) we'd need to do it anyway to inline a SRF, and (b) by doing it now,
                               1086                 :                :  * we can be sure that pull_up_constant_function() will see constants
                               1087                 :                :  * if there are constants to be seen.  This approach also guarantees
                               1088                 :                :  * that every FUNCTION RTE has been const-simplified, allowing planner.c's
                               1089                 :                :  * preprocess_expression() to skip doing it again.
                               1090                 :                :  *
                               1091                 :                :  * Like most of the planner, this feels free to scribble on its input data
                               1092                 :                :  * structure.
                               1093                 :                :  */
                               1094                 :                : void
 2330                          1095                 :         291092 : preprocess_function_rtes(PlannerInfo *root)
                               1096                 :                : {
                               1097                 :                :     ListCell   *rt;
                               1098                 :                : 
 6483                          1099   [ +  -  +  +  :         752583 :     foreach(rt, root->parse->rtable)
                                              +  + ]
                               1100                 :                :     {
                               1101                 :         461494 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
                               1102                 :                : 
                               1103         [ +  + ]:         461494 :         if (rte->rtekind == RTE_FUNCTION)
                               1104                 :                :         {
                               1105                 :                :             Query      *funcquery;
                               1106                 :                : 
                               1107                 :                :             /* Apply const-simplification */
 2330                          1108                 :          25427 :             rte->functions = (List *)
                               1109                 :          25427 :                 eval_const_expressions(root, (Node *) rte->functions);
                               1110                 :                : 
                               1111                 :                :             /* Check safety of expansion, and expand if possible */
   25 tgl@sss.pgh.pa.us        1112                 :GNC       25427 :             funcquery = inline_function_in_from(root, rte);
 6483 tgl@sss.pgh.pa.us        1113         [ +  + ]:CBC       25424 :             if (funcquery)
                               1114                 :                :             {
                               1115                 :                :                 /* Successful expansion, convert the RTE to a subquery */
                               1116                 :            123 :                 rte->rtekind = RTE_SUBQUERY;
                               1117                 :            123 :                 rte->subquery = funcquery;
 2647                          1118                 :            123 :                 rte->security_barrier = false;
                               1119                 :                : 
                               1120                 :                :                 /*
                               1121                 :                :                  * Clear fields that should not be set in a subquery RTE.
                               1122                 :                :                  * However, we leave rte->functions filled in for the moment,
                               1123                 :                :                  * in case makeWholeRowVar needs to consult it.  We'll clear
                               1124                 :                :                  * it in setrefs.c (see add_rte_to_flat_rtable) so that this
                               1125                 :                :                  * abuse of the data structure doesn't escape the planner.
                               1126                 :                :                  */
                               1127                 :            123 :                 rte->funcordinality = false;
                               1128                 :                :             }
                               1129                 :                :         }
                               1130                 :                :     }
 6483                          1131                 :         291089 : }
                               1132                 :                : 
                               1133                 :                : /*
                               1134                 :                :  * pull_up_subqueries
                               1135                 :                :  *      Look for subqueries in the rangetable that can be pulled up into
                               1136                 :                :  *      the parent query.  If the subquery has no special features like
                               1137                 :                :  *      grouping/aggregation then we can merge it into the parent's jointree.
                               1138                 :                :  *      Also, subqueries that are simple UNION ALL structures can be
                               1139                 :                :  *      converted into "append relations".
                               1140                 :                :  */
                               1141                 :                : void
 3934                          1142                 :         291089 : pull_up_subqueries(PlannerInfo *root)
                               1143                 :                : {
                               1144                 :                :     /* Top level of jointree must always be a FromExpr */
                               1145         [ -  + ]:         291089 :     Assert(IsA(root->parse->jointree, FromExpr));
                               1146                 :                :     /* Recursion starts with no containing join nor appendrel */
                               1147                 :         582175 :     root->parse->jointree = (FromExpr *)
                               1148                 :         291089 :         pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
                               1149                 :                :                                    NULL, NULL);
                               1150                 :                :     /* We should still have a FromExpr */
                               1151         [ -  + ]:         291086 :     Assert(IsA(root->parse->jointree, FromExpr));
 4875                          1152                 :         291086 : }
                               1153                 :                : 
                               1154                 :                : /*
                               1155                 :                :  * pull_up_subqueries_recurse
                               1156                 :                :  *      Recursive guts of pull_up_subqueries.
                               1157                 :                :  *
                               1158                 :                :  * This recursively processes the jointree and returns a modified jointree.
                               1159                 :                :  *
                               1160                 :                :  * If this jointree node is within either side of an outer join, then
                               1161                 :                :  * lowest_outer_join references the lowest such JoinExpr node; otherwise
                               1162                 :                :  * it is NULL.  We use this to constrain the effects of LATERAL subqueries.
                               1163                 :                :  *
                               1164                 :                :  * If we are looking at a member subquery of an append relation,
                               1165                 :                :  * containing_appendrel describes that relation; else it is NULL.
                               1166                 :                :  * This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
                               1167                 :                :  * items, and puts some additional restrictions on what can be pulled up.
                               1168                 :                :  *
                               1169                 :                :  * A tricky aspect of this code is that if we pull up a subquery we have
                               1170                 :                :  * to replace Vars that reference the subquery's outputs throughout the
                               1171                 :                :  * parent query, including quals attached to jointree nodes above the one
                               1172                 :                :  * we are currently processing!  We handle this by being careful to maintain
                               1173                 :                :  * validity of the jointree structure while recursing, in the following sense:
                               1174                 :                :  * whenever we recurse, all qual expressions in the tree must be reachable
                               1175                 :                :  * from the top level, in case the recursive call needs to modify them.
                               1176                 :                :  *
                               1177                 :                :  * Notice also that we can't turn pullup_replace_vars loose on the whole
                               1178                 :                :  * jointree, because it'd return a mutated copy of the tree; we have to
                               1179                 :                :  * invoke it just on the quals, instead.  This behavior is what makes it
                               1180                 :                :  * reasonable to pass lowest_outer_join as a pointer rather than some
                               1181                 :                :  * more-indirect way of identifying the lowest OJ.  Likewise, we don't
                               1182                 :                :  * replace append_rel_list members but only their substructure, so the
                               1183                 :                :  * containing_appendrel reference is safe to use.
                               1184                 :                :  */
                               1185                 :                : static Node *
                               1186                 :         720160 : pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
                               1187                 :                :                            JoinExpr *lowest_outer_join,
                               1188                 :                :                            AppendRelInfo *containing_appendrel)
                               1189                 :                : {
                               1190                 :                :     /* Since this function recurses, it could be driven to stack overflow. */
 1091                          1191                 :         720160 :     check_stack_depth();
                               1192                 :                :     /* Also, since it's a bit expensive, let's check for query cancel. */
                               1193         [ -  + ]:         720160 :     CHECK_FOR_INTERRUPTS();
                               1194                 :                : 
 3934                          1195         [ -  + ]:         720160 :     Assert(jtnode != NULL);
 8367                          1196         [ +  + ]:         720160 :     if (IsA(jtnode, RangeTblRef))
                               1197                 :                :     {
                               1198                 :         372753 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
 7257                          1199                 :         372753 :         RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
                               1200                 :                : 
                               1201                 :                :         /*
                               1202                 :                :          * Is this a subquery RTE, and if so, is the subquery simple enough to
                               1203                 :                :          * pull up?
                               1204                 :                :          *
                               1205                 :                :          * If we are looking at an append-relation member, we can't pull it up
                               1206                 :                :          * unless is_safe_append_member says so.
                               1207                 :                :          */
 7891                          1208   [ +  +  +  + ]:         405877 :         if (rte->rtekind == RTE_SUBQUERY &&
 1791                          1209         [ +  + ]:          55120 :             is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) &&
 6077                          1210         [ +  + ]:           6356 :             (containing_appendrel == NULL ||
                               1211                 :           6356 :              is_safe_append_member(rte->subquery)))
 7257                          1212                 :          18944 :             return pull_up_simple_subquery(root, jtnode, rte,
                               1213                 :                :                                            lowest_outer_join,
                               1214                 :                :                                            containing_appendrel);
                               1215                 :                : 
                               1216                 :                :         /*
                               1217                 :                :          * Alternatively, is it a simple UNION ALL subquery?  If so, flatten
                               1218                 :                :          * into an "append relation".
                               1219                 :                :          *
                               1220                 :                :          * It's safe to do this regardless of whether this query is itself an
                               1221                 :                :          * appendrel member.  (If you're thinking we should try to flatten the
                               1222                 :                :          * two levels of appendrel together, you're right; but we handle that
                               1223                 :                :          * in set_append_rel_pathlist, not here.)
                               1224                 :                :          */
                               1225   [ +  +  +  + ]:         367989 :         if (rte->rtekind == RTE_SUBQUERY &&
                               1226                 :          14180 :             is_simple_union_all(rte->subquery))
                               1227                 :           2464 :             return pull_up_simple_union_all(root, jtnode, rte);
                               1228                 :                : 
                               1229                 :                :         /*
                               1230                 :                :          * Or perhaps it's a simple VALUES RTE?
                               1231                 :                :          *
                               1232                 :                :          * We don't allow VALUES pullup below an outer join nor into an
                               1233                 :                :          * appendrel (such cases are impossible anyway at the moment).
                               1234                 :                :          */
 3934                          1235   [ +  +  +  - ]:         351345 :         if (rte->rtekind == RTE_VALUES &&
                               1236         [ +  - ]:           6539 :             lowest_outer_join == NULL &&
                               1237         [ +  + ]:           6539 :             containing_appendrel == NULL &&
 2515                          1238                 :           6539 :             is_simple_values(root, rte))
 3934                          1239                 :           2297 :             return pull_up_simple_values(root, jtnode, rte);
                               1240                 :                : 
                               1241                 :                :         /*
                               1242                 :                :          * Or perhaps it's a FUNCTION RTE that we could inline?
                               1243                 :                :          */
 2330                          1244         [ +  + ]:         349048 :         if (rte->rtekind == RTE_FUNCTION)
                               1245                 :          25301 :             return pull_up_constant_function(root, jtnode, rte,
                               1246                 :                :                                              containing_appendrel);
                               1247                 :                : 
                               1248                 :                :         /* Otherwise, do nothing at this node. */
                               1249                 :                :     }
 8367                          1250         [ +  + ]:         347407 :     else if (IsA(jtnode, FromExpr))
                               1251                 :                :     {
                               1252                 :         296058 :         FromExpr   *f = (FromExpr *) jtnode;
                               1253                 :                :         ListCell   *l;
                               1254                 :                : 
 6077                          1255         [ -  + ]:         296058 :         Assert(containing_appendrel == NULL);
                               1256                 :                :         /* Recursively transform all the child nodes */
 8367                          1257   [ +  +  +  +  :         614142 :         foreach(l, f->fromlist)
                                              +  + ]
                               1258                 :                :         {
 4875                          1259                 :         318087 :             lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l),
                               1260                 :                :                                                    lowest_outer_join,
                               1261                 :                :                                                    NULL);
                               1262                 :                :         }
                               1263                 :                :     }
 8367                          1264         [ +  - ]:          51349 :     else if (IsA(jtnode, JoinExpr))
                               1265                 :                :     {
                               1266                 :          51349 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               1267                 :                : 
 6077                          1268         [ -  + ]:          51349 :         Assert(containing_appendrel == NULL);
                               1269                 :                :         /* Recurse, being careful to tell myself when inside outer join */
 8367                          1270   [ +  +  +  +  :          51349 :         switch (j->jointype)
                                                 - ]
                               1271                 :                :         {
                               1272                 :          22998 :             case JOIN_INNER:
 4875                          1273                 :          22998 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
                               1274                 :                :                                                      lowest_outer_join,
                               1275                 :                :                                                      NULL);
                               1276                 :          22998 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
                               1277                 :                :                                                      lowest_outer_join,
                               1278                 :                :                                                      NULL);
 8367                          1279                 :          22998 :                 break;
                               1280                 :          27193 :             case JOIN_LEFT:
                               1281                 :                :             case JOIN_SEMI:
                               1282                 :                :             case JOIN_ANTI:
 4875                          1283                 :          27193 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
                               1284                 :                :                                                      j,
                               1285                 :                :                                                      NULL);
                               1286                 :          27193 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
                               1287                 :                :                                                      j,
                               1288                 :                :                                                      NULL);
 8367                          1289                 :          27193 :                 break;
                               1290                 :            548 :             case JOIN_FULL:
 4875                          1291                 :            548 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
                               1292                 :                :                                                      j,
                               1293                 :                :                                                      NULL);
                               1294                 :            548 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
                               1295                 :                :                                                      j,
                               1296                 :                :                                                      NULL);
 8367                          1297                 :            548 :                 break;
                               1298                 :            610 :             case JOIN_RIGHT:
 4875                          1299                 :            610 :                 j->larg = pull_up_subqueries_recurse(root, j->larg,
                               1300                 :                :                                                      j,
                               1301                 :                :                                                      NULL);
                               1302                 :            610 :                 j->rarg = pull_up_subqueries_recurse(root, j->rarg,
                               1303                 :                :                                                      j,
                               1304                 :                :                                                      NULL);
 8367                          1305                 :            610 :                 break;
 8367 tgl@sss.pgh.pa.us        1306                 :UBC           0 :             default:
 8181                          1307         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                               1308                 :                :                      (int) j->jointype);
                               1309                 :                :                 break;
                               1310                 :                :         }
                               1311                 :                :     }
                               1312                 :                :     else
                               1313         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               1314                 :                :              (int) nodeTag(jtnode));
 8367 tgl@sss.pgh.pa.us        1315                 :CBC      671151 :     return jtnode;
                               1316                 :                : }
                               1317                 :                : 
                               1318                 :                : /*
                               1319                 :                :  * pull_up_simple_subquery
                               1320                 :                :  *      Attempt to pull up a single simple subquery.
                               1321                 :                :  *
                               1322                 :                :  * jtnode is a RangeTblRef that has been tentatively identified as a simple
                               1323                 :                :  * subquery by pull_up_subqueries.  We return the replacement jointree node,
                               1324                 :                :  * or jtnode itself if we determine that the subquery can't be pulled up
                               1325                 :                :  * after all.
                               1326                 :                :  *
                               1327                 :                :  * rte is the RangeTblEntry referenced by jtnode.  Remaining parameters are
                               1328                 :                :  * as for pull_up_subqueries_recurse.
                               1329                 :                :  */
                               1330                 :                : static Node *
 7257                          1331                 :          18944 : pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
                               1332                 :                :                         JoinExpr *lowest_outer_join,
                               1333                 :                :                         AppendRelInfo *containing_appendrel)
                               1334                 :                : {
                               1335                 :          18944 :     Query      *parse = root->parse;
                               1336                 :          18944 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               1337                 :                :     Query      *subquery;
                               1338                 :                :     PlannerInfo *subroot;
                               1339                 :                :     int         rtoffset;
                               1340                 :                :     pullup_replace_vars_context rvcontext;
                               1341                 :                :     ListCell   *lc;
                               1342                 :                : 
                               1343                 :                :     /*
                               1344                 :                :      * Make a modifiable copy of the subquery to hack on, so that the RTE will
                               1345                 :                :      * be left unchanged in case we decide below that we can't pull it up
                               1346                 :                :      * after all.
                               1347                 :                :      */
                               1348                 :          18944 :     subquery = copyObject(rte->subquery);
                               1349                 :                : 
                               1350                 :                :     /*
                               1351                 :                :      * Create a PlannerInfo data structure for this subquery.
                               1352                 :                :      *
                               1353                 :                :      * NOTE: the next few steps should match the first processing in
                               1354                 :                :      * subquery_planner().  Can we refactor to avoid code duplication, or
                               1355                 :                :      * would that just make things uglier?
                               1356                 :                :      */
                               1357                 :          18944 :     subroot = makeNode(PlannerInfo);
                               1358                 :          18944 :     subroot->parse = subquery;
 6876                          1359                 :          18944 :     subroot->glob = root->glob;
                               1360                 :          18944 :     subroot->query_level = root->query_level;
   71 rhaas@postgresql.org     1361                 :GNC       18944 :     subroot->plan_name = root->plan_name;
 6283 tgl@sss.pgh.pa.us        1362                 :CBC       18944 :     subroot->parent_root = root->parent_root;
 4851                          1363                 :          18944 :     subroot->plan_params = NIL;
 3781                          1364                 :          18944 :     subroot->outer_params = NULL;
 6906                          1365                 :          18944 :     subroot->planner_cxt = CurrentMemoryContext;
 6876                          1366                 :          18944 :     subroot->init_plans = NIL;
 6283                          1367                 :          18944 :     subroot->cte_plan_ids = NIL;
 4200                          1368                 :          18944 :     subroot->multiexpr_params = NIL;
 1052                          1369                 :          18944 :     subroot->join_domains = NIL;
 6483                          1370                 :          18944 :     subroot->eq_classes = NIL;
 2341 drowley@postgresql.o     1371                 :          18944 :     subroot->ec_merging_done = false;
 1052 tgl@sss.pgh.pa.us        1372                 :          18944 :     subroot->last_rinfo_serial = 0;
 1722                          1373                 :          18944 :     subroot->all_result_relids = NULL;
                               1374                 :          18944 :     subroot->leaf_result_relids = NULL;
 7257                          1375                 :          18944 :     subroot->append_rel_list = NIL;
 1722                          1376                 :          18944 :     subroot->row_identity_vars = NIL;
 5896                          1377                 :          18944 :     subroot->rowMarks = NIL;
 3572                          1378                 :          18944 :     memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
 3565                          1379                 :          18944 :     memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
 1064                          1380                 :          18944 :     subroot->processed_groupClause = NIL;
                               1381                 :          18944 :     subroot->processed_distinctClause = NIL;
 3572                          1382                 :          18944 :     subroot->processed_tlist = NIL;
 1722                          1383                 :          18944 :     subroot->update_colnos = NIL;
 3572                          1384                 :          18944 :     subroot->grouping_map = NULL;
                               1385                 :          18944 :     subroot->minmax_aggs = NIL;
 3255                          1386                 :          18944 :     subroot->qual_security_level = 0;
 1218                          1387                 :          18944 :     subroot->placeholdersFrozen = false;
 6283                          1388                 :          18944 :     subroot->hasRecursion = false;
  119 rhaas@postgresql.org     1389                 :GNC       18944 :     subroot->assumeReplanning = false;
 6283 tgl@sss.pgh.pa.us        1390                 :CBC       18944 :     subroot->wt_param_id = -1;
 3572                          1391                 :          18944 :     subroot->non_recursive_path = NULL;
                               1392                 :                :     /* We don't currently need a top JoinDomain for the subroot */
                               1393                 :                : 
                               1394                 :                :     /* No CTEs to worry about */
 6283                          1395         [ -  + ]:          18944 :     Assert(subquery->cteList == NIL);
                               1396                 :                : 
                               1397                 :                :     /*
                               1398                 :                :      * Scan the rangetable for relation RTEs and retrieve the necessary
                               1399                 :                :      * catalog information for each relation.  Using this information, clear
                               1400                 :                :      * the inh flag for any relation that has no children, collect not-null
                               1401                 :                :      * attribute numbers for any relation that has column not-null
                               1402                 :                :      * constraints, and expand virtual generated columns for any relation that
                               1403                 :                :      * contains them.
                               1404                 :                :      */
  148 rguo@postgresql.org      1405                 :GNC       18944 :     subquery = subroot->parse = preprocess_relation_rtes(subroot);
                               1406                 :                : 
                               1407                 :                :     /*
                               1408                 :                :      * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
                               1409                 :                :      * that we don't need so many special cases to deal with that situation.
                               1410                 :                :      */
 2515 tgl@sss.pgh.pa.us        1411                 :CBC       18944 :     replace_empty_jointree(subquery);
                               1412                 :                : 
                               1413                 :                :     /*
                               1414                 :                :      * Pull up any SubLinks within the subquery's quals, so that we don't
                               1415                 :                :      * leave unoptimized SubLinks behind.
                               1416                 :                :      */
 7257                          1417         [ +  + ]:          18944 :     if (subquery->hasSubLinks)
 6331                          1418                 :           1214 :         pull_up_sublinks(subroot);
                               1419                 :                : 
                               1420                 :                :     /*
                               1421                 :                :      * Similarly, preprocess its function RTEs to inline any set-returning
                               1422                 :                :      * functions in its rangetable.
                               1423                 :                :      */
 2330                          1424                 :          18944 :     preprocess_function_rtes(subroot);
                               1425                 :                : 
                               1426                 :                :     /*
                               1427                 :                :      * Recursively pull up the subquery's subqueries, so that
                               1428                 :                :      * pull_up_subqueries' processing is complete for its jointree and
                               1429                 :                :      * rangetable.
                               1430                 :                :      *
                               1431                 :                :      * Note: it's okay that the subquery's recursion starts with NULL for
                               1432                 :                :      * containing-join info, even if we are within an outer join in the upper
                               1433                 :                :      * query; the lower query starts with a clean slate for outer-join
                               1434                 :                :      * semantics.  Likewise, we needn't pass down appendrel state.
                               1435                 :                :      */
 3934                          1436                 :          18944 :     pull_up_subqueries(subroot);
                               1437                 :                : 
                               1438                 :                :     /*
                               1439                 :                :      * Now we must recheck whether the subquery is still simple enough to pull
                               1440                 :                :      * up.  If not, abandon processing it.
                               1441                 :                :      *
                               1442                 :                :      * We don't really need to recheck all the conditions involved, but it's
                               1443                 :                :      * easier just to keep this "if" looking the same as the one in
                               1444                 :                :      * pull_up_subqueries_recurse.
                               1445                 :                :      */
 1791                          1446   [ +  +  +  + ]:          22134 :     if (is_simple_subquery(root, subquery, rte, lowest_outer_join) &&
 6077                          1447         [ +  + ]:           3304 :         (containing_appendrel == NULL || is_safe_append_member(subquery)))
                               1448                 :                :     {
                               1449                 :                :         /* good to go */
                               1450                 :                :     }
                               1451                 :                :     else
                               1452                 :                :     {
                               1453                 :                :         /*
                               1454                 :                :          * Give up, return unmodified RangeTblRef.
                               1455                 :                :          *
                               1456                 :                :          * Note: The work we just did will be redone when the subquery gets
                               1457                 :                :          * planned on its own.  Perhaps we could avoid that by storing the
                               1458                 :                :          * modified subquery back into the rangetable, but I'm not gonna risk
                               1459                 :                :          * it now.
                               1460                 :                :          */
 7257                          1461                 :            120 :         return jtnode;
                               1462                 :                :     }
                               1463                 :                : 
                               1464                 :                :     /*
                               1465                 :                :      * We must flatten any join alias Vars in the subquery's targetlist,
                               1466                 :                :      * because pulling up the subquery's subqueries might have changed their
                               1467                 :                :      * expansions into arbitrary expressions, which could affect
                               1468                 :                :      * pullup_replace_vars' decisions about whether PlaceHolderVar wrappers
                               1469                 :                :      * are needed for tlist entries.  (Likely it'd be better to do
                               1470                 :                :      * flatten_join_alias_vars on the whole query tree at some earlier stage,
                               1471                 :                :      * maybe even in the rewriter; but for now let's just fix this case here.)
                               1472                 :                :      */
 4408                          1473                 :          18824 :     subquery->targetList = (List *)
 1052                          1474                 :          18824 :         flatten_join_alias_vars(subroot, subroot->parse,
                               1475                 :          18824 :                                 (Node *) subquery->targetList);
                               1476                 :                : 
                               1477                 :                :     /*
                               1478                 :                :      * Adjust level-0 varnos in subquery so that we can append its rangetable
                               1479                 :                :      * to upper query's.  We have to fix the subquery's append_rel_list as
                               1480                 :                :      * well.
                               1481                 :                :      */
 7257                          1482                 :          18824 :     rtoffset = list_length(parse->rtable);
                               1483                 :          18824 :     OffsetVarNodes((Node *) subquery, rtoffset, 0);
                               1484                 :          18824 :     OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
                               1485                 :                : 
                               1486                 :                :     /*
                               1487                 :                :      * Upper-level vars in subquery are now one level closer to their parent
                               1488                 :                :      * than before.
                               1489                 :                :      */
                               1490                 :          18824 :     IncrementVarSublevelsUp((Node *) subquery, -1, 1);
                               1491                 :          18824 :     IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
                               1492                 :                : 
                               1493                 :                :     /*
                               1494                 :                :      * The subquery's targetlist items are now in the appropriate form to
                               1495                 :                :      * insert into the top query, except that we may need to wrap them in
                               1496                 :                :      * PlaceHolderVars.  Set up required context data for pullup_replace_vars.
                               1497                 :                :      * (Note that we should include the subquery's inner joins in relids,
                               1498                 :                :      * since it may include join alias vars referencing them.)
                               1499                 :                :      */
 5950                          1500                 :          18824 :     rvcontext.root = root;
                               1501                 :          18824 :     rvcontext.targetlist = subquery->targetList;
                               1502                 :          18824 :     rvcontext.target_rte = rte;
  295 rguo@postgresql.org      1503                 :          18824 :     rvcontext.result_relation = 0;
 4505 tgl@sss.pgh.pa.us        1504         [ +  + ]:          18824 :     if (rte->lateral)
                               1505                 :                :     {
                               1506                 :            583 :         rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
                               1507                 :                :                                                   true, true);
  382                          1508                 :            583 :         rvcontext.nullinfo = get_nullingrels(parse);
                               1509                 :                :     }
                               1510                 :                :     else                        /* won't need these values */
                               1511                 :                :     {
 4505                          1512                 :          18241 :         rvcontext.relids = NULL;
  382                          1513                 :          18241 :         rvcontext.nullinfo = NULL;
                               1514                 :                :     }
 5950                          1515                 :          18824 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
                               1516                 :          18824 :     rvcontext.varno = varno;
                               1517                 :                :     /* this flag will be set below, if needed */
  279 rguo@postgresql.org      1518                 :          18824 :     rvcontext.wrap_option = REPLACE_WRAP_NONE;
                               1519                 :                :     /* initialize cache array with indexes 0 .. length(tlist) */
 5950 tgl@sss.pgh.pa.us        1520                 :          18824 :     rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
                               1521                 :                :                                  sizeof(Node *));
                               1522                 :                : 
                               1523                 :                :     /*
                               1524                 :                :      * If the parent query uses grouping sets, we need a PlaceHolderVar for
                               1525                 :                :      * each expression of the subquery's targetlist items.  This ensures that
                               1526                 :                :      * expressions retain their separate identity so that they will match
                               1527                 :                :      * grouping set columns when appropriate.  (It'd be sufficient to wrap
                               1528                 :                :      * values used in grouping set columns, and do so only in non-aggregated
                               1529                 :                :      * portions of the tlist and havingQual, but that would require a lot of
                               1530                 :                :      * infrastructure that pullup_replace_vars hasn't currently got.)
                               1531                 :                :      */
 2896                          1532         [ +  + ]:          18824 :     if (parse->groupingSets)
  279 rguo@postgresql.org      1533                 :            166 :         rvcontext.wrap_option = REPLACE_WRAP_ALL;
                               1534                 :                : 
                               1535                 :                :     /*
                               1536                 :                :      * Replace all of the top query's references to the subquery's outputs
                               1537                 :                :      * with copies of the adjusted subtlist items, being careful not to
                               1538                 :                :      * replace any of the jointree structure.
                               1539                 :                :      */
 2330 tgl@sss.pgh.pa.us        1540                 :          18824 :     perform_pullup_replace_vars(root, &rvcontext,
                               1541                 :                :                                 containing_appendrel);
                               1542                 :                : 
                               1543                 :                :     /*
                               1544                 :                :      * If the subquery had a LATERAL marker, propagate that to any of its
                               1545                 :                :      * child RTEs that could possibly now contain lateral cross-references.
                               1546                 :                :      * The children might or might not contain any actual lateral
                               1547                 :                :      * cross-references, but we have to mark the pulled-up child RTEs so that
                               1548                 :                :      * later planner stages will check for such.
                               1549                 :                :      */
 4875                          1550         [ +  + ]:          18821 :     if (rte->lateral)
                               1551                 :                :     {
                               1552   [ +  -  +  +  :           1364 :         foreach(lc, subquery->rtable)
                                              +  + ]
                               1553                 :                :         {
                               1554                 :            781 :             RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
                               1555                 :                : 
                               1556   [ +  +  +  - ]:            781 :             switch (child_rte->rtekind)
                               1557                 :                :             {
 3798                          1558                 :            348 :                 case RTE_RELATION:
                               1559         [ +  + ]:            348 :                     if (child_rte->tablesample)
                               1560                 :             18 :                         child_rte->lateral = true;
                               1561                 :            348 :                     break;
 4875                          1562                 :            140 :                 case RTE_SUBQUERY:
                               1563                 :                :                 case RTE_FUNCTION:
                               1564                 :                :                 case RTE_VALUES:
                               1565                 :                :                 case RTE_TABLEFUNC:
                               1566                 :            140 :                     child_rte->lateral = true;
                               1567                 :            140 :                     break;
                               1568                 :            293 :                 case RTE_JOIN:
                               1569                 :                :                 case RTE_CTE:
                               1570                 :                :                 case RTE_NAMEDTUPLESTORE:
                               1571                 :                :                 case RTE_RESULT:
                               1572                 :                :                 case RTE_GROUP:
                               1573                 :                :                     /* these can't contain any lateral references */
                               1574                 :            293 :                     break;
                               1575                 :                :             }
                               1576                 :                :         }
                               1577                 :                :     }
                               1578                 :                : 
                               1579                 :                :     /*
                               1580                 :                :      * Now append the adjusted rtable entries and their perminfos to upper
                               1581                 :                :      * query. (We hold off until after fixing the upper rtable entries; no
                               1582                 :                :      * point in running that code on the subquery ones too.)
                               1583                 :                :      */
 1107 alvherre@alvh.no-ip.     1584                 :          18821 :     CombineRangeTables(&parse->rtable, &parse->rteperminfos,
                               1585                 :                :                        subquery->rtable, subquery->rteperminfos);
                               1586                 :                : 
                               1587                 :                :     /*
                               1588                 :                :      * Pull up any FOR UPDATE/SHARE markers, too.  (OffsetVarNodes already
                               1589                 :                :      * adjusted the marker rtindexes, so just concat the lists.)
                               1590                 :                :      */
 7257 tgl@sss.pgh.pa.us        1591                 :          18821 :     parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
                               1592                 :                : 
                               1593                 :                :     /*
                               1594                 :                :      * We also have to fix the relid sets of any PlaceHolderVar nodes in the
                               1595                 :                :      * parent query.  (This could perhaps be done by pullup_replace_vars(),
                               1596                 :                :      * but it seems cleaner to use two passes.)  Note in particular that any
                               1597                 :                :      * PlaceHolderVar nodes just created by pullup_replace_vars() will be
                               1598                 :                :      * adjusted, so having created them with the subquery's varno is correct.
                               1599                 :                :      *
                               1600                 :                :      * Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
                               1601                 :                :      * already checked that this won't require introducing multiple subrelids
                               1602                 :                :      * into the single-slot AppendRelInfo structs.
                               1603                 :                :      */
 1091                          1604   [ +  +  +  + ]:          18821 :     if (root->glob->lastPHId != 0 || root->append_rel_list)
                               1605                 :                :     {
                               1606                 :                :         Relids      subrelids;
                               1607                 :                : 
 1052                          1608                 :           4160 :         subrelids = get_relids_in_jointree((Node *) subquery->jointree,
                               1609                 :                :                                            true, false);
 1091                          1610         [ +  + ]:           4160 :         if (root->glob->lastPHId != 0)
                               1611                 :            997 :             substitute_phv_relids((Node *) parse, varno, subrelids);
                               1612                 :           4160 :         fix_append_rel_relids(root, varno, subrelids);
                               1613                 :                :     }
                               1614                 :                : 
                               1615                 :                :     /*
                               1616                 :                :      * And now add subquery's AppendRelInfos to our list.
                               1617                 :                :      */
 7257                          1618                 :          37642 :     root->append_rel_list = list_concat(root->append_rel_list,
                               1619                 :          18821 :                                         subroot->append_rel_list);
                               1620                 :                : 
                               1621                 :                :     /*
                               1622                 :                :      * We don't have to do the equivalent bookkeeping for outer-join info,
                               1623                 :                :      * because that hasn't been set up yet.  placeholder_list likewise.
                               1624                 :                :      */
 6334                          1625         [ -  + ]:          18821 :     Assert(root->join_info_list == NIL);
                               1626         [ -  + ]:          18821 :     Assert(subroot->join_info_list == NIL);
 6265                          1627         [ -  + ]:          18821 :     Assert(root->placeholder_list == NIL);
                               1628         [ -  + ]:          18821 :     Assert(subroot->placeholder_list == NIL);
                               1629                 :                : 
                               1630                 :                :     /*
                               1631                 :                :      * We no longer need the RTE's copy of the subquery's query tree.  Getting
                               1632                 :                :      * rid of it saves nothing in particular so far as this level of query is
                               1633                 :                :      * concerned; but if this query level is in turn pulled up into a parent,
                               1634                 :                :      * we'd waste cycles copying the now-unused query tree.
                               1635                 :                :      */
 1625                          1636                 :          18821 :     rte->subquery = NULL;
                               1637                 :                : 
                               1638                 :                :     /*
                               1639                 :                :      * Miscellaneous housekeeping.
                               1640                 :                :      *
                               1641                 :                :      * Although replace_rte_variables() faithfully updated parse->hasSubLinks
                               1642                 :                :      * if it copied any SubLinks out of the subquery's targetlist, we still
                               1643                 :                :      * could have SubLinks added to the query in the expressions of FUNCTION
                               1644                 :                :      * and VALUES RTEs copied up from the subquery.  So it's necessary to copy
                               1645                 :                :      * subquery->hasSubLinks anyway.  Perhaps this can be improved someday.
                               1646                 :                :      */
 7257                          1647                 :          18821 :     parse->hasSubLinks |= subquery->hasSubLinks;
                               1648                 :                : 
                               1649                 :                :     /* If subquery had any RLS conditions, now main query does too */
 3324                          1650                 :          18821 :     parse->hasRowSecurity |= subquery->hasRowSecurity;
                               1651                 :                : 
                               1652                 :                :     /*
                               1653                 :                :      * subquery won't be pulled up if it hasAggs, hasWindowFuncs, or
                               1654                 :                :      * hasTargetSRFs, so no work needed on those flags
                               1655                 :                :      */
                               1656                 :                : 
                               1657                 :                :     /*
                               1658                 :                :      * Return the adjusted subquery jointree to replace the RangeTblRef entry
                               1659                 :                :      * in parent's jointree; or, if the FromExpr is degenerate, just return
                               1660                 :                :      * its single member.
                               1661                 :                :      */
 2515                          1662         [ -  + ]:          18821 :     Assert(IsA(subquery->jointree, FromExpr));
                               1663         [ -  + ]:          18821 :     Assert(subquery->jointree->fromlist != NIL);
                               1664   [ +  +  +  + ]:          34706 :     if (subquery->jointree->quals == NULL &&
                               1665                 :          15885 :         list_length(subquery->jointree->fromlist) == 1)
                               1666                 :          15726 :         return (Node *) linitial(subquery->jointree->fromlist);
                               1667                 :                : 
 7257                          1668                 :           3095 :     return (Node *) subquery->jointree;
                               1669                 :                : }
                               1670                 :                : 
                               1671                 :                : /*
                               1672                 :                :  * pull_up_simple_union_all
                               1673                 :                :  *      Pull up a single simple UNION ALL subquery.
                               1674                 :                :  *
                               1675                 :                :  * jtnode is a RangeTblRef that has been identified as a simple UNION ALL
                               1676                 :                :  * subquery by pull_up_subqueries.  We pull up the leaf subqueries and
                               1677                 :                :  * build an "append relation" for the union set.  The result value is just
                               1678                 :                :  * jtnode, since we don't actually need to change the query jointree.
                               1679                 :                :  */
                               1680                 :                : static Node *
                               1681                 :           2464 : pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
                               1682                 :                : {
                               1683                 :           2464 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               1684                 :           2464 :     Query      *subquery = rte->subquery;
 4876                          1685                 :           2464 :     int         rtoffset = list_length(root->parse->rtable);
                               1686                 :                :     List       *rtable;
                               1687                 :                : 
                               1688                 :                :     /*
                               1689                 :                :      * Make a modifiable copy of the subquery's rtable, so we can adjust
                               1690                 :                :      * upper-level Vars in it.  There are no such Vars in the setOperations
                               1691                 :                :      * tree proper, so fixing the rtable should be sufficient.
                               1692                 :                :      */
                               1693                 :           2464 :     rtable = copyObject(subquery->rtable);
                               1694                 :                : 
                               1695                 :                :     /*
                               1696                 :                :      * Upper-level vars in subquery are now one level closer to their parent
                               1697                 :                :      * than before.  We don't have to worry about offsetting varnos, though,
                               1698                 :                :      * because the UNION leaf queries can't cross-reference each other.
                               1699                 :                :      */
 6334 heikki.linnakangas@i     1700                 :           2464 :     IncrementVarSublevelsUp_rtable(rtable, -1, 1);
                               1701                 :                : 
                               1702                 :                :     /*
                               1703                 :                :      * If the UNION ALL subquery had a LATERAL marker, propagate that to all
                               1704                 :                :      * its children.  The individual children might or might not contain any
                               1705                 :                :      * actual lateral cross-references, but we have to mark the pulled-up
                               1706                 :                :      * child RTEs so that later planner stages will check for such.
                               1707                 :                :      */
 4876 tgl@sss.pgh.pa.us        1708         [ +  + ]:           2464 :     if (rte->lateral)
                               1709                 :                :     {
                               1710                 :                :         ListCell   *rt;
                               1711                 :                : 
                               1712   [ +  -  +  +  :             99 :         foreach(rt, rtable)
                                              +  + ]
                               1713                 :                :         {
                               1714                 :             66 :             RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt);
                               1715                 :                : 
                               1716         [ -  + ]:             66 :             Assert(child_rte->rtekind == RTE_SUBQUERY);
                               1717                 :             66 :             child_rte->lateral = true;
                               1718                 :                :         }
                               1719                 :                :     }
                               1720                 :                : 
                               1721                 :                :     /*
                               1722                 :                :      * Append child RTEs (and their perminfos) to parent rtable.
                               1723                 :                :      */
 1107 alvherre@alvh.no-ip.     1724                 :           2464 :     CombineRangeTables(&root->parse->rtable, &root->parse->rteperminfos,
                               1725                 :                :                        rtable, subquery->rteperminfos);
                               1726                 :                : 
                               1727                 :                :     /*
                               1728                 :                :      * Recursively scan the subquery's setOperations tree and add
                               1729                 :                :      * AppendRelInfo nodes for leaf subqueries to the parent's
                               1730                 :                :      * append_rel_list.  Also apply pull_up_subqueries to the leaf subqueries.
                               1731                 :                :      */
 7257 tgl@sss.pgh.pa.us        1732         [ -  + ]:           2464 :     Assert(subquery->setOperations);
 6334 heikki.linnakangas@i     1733                 :           2464 :     pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
                               1734                 :                :                                rtoffset);
                               1735                 :                : 
                               1736                 :                :     /*
                               1737                 :                :      * Mark the parent as an append relation.
                               1738                 :                :      */
 7257 tgl@sss.pgh.pa.us        1739                 :           2464 :     rte->inh = true;
                               1740                 :                : 
                               1741                 :           2464 :     return jtnode;
                               1742                 :                : }
                               1743                 :                : 
                               1744                 :                : /*
                               1745                 :                :  * pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
                               1746                 :                :  *
                               1747                 :                :  * Build an AppendRelInfo for each leaf query in the setop tree, and then
                               1748                 :                :  * apply pull_up_subqueries to the leaf query.
                               1749                 :                :  *
                               1750                 :                :  * Note that setOpQuery is the Query containing the setOp node, whose tlist
                               1751                 :                :  * contains references to all the setop output columns.  When called from
                               1752                 :                :  * pull_up_simple_union_all, this is *not* the same as root->parse, which is
                               1753                 :                :  * the parent Query we are pulling up into.
                               1754                 :                :  *
                               1755                 :                :  * parentRTindex is the appendrel parent's index in root->parse->rtable.
                               1756                 :                :  *
                               1757                 :                :  * The child RTEs have already been copied to the parent.  childRToffset
                               1758                 :                :  * tells us where in the parent's range table they were copied.  When called
                               1759                 :                :  * from flatten_simple_union_all, childRToffset is 0 since the child RTEs
                               1760                 :                :  * were already in root->parse->rtable and no RT index adjustment is needed.
                               1761                 :                :  */
                               1762                 :                : static void
                               1763                 :          13711 : pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
                               1764                 :                :                            Query *setOpQuery, int childRToffset)
                               1765                 :                : {
                               1766         [ +  + ]:          13711 :     if (IsA(setOp, RangeTblRef))
                               1767                 :                :     {
                               1768                 :           8286 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
                               1769                 :                :         int         childRTindex;
                               1770                 :                :         AppendRelInfo *appinfo;
                               1771                 :                : 
                               1772                 :                :         /*
                               1773                 :                :          * Calculate the index in the parent's range table
                               1774                 :                :          */
 6334 heikki.linnakangas@i     1775                 :           8286 :         childRTindex = childRToffset + rtr->rtindex;
                               1776                 :                : 
                               1777                 :                :         /*
                               1778                 :                :          * Build a suitable AppendRelInfo, and attach to parent's list.
                               1779                 :                :          */
 7257 tgl@sss.pgh.pa.us        1780                 :           8286 :         appinfo = makeNode(AppendRelInfo);
                               1781                 :           8286 :         appinfo->parent_relid = parentRTindex;
                               1782                 :           8286 :         appinfo->child_relid = childRTindex;
                               1783                 :           8286 :         appinfo->parent_reltype = InvalidOid;
                               1784                 :           8286 :         appinfo->child_reltype = InvalidOid;
 2207                          1785                 :           8286 :         make_setop_translation_list(setOpQuery, childRTindex, appinfo);
 7257                          1786                 :           8286 :         appinfo->parent_reloid = InvalidOid;
                               1787                 :           8286 :         root->append_rel_list = lappend(root->append_rel_list, appinfo);
                               1788                 :                : 
                               1789                 :                :         /*
                               1790                 :                :          * Recursively apply pull_up_subqueries to the new child RTE.  (We
                               1791                 :                :          * must build the AppendRelInfo first, because this will modify it;
                               1792                 :                :          * indeed, that's the only part of the upper query where Vars
                               1793                 :                :          * referencing childRTindex can exist at this point.)
                               1794                 :                :          *
                               1795                 :                :          * Note that we can pass NULL for containing-join info even if we're
                               1796                 :                :          * actually under an outer join, because the child's expressions
                               1797                 :                :          * aren't going to propagate up to the join.  Also, we ignore the
                               1798                 :                :          * possibility that pull_up_subqueries_recurse() returns a different
                               1799                 :                :          * jointree node than what we pass it; if it does, the important thing
                               1800                 :                :          * is that it replaced the child relid in the AppendRelInfo node.
                               1801                 :                :          */
                               1802                 :           8286 :         rtr = makeNode(RangeTblRef);
                               1803                 :           8286 :         rtr->rtindex = childRTindex;
 4875                          1804                 :           8286 :         (void) pull_up_subqueries_recurse(root, (Node *) rtr,
                               1805                 :                :                                           NULL, appinfo);
                               1806                 :                :     }
 7257                          1807         [ +  - ]:           5425 :     else if (IsA(setOp, SetOperationStmt))
                               1808                 :                :     {
                               1809                 :           5425 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
                               1810                 :                : 
                               1811                 :                :         /* Recurse to reach leaf queries */
 6334 heikki.linnakangas@i     1812                 :           5425 :         pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
                               1813                 :                :                                    childRToffset);
                               1814                 :           5425 :         pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
                               1815                 :                :                                    childRToffset);
                               1816                 :                :     }
                               1817                 :                :     else
                               1818                 :                :     {
 7257 tgl@sss.pgh.pa.us        1819         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               1820                 :                :              (int) nodeTag(setOp));
                               1821                 :                :     }
 7257 tgl@sss.pgh.pa.us        1822                 :CBC       13711 : }
                               1823                 :                : 
                               1824                 :                : /*
                               1825                 :                :  * make_setop_translation_list
                               1826                 :                :  *    Build the list of translations from parent Vars to child Vars for
                               1827                 :                :  *    a UNION ALL member.  (At this point it's just a simple list of
                               1828                 :                :  *    referencing Vars, but if we succeed in pulling up the member
                               1829                 :                :  *    subquery, the Vars will get replaced by pulled-up expressions.)
                               1830                 :                :  *    Also create the rather trivial reverse-translation array.
                               1831                 :                :  */
                               1832                 :                : static void
 1554                          1833                 :           8286 : make_setop_translation_list(Query *query, int newvarno,
                               1834                 :                :                             AppendRelInfo *appinfo)
                               1835                 :                : {
 7257                          1836                 :           8286 :     List       *vars = NIL;
                               1837                 :                :     AttrNumber *pcolnos;
                               1838                 :                :     ListCell   *l;
                               1839                 :                : 
                               1840                 :                :     /* Initialize reverse-translation array with all entries zero */
                               1841                 :                :     /* (entries for resjunk columns will stay that way) */
 2207                          1842                 :           8286 :     appinfo->num_child_cols = list_length(query->targetList);
                               1843                 :           8286 :     appinfo->parent_colnos = pcolnos =
                               1844                 :           8286 :         (AttrNumber *) palloc0(appinfo->num_child_cols * sizeof(AttrNumber));
                               1845                 :                : 
 7257                          1846   [ +  +  +  +  :          37801 :     foreach(l, query->targetList)
                                              +  + ]
                               1847                 :                :     {
                               1848                 :          29515 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               1849                 :                : 
                               1850         [ -  + ]:          29515 :         if (tle->resjunk)
 7257 tgl@sss.pgh.pa.us        1851                 :UBC           0 :             continue;
                               1852                 :                : 
 5591 peter_e@gmx.net          1853                 :CBC       29515 :         vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
 2207 tgl@sss.pgh.pa.us        1854                 :          29515 :         pcolnos[tle->resno - 1] = tle->resno;
                               1855                 :                :     }
                               1856                 :                : 
                               1857                 :           8286 :     appinfo->translated_vars = vars;
 7257                          1858                 :           8286 : }
                               1859                 :                : 
                               1860                 :                : /*
                               1861                 :                :  * is_simple_subquery
                               1862                 :                :  *    Check a subquery in the range table to see if it's simple enough
                               1863                 :                :  *    to pull up into the parent query.
                               1864                 :                :  *
                               1865                 :                :  * rte is the RTE_SUBQUERY RangeTblEntry that contained the subquery.
                               1866                 :                :  * (Note subquery is not necessarily equal to rte->subquery; it could be a
                               1867                 :                :  * processed copy of that.)
                               1868                 :                :  * lowest_outer_join is the lowest outer join above the subquery, or NULL.
                               1869                 :                :  */
                               1870                 :                : static bool
 1791                          1871                 :          52068 : is_simple_subquery(PlannerInfo *root, Query *subquery, RangeTblEntry *rte,
                               1872                 :                :                    JoinExpr *lowest_outer_join)
                               1873                 :                : {
                               1874                 :                :     /*
                               1875                 :                :      * Let's just make sure it's a valid subselect ...
                               1876                 :                :      */
 8367                          1877         [ +  - ]:          52068 :     if (!IsA(subquery, Query) ||
 3259                          1878         [ -  + ]:          52068 :         subquery->commandType != CMD_SELECT)
 8181 tgl@sss.pgh.pa.us        1879         [ #  # ]:UBC           0 :         elog(ERROR, "subquery is bogus");
                               1880                 :                : 
                               1881                 :                :     /*
                               1882                 :                :      * Can't currently pull up a query with setops (unless it's simple UNION
                               1883                 :                :      * ALL, which is handled by a different code path). Maybe after querytree
                               1884                 :                :      * redesign...
                               1885                 :                :      */
 8367 tgl@sss.pgh.pa.us        1886         [ +  + ]:CBC       52068 :     if (subquery->setOperations)
                               1887                 :           2908 :         return false;
                               1888                 :                : 
                               1889                 :                :     /*
                               1890                 :                :      * Can't pull up a subquery involving grouping, aggregation, SRFs,
                               1891                 :                :      * sorting, limiting, or WITH.  (XXX WITH could possibly be allowed later)
                               1892                 :                :      *
                               1893                 :                :      * We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
                               1894                 :                :      * clauses, because pullup would cause the locking to occur semantically
                               1895                 :                :      * higher than it should.  Implicit FOR UPDATE/SHARE is okay because in
                               1896                 :                :      * that case the locking was originally declared in the upper query
                               1897                 :                :      * anyway.
                               1898                 :                :      */
                               1899         [ +  + ]:          49160 :     if (subquery->hasAggs ||
 6198                          1900         [ +  + ]:          48255 :         subquery->hasWindowFuncs ||
 3382                          1901         [ +  + ]:          48062 :         subquery->hasTargetSRFs ||
 8367                          1902         [ +  + ]:          45916 :         subquery->groupClause ||
 3868 andres@anarazel.de       1903         [ +  + ]:          45873 :         subquery->groupingSets ||
 8367 tgl@sss.pgh.pa.us        1904         [ +  - ]:          45855 :         subquery->havingQual ||
                               1905         [ +  + ]:          45855 :         subquery->sortClause ||
                               1906         [ +  + ]:          45416 :         subquery->distinctClause ||
                               1907         [ +  + ]:          44970 :         subquery->limitOffset ||
 6283                          1908         [ +  + ]:          44745 :         subquery->limitCount ||
 5894                          1909         [ +  + ]:          44590 :         subquery->hasForUpdate ||
 6283                          1910         [ +  + ]:          41521 :         subquery->cteList)
 8367                          1911                 :           7723 :         return false;
                               1912                 :                : 
                               1913                 :                :     /*
                               1914                 :                :      * Don't pull up if the RTE represents a security-barrier view; we
                               1915                 :                :      * couldn't prevent information leakage once the RTE's Vars are scattered
                               1916                 :                :      * about in the upper query.
                               1917                 :                :      */
 4875                          1918         [ +  + ]:          41437 :     if (rte->security_barrier)
 4880                          1919                 :            350 :         return false;
                               1920                 :                : 
                               1921                 :                :     /*
                               1922                 :                :      * If the subquery is LATERAL, check for pullup restrictions from that.
                               1923                 :                :      */
 4503                          1924         [ +  + ]:          41087 :     if (rte->lateral)
                               1925                 :                :     {
                               1926                 :                :         bool        restricted;
                               1927                 :                :         Relids      safe_upper_varnos;
                               1928                 :                : 
                               1929                 :                :         /*
                               1930                 :                :          * The subquery's WHERE and JOIN/ON quals mustn't contain any lateral
                               1931                 :                :          * references to rels outside a higher outer join (including the case
                               1932                 :                :          * where the outer join is within the subquery itself).  In such a
                               1933                 :                :          * case, pulling up would result in a situation where we need to
                               1934                 :                :          * postpone quals from below an outer join to above it, which is
                               1935                 :                :          * probably completely wrong and in any case is a complication that
                               1936                 :                :          * doesn't seem worth addressing at the moment.
                               1937                 :                :          */
                               1938         [ +  + ]:           1214 :         if (lowest_outer_join != NULL)
                               1939                 :                :         {
                               1940                 :            690 :             restricted = true;
                               1941                 :            690 :             safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join,
                               1942                 :                :                                                        true, true);
                               1943                 :                :         }
                               1944                 :                :         else
                               1945                 :                :         {
                               1946                 :            524 :             restricted = false;
                               1947                 :            524 :             safe_upper_varnos = NULL;   /* doesn't matter */
                               1948                 :                :         }
                               1949                 :                : 
 1791                          1950         [ +  + ]:           1214 :         if (jointree_contains_lateral_outer_refs(root,
                               1951                 :           1214 :                                                  (Node *) subquery->jointree,
                               1952                 :                :                                                  restricted, safe_upper_varnos))
 4875                          1953                 :             12 :             return false;
                               1954                 :                : 
                               1955                 :                :         /*
                               1956                 :                :          * If there's an outer join above the LATERAL subquery, also disallow
                               1957                 :                :          * pullup if the subquery's targetlist has any references to rels
                               1958                 :                :          * outside the outer join, since these might get pulled into quals
                               1959                 :                :          * above the subquery (but in or below the outer join) and then lead
                               1960                 :                :          * to qual-postponement issues similar to the case checked for above.
                               1961                 :                :          * (We wouldn't need to prevent pullup if no such references appear in
                               1962                 :                :          * outer-query quals, but we don't have enough info here to check
                               1963                 :                :          * that.  Also, maybe this restriction could be removed if we forced
                               1964                 :                :          * such refs to be wrapped in PlaceHolderVars, even when they're below
                               1965                 :                :          * the nearest outer join?  But it's a pretty hokey usage, so not
                               1966                 :                :          * clear this is worth sweating over.)
                               1967                 :                :          *
                               1968                 :                :          * If you change this, see also the comments about lateral references
                               1969                 :                :          * in pullup_replace_vars_callback().
                               1970                 :                :          */
 4503                          1971         [ +  + ]:           1202 :         if (lowest_outer_join != NULL)
                               1972                 :                :         {
 1791                          1973                 :            690 :             Relids      lvarnos = pull_varnos_of_level(root,
                               1974                 :            690 :                                                        (Node *) subquery->targetList,
                               1975                 :                :                                                        1);
                               1976                 :                : 
 4503                          1977         [ +  + ]:            690 :             if (!bms_is_subset(lvarnos, safe_upper_varnos))
                               1978                 :              6 :                 return false;
                               1979                 :                :         }
                               1980                 :                :     }
                               1981                 :                : 
                               1982                 :                :     /*
                               1983                 :                :      * Don't pull up a subquery that has any volatile functions in its
                               1984                 :                :      * targetlist.  Otherwise we might introduce multiple evaluations of these
                               1985                 :                :      * functions, if they get copied to multiple places in the upper query,
                               1986                 :                :      * leading to surprising results.  (Note: the PlaceHolderVar mechanism
                               1987                 :                :      * doesn't quite guarantee single evaluation; else we could pull up anyway
                               1988                 :                :      * and just wrap such items in PlaceHolderVars ...)
                               1989                 :                :      */
 7060                          1990         [ +  + ]:          41069 :     if (contain_volatile_functions((Node *) subquery->targetList))
 8367                          1991                 :            135 :         return false;
                               1992                 :                : 
 3934                          1993                 :          40934 :     return true;
                               1994                 :                : }
                               1995                 :                : 
                               1996                 :                : /*
                               1997                 :                :  * pull_up_simple_values
                               1998                 :                :  *      Pull up a single simple VALUES RTE.
                               1999                 :                :  *
                               2000                 :                :  * jtnode is a RangeTblRef that has been identified as a simple VALUES RTE
                               2001                 :                :  * by pull_up_subqueries.  We always return a RangeTblRef representing a
                               2002                 :                :  * RESULT RTE to replace it (all failure cases should have been detected by
                               2003                 :                :  * is_simple_values()).  Actually, what we return is just jtnode, because
                               2004                 :                :  * we replace the VALUES RTE in the rangetable with the RESULT RTE.
                               2005                 :                :  *
                               2006                 :                :  * rte is the RangeTblEntry referenced by jtnode.  Because of the limited
                               2007                 :                :  * possible usage of VALUES RTEs, we do not need the remaining parameters
                               2008                 :                :  * of pull_up_subqueries_recurse.
                               2009                 :                :  */
                               2010                 :                : static Node *
                               2011                 :           2297 : pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
                               2012                 :                : {
                               2013                 :           2297 :     Query      *parse = root->parse;
                               2014                 :           2297 :     int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               2015                 :                :     List       *values_list;
                               2016                 :                :     List       *tlist;
                               2017                 :                :     AttrNumber  attrno;
                               2018                 :                :     pullup_replace_vars_context rvcontext;
                               2019                 :                :     ListCell   *lc;
                               2020                 :                : 
                               2021         [ -  + ]:           2297 :     Assert(rte->rtekind == RTE_VALUES);
                               2022         [ -  + ]:           2297 :     Assert(list_length(rte->values_lists) == 1);
                               2023                 :                : 
                               2024                 :                :     /*
                               2025                 :                :      * Need a modifiable copy of the VALUES list to hack on, just in case it's
                               2026                 :                :      * multiply referenced.
                               2027                 :                :      */
 3205 peter_e@gmx.net          2028                 :           2297 :     values_list = copyObject(linitial(rte->values_lists));
                               2029                 :                : 
                               2030                 :                :     /*
                               2031                 :                :      * The VALUES RTE can't contain any Vars of level zero, let alone any that
                               2032                 :                :      * are join aliases, so no need to flatten join alias Vars.
                               2033                 :                :      */
 3934 tgl@sss.pgh.pa.us        2034         [ -  + ]:           2297 :     Assert(!contain_vars_of_level((Node *) values_list, 0));
                               2035                 :                : 
                               2036                 :                :     /*
                               2037                 :                :      * Set up required context data for pullup_replace_vars.  In particular,
                               2038                 :                :      * we have to make the VALUES list look like a subquery targetlist.
                               2039                 :                :      */
                               2040                 :           2297 :     tlist = NIL;
                               2041                 :           2297 :     attrno = 1;
                               2042   [ +  +  +  +  :           4964 :     foreach(lc, values_list)
                                              +  + ]
                               2043                 :                :     {
                               2044                 :           2667 :         tlist = lappend(tlist,
                               2045                 :           2667 :                         makeTargetEntry((Expr *) lfirst(lc),
                               2046                 :                :                                         attrno,
                               2047                 :                :                                         NULL,
                               2048                 :                :                                         false));
                               2049                 :           2667 :         attrno++;
                               2050                 :                :     }
                               2051                 :           2297 :     rvcontext.root = root;
                               2052                 :           2297 :     rvcontext.targetlist = tlist;
                               2053                 :           2297 :     rvcontext.target_rte = rte;
  295 rguo@postgresql.org      2054                 :           2297 :     rvcontext.result_relation = 0;
  382 tgl@sss.pgh.pa.us        2055                 :           2297 :     rvcontext.relids = NULL;    /* can't be any lateral references here */
                               2056                 :           2297 :     rvcontext.nullinfo = NULL;
 3934                          2057                 :           2297 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
                               2058                 :           2297 :     rvcontext.varno = varno;
  279 rguo@postgresql.org      2059                 :           2297 :     rvcontext.wrap_option = REPLACE_WRAP_NONE;
                               2060                 :                :     /* initialize cache array with indexes 0 .. length(tlist) */
 3934 tgl@sss.pgh.pa.us        2061                 :           2297 :     rvcontext.rv_cache = palloc0((list_length(tlist) + 1) *
                               2062                 :                :                                  sizeof(Node *));
                               2063                 :                : 
                               2064                 :                :     /*
                               2065                 :                :      * Replace all of the top query's references to the RTE's outputs with
                               2066                 :                :      * copies of the adjusted VALUES expressions, being careful not to replace
                               2067                 :                :      * any of the jointree structure.  We can assume there's no outer joins or
                               2068                 :                :      * appendrels in the dummy Query that surrounds a VALUES RTE.
                               2069                 :                :      */
 1052                          2070                 :           2297 :     perform_pullup_replace_vars(root, &rvcontext, NULL);
                               2071                 :                : 
                               2072                 :                :     /*
                               2073                 :                :      * There should be no appendrels to fix, nor any outer joins and hence no
                               2074                 :                :      * PlaceHolderVars.
                               2075                 :                :      */
 3934                          2076         [ -  + ]:           2297 :     Assert(root->append_rel_list == NIL);
                               2077         [ -  + ]:           2297 :     Assert(root->join_info_list == NIL);
                               2078         [ -  + ]:           2297 :     Assert(root->placeholder_list == NIL);
                               2079                 :                : 
                               2080                 :                :     /*
                               2081                 :                :      * Replace the VALUES RTE with a RESULT RTE.  The VALUES RTE is the only
                               2082                 :                :      * rtable entry in the current query level, so this is easy.
                               2083                 :                :      */
 2515                          2084         [ -  + ]:           2297 :     Assert(list_length(parse->rtable) == 1);
                               2085                 :                : 
                               2086                 :                :     /* Create suitable RTE */
                               2087                 :           2297 :     rte = makeNode(RangeTblEntry);
                               2088                 :           2297 :     rte->rtekind = RTE_RESULT;
                               2089                 :           2297 :     rte->eref = makeAlias("*RESULT*", NIL);
                               2090                 :                : 
                               2091                 :                :     /* Replace rangetable */
                               2092                 :           2297 :     parse->rtable = list_make1(rte);
                               2093                 :                : 
                               2094                 :                :     /* We could manufacture a new RangeTblRef, but the one we have is fine */
                               2095         [ -  + ]:           2297 :     Assert(varno == 1);
                               2096                 :                : 
                               2097                 :           2297 :     return jtnode;
                               2098                 :                : }
                               2099                 :                : 
                               2100                 :                : /*
                               2101                 :                :  * is_simple_values
                               2102                 :                :  *    Check a VALUES RTE in the range table to see if it's simple enough
                               2103                 :                :  *    to pull up into the parent query.
                               2104                 :                :  *
                               2105                 :                :  * rte is the RTE_VALUES RangeTblEntry to check.
                               2106                 :                :  */
                               2107                 :                : static bool
                               2108                 :           6539 : is_simple_values(PlannerInfo *root, RangeTblEntry *rte)
                               2109                 :                : {
 3934                          2110         [ -  + ]:           6539 :     Assert(rte->rtekind == RTE_VALUES);
                               2111                 :                : 
                               2112                 :                :     /*
                               2113                 :                :      * There must be exactly one VALUES list, else it's not semantically
                               2114                 :                :      * correct to replace the VALUES RTE with a RESULT RTE, nor would we have
                               2115                 :                :      * a unique set of expressions to substitute into the parent query.
                               2116                 :                :      */
                               2117         [ +  + ]:           6539 :     if (list_length(rte->values_lists) != 1)
                               2118                 :           4242 :         return false;
                               2119                 :                : 
                               2120                 :                :     /*
                               2121                 :                :      * Because VALUES can't appear under an outer join (or at least, we won't
                               2122                 :                :      * try to pull it up if it does), we need not worry about LATERAL, nor
                               2123                 :                :      * about validity of PHVs for the VALUES' outputs.
                               2124                 :                :      */
                               2125                 :                : 
                               2126                 :                :     /*
                               2127                 :                :      * Don't pull up a VALUES that contains any set-returning or volatile
                               2128                 :                :      * functions.  The considerations here are basically identical to the
                               2129                 :                :      * restrictions on a pull-able subquery's targetlist.
                               2130                 :                :      */
                               2131   [ +  -  -  + ]:           4594 :     if (expression_returns_set((Node *) rte->values_lists) ||
                               2132                 :           2297 :         contain_volatile_functions((Node *) rte->values_lists))
 3934 tgl@sss.pgh.pa.us        2133                 :UBC           0 :         return false;
                               2134                 :                : 
                               2135                 :                :     /*
                               2136                 :                :      * Do not pull up a VALUES that's not the only RTE in its parent query.
                               2137                 :                :      * This is actually the only case that the parser will generate at the
                               2138                 :                :      * moment, and assuming this is true greatly simplifies
                               2139                 :                :      * pull_up_simple_values().
                               2140                 :                :      */
 3934 tgl@sss.pgh.pa.us        2141         [ +  - ]:CBC        2297 :     if (list_length(root->parse->rtable) != 1 ||
                               2142         [ -  + ]:           2297 :         rte != (RangeTblEntry *) linitial(root->parse->rtable))
 8367 tgl@sss.pgh.pa.us        2143                 :UBC           0 :         return false;
                               2144                 :                : 
 8367 tgl@sss.pgh.pa.us        2145                 :CBC        2297 :     return true;
                               2146                 :                : }
                               2147                 :                : 
                               2148                 :                : /*
                               2149                 :                :  * pull_up_constant_function
                               2150                 :                :  *      Pull up an RTE_FUNCTION expression that was simplified to a constant.
                               2151                 :                :  *
                               2152                 :                :  * jtnode is a RangeTblRef that has been identified as a FUNCTION RTE by
                               2153                 :                :  * pull_up_subqueries.  If its expression is just a Const, hoist that value
                               2154                 :                :  * up into the parent query, and replace the RTE_FUNCTION with RTE_RESULT.
                               2155                 :                :  *
                               2156                 :                :  * In principle we could pull up any immutable expression, but we don't.
                               2157                 :                :  * That might result in multiple evaluations of the expression, which could
                               2158                 :                :  * be costly if it's not just a Const.  Also, the main value of this is
                               2159                 :                :  * to let the constant participate in further const-folding, and of course
                               2160                 :                :  * that won't happen for a non-Const.
                               2161                 :                :  *
                               2162                 :                :  * The pulled-up value might need to be wrapped in a PlaceHolderVar if the
                               2163                 :                :  * RTE is below an outer join or is part of an appendrel; the extra
                               2164                 :                :  * parameters show whether that's needed.
                               2165                 :                :  */
                               2166                 :                : static Node *
 2330                          2167                 :          25301 : pull_up_constant_function(PlannerInfo *root, Node *jtnode,
                               2168                 :                :                           RangeTblEntry *rte,
                               2169                 :                :                           AppendRelInfo *containing_appendrel)
                               2170                 :                : {
                               2171                 :          25301 :     Query      *parse = root->parse;
                               2172                 :                :     RangeTblFunction *rtf;
                               2173                 :                :     TypeFuncClass functypclass;
                               2174                 :                :     Oid         funcrettype;
                               2175                 :                :     TupleDesc   tupdesc;
                               2176                 :                :     pullup_replace_vars_context rvcontext;
                               2177                 :                : 
                               2178                 :                :     /* Fail if the RTE has ORDINALITY - we don't implement that here. */
                               2179         [ +  + ]:          25301 :     if (rte->funcordinality)
                               2180                 :            479 :         return jtnode;
                               2181                 :                : 
                               2182                 :                :     /* Fail if RTE isn't a single, simple Const expr */
                               2183         [ +  + ]:          24822 :     if (list_length(rte->functions) != 1)
                               2184                 :             36 :         return jtnode;
                               2185                 :          24786 :     rtf = linitial_node(RangeTblFunction, rte->functions);
                               2186         [ +  + ]:          24786 :     if (!IsA(rtf->funcexpr, Const))
                               2187                 :          24600 :         return jtnode;
                               2188                 :                : 
                               2189                 :                :     /*
                               2190                 :                :      * If the function's result is not a scalar, we punt.  In principle we
                               2191                 :                :      * could break the composite constant value apart into per-column
                               2192                 :                :      * constants, but for now it seems not worth the work.
                               2193                 :                :      */
 2276                          2194         [ +  + ]:            186 :     if (rtf->funccolcount != 1)
                               2195                 :             15 :         return jtnode;          /* definitely composite */
                               2196                 :                : 
                               2197                 :                :     /* If it has a coldeflist, it certainly returns RECORD */
  611                          2198         [ -  + ]:            171 :     if (rtf->funccolnames != NIL)
  611 tgl@sss.pgh.pa.us        2199                 :UBC           0 :         return jtnode;          /* must be a one-column RECORD type */
                               2200                 :                : 
 2276 tgl@sss.pgh.pa.us        2201                 :CBC         171 :     functypclass = get_expr_result_type(rtf->funcexpr,
                               2202                 :                :                                         &funcrettype,
                               2203                 :                :                                         &tupdesc);
                               2204         [ +  + ]:            171 :     if (functypclass != TYPEFUNC_SCALAR)
                               2205                 :              6 :         return jtnode;          /* must be a one-column composite type */
                               2206                 :                : 
                               2207                 :                :     /* Create context for applying pullup_replace_vars */
 2330                          2208                 :            165 :     rvcontext.root = root;
                               2209                 :            165 :     rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr,
                               2210                 :                :                                                       1,    /* resno */
                               2211                 :                :                                                       NULL, /* resname */
                               2212                 :                :                                                       false));  /* resjunk */
                               2213                 :            165 :     rvcontext.target_rte = rte;
  295 rguo@postgresql.org      2214                 :            165 :     rvcontext.result_relation = 0;
                               2215                 :                : 
                               2216                 :                :     /*
                               2217                 :                :      * Since this function was reduced to a Const, it doesn't contain any
                               2218                 :                :      * lateral references, even if it's marked as LATERAL.  This means we
                               2219                 :                :      * don't need to fill relids or nullinfo.
                               2220                 :                :      */
 2330 tgl@sss.pgh.pa.us        2221                 :            165 :     rvcontext.relids = NULL;
  382                          2222                 :            165 :     rvcontext.nullinfo = NULL;
                               2223                 :                : 
 2330                          2224                 :            165 :     rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
                               2225                 :            165 :     rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex;
                               2226                 :                :     /* this flag will be set below, if needed */
  279 rguo@postgresql.org      2227                 :            165 :     rvcontext.wrap_option = REPLACE_WRAP_NONE;
                               2228                 :                :     /* initialize cache array with indexes 0 .. length(tlist) */
 2330 tgl@sss.pgh.pa.us        2229                 :            165 :     rvcontext.rv_cache = palloc0((list_length(rvcontext.targetlist) + 1) *
                               2230                 :                :                                  sizeof(Node *));
                               2231                 :                : 
                               2232                 :                :     /*
                               2233                 :                :      * If the parent query uses grouping sets, we need a PlaceHolderVar for
                               2234                 :                :      * each expression of the subquery's targetlist items.  (See comments in
                               2235                 :                :      * pull_up_simple_subquery().)
                               2236                 :                :      */
                               2237         [ -  + ]:            165 :     if (parse->groupingSets)
  279 rguo@postgresql.org      2238                 :UBC           0 :         rvcontext.wrap_option = REPLACE_WRAP_ALL;
                               2239                 :                : 
                               2240                 :                :     /*
                               2241                 :                :      * Replace all of the top query's references to the RTE's output with
                               2242                 :                :      * copies of the funcexpr, being careful not to replace any of the
                               2243                 :                :      * jointree structure.
                               2244                 :                :      */
 2330 tgl@sss.pgh.pa.us        2245                 :CBC         165 :     perform_pullup_replace_vars(root, &rvcontext,
                               2246                 :                :                                 containing_appendrel);
                               2247                 :                : 
                               2248                 :                :     /*
                               2249                 :                :      * We don't need to bother with changing PlaceHolderVars in the parent
                               2250                 :                :      * query.  Their references to the RT index are still good for now, and
                               2251                 :                :      * will get removed later if we're able to drop the RTE_RESULT.
                               2252                 :                :      */
                               2253                 :                : 
                               2254                 :                :     /*
                               2255                 :                :      * Convert the RTE to be RTE_RESULT type, signifying that we don't need to
                               2256                 :                :      * scan it anymore, and zero out RTE_FUNCTION-specific fields.  Also make
                               2257                 :                :      * sure the RTE is not marked LATERAL, since elsewhere we don't expect
                               2258                 :                :      * RTE_RESULTs to be LATERAL.
                               2259                 :                :      */
                               2260                 :            165 :     rte->rtekind = RTE_RESULT;
                               2261                 :            165 :     rte->functions = NIL;
 1622                          2262                 :            165 :     rte->lateral = false;
                               2263                 :                : 
                               2264                 :                :     /*
                               2265                 :                :      * We can reuse the RangeTblRef node.
                               2266                 :                :      */
 2330                          2267                 :            165 :     return jtnode;
                               2268                 :                : }
                               2269                 :                : 
                               2270                 :                : /*
                               2271                 :                :  * is_simple_union_all
                               2272                 :                :  *    Check a subquery to see if it's a simple UNION ALL.
                               2273                 :                :  *
                               2274                 :                :  * We require all the setops to be UNION ALL (no mixing) and there can't be
                               2275                 :                :  * any datatype coercions involved, ie, all the leaf queries must emit the
                               2276                 :                :  * same datatypes.
                               2277                 :                :  */
                               2278                 :                : static bool
 7257                          2279                 :          14180 : is_simple_union_all(Query *subquery)
                               2280                 :                : {
                               2281                 :                :     SetOperationStmt *topop;
                               2282                 :                : 
                               2283                 :                :     /* Let's just make sure it's a valid subselect ... */
                               2284         [ +  - ]:          14180 :     if (!IsA(subquery, Query) ||
 3259                          2285         [ -  + ]:          14180 :         subquery->commandType != CMD_SELECT)
 7257 tgl@sss.pgh.pa.us        2286         [ #  # ]:UBC           0 :         elog(ERROR, "subquery is bogus");
                               2287                 :                : 
                               2288                 :                :     /* Is it a set-operation query at all? */
 3221 peter_e@gmx.net          2289                 :CBC       14180 :     topop = castNode(SetOperationStmt, subquery->setOperations);
 7257 tgl@sss.pgh.pa.us        2290         [ +  + ]:          14180 :     if (!topop)
                               2291                 :          11272 :         return false;
                               2292                 :                : 
                               2293                 :                :     /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
                               2294         [ +  + ]:           2908 :     if (subquery->sortClause ||
                               2295         [ +  - ]:           2876 :         subquery->limitOffset ||
                               2296         [ +  - ]:           2876 :         subquery->limitCount ||
 6283                          2297         [ +  - ]:           2876 :         subquery->rowMarks ||
                               2298         [ +  + ]:           2876 :         subquery->cteList)
 7257                          2299                 :            130 :         return false;
                               2300                 :                : 
                               2301                 :                :     /* Recursively check the tree of set operations */
                               2302                 :           2778 :     return is_simple_union_all_recurse((Node *) topop, subquery,
                               2303                 :                :                                        topop->colTypes);
                               2304                 :                : }
                               2305                 :                : 
                               2306                 :                : static bool
                               2307                 :          17607 : is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
                               2308                 :                : {
                               2309                 :                :     /* Since this function recurses, it could be driven to stack overflow. */
 1091                          2310                 :          17607 :     check_stack_depth();
                               2311                 :                : 
 7257                          2312         [ +  + ]:          17607 :     if (IsA(setOp, RangeTblRef))
                               2313                 :                :     {
                               2314                 :           8976 :         RangeTblRef *rtr = (RangeTblRef *) setOp;
                               2315                 :           8976 :         RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
                               2316                 :           8976 :         Query      *subquery = rte->subquery;
                               2317                 :                : 
                               2318         [ -  + ]:           8976 :         Assert(subquery != NULL);
                               2319                 :                : 
                               2320                 :                :         /* Leaf nodes are OK if they match the toplevel column types */
                               2321                 :                :         /* We don't have to compare typmods or collations here */
                               2322                 :           8976 :         return tlist_same_datatypes(subquery->targetList, colTypes, true);
                               2323                 :                :     }
                               2324         [ +  - ]:           8631 :     else if (IsA(setOp, SetOperationStmt))
                               2325                 :                :     {
                               2326                 :           8631 :         SetOperationStmt *op = (SetOperationStmt *) setOp;
                               2327                 :                : 
                               2328                 :                :         /* Must be UNION ALL */
                               2329   [ +  +  +  + ]:           8631 :         if (op->op != SETOP_UNION || !op->all)
                               2330                 :           2552 :             return false;
                               2331                 :                : 
                               2332                 :                :         /* Recurse to check inputs */
                               2333   [ +  +  +  + ]:          11778 :         return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
                               2334                 :           5699 :             is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
                               2335                 :                :     }
                               2336                 :                :     else
                               2337                 :                :     {
 7257 tgl@sss.pgh.pa.us        2338         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               2339                 :                :              (int) nodeTag(setOp));
                               2340                 :                :         return false;           /* keep compiler quiet */
                               2341                 :                :     }
                               2342                 :                : }
                               2343                 :                : 
                               2344                 :                : /*
                               2345                 :                :  * is_safe_append_member
                               2346                 :                :  *    Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
                               2347                 :                :  *    safe to pull up.
                               2348                 :                :  */
                               2349                 :                : static bool
 7257 tgl@sss.pgh.pa.us        2350                 :CBC        9660 : is_safe_append_member(Query *subquery)
                               2351                 :                : {
                               2352                 :                :     FromExpr   *jtnode;
                               2353                 :                : 
                               2354                 :                :     /*
                               2355                 :                :      * It's only safe to pull up the child if its jointree contains exactly
                               2356                 :                :      * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
                               2357                 :                :      * could be buried in several levels of FromExpr, however.  Also, if the
                               2358                 :                :      * child's jointree is completely empty, we can pull up because
                               2359                 :                :      * pull_up_simple_subquery will insert a single RTE_RESULT RTE instead.
                               2360                 :                :      *
                               2361                 :                :      * Also, the child can't have any WHERE quals because there's no place to
                               2362                 :                :      * put them in an appendrel.  (This is a bit annoying...) If we didn't
                               2363                 :                :      * need to check this, we'd just test whether get_relids_in_jointree()
                               2364                 :                :      * yields a singleton set, to be more consistent with the coding of
                               2365                 :                :      * fix_append_rel_relids().
                               2366                 :                :      */
                               2367                 :           9660 :     jtnode = subquery->jointree;
 2515                          2368         [ -  + ]:           9660 :     Assert(IsA(jtnode, FromExpr));
                               2369                 :                :     /* Check the completely-empty case */
                               2370   [ +  +  +  + ]:           9660 :     if (jtnode->fromlist == NIL && jtnode->quals == NULL)
                               2371                 :            292 :         return true;
                               2372                 :                :     /* Check the more general case */
 7257                          2373         [ +  + ]:          16469 :     while (IsA(jtnode, FromExpr))
                               2374                 :                :     {
                               2375         [ +  + ]:           9374 :         if (jtnode->quals != NULL)
                               2376                 :           2273 :             return false;
                               2377         [ -  + ]:           7101 :         if (list_length(jtnode->fromlist) != 1)
 7257 tgl@sss.pgh.pa.us        2378                 :UBC           0 :             return false;
 7257 tgl@sss.pgh.pa.us        2379                 :CBC        7101 :         jtnode = linitial(jtnode->fromlist);
                               2380                 :                :     }
                               2381         [ +  + ]:           7095 :     if (!IsA(jtnode, RangeTblRef))
                               2382                 :            893 :         return false;
                               2383                 :                : 
                               2384                 :           6202 :     return true;
                               2385                 :                : }
                               2386                 :                : 
                               2387                 :                : /*
                               2388                 :                :  * jointree_contains_lateral_outer_refs
                               2389                 :                :  *      Check for disallowed lateral references in a jointree's quals
                               2390                 :                :  *
                               2391                 :                :  * If restricted is false, all level-1 Vars are allowed (but we still must
                               2392                 :                :  * search the jointree, since it might contain outer joins below which there
                               2393                 :                :  * will be restrictions).  If restricted is true, return true when any qual
                               2394                 :                :  * in the jointree contains level-1 Vars coming from outside the rels listed
                               2395                 :                :  * in safe_upper_varnos.
                               2396                 :                :  */
                               2397                 :                : static bool
 1791                          2398                 :           2604 : jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode,
                               2399                 :                :                                      bool restricted,
                               2400                 :                :                                      Relids safe_upper_varnos)
                               2401                 :                : {
 4503                          2402         [ -  + ]:           2604 :     if (jtnode == NULL)
 4503 tgl@sss.pgh.pa.us        2403                 :UBC           0 :         return false;
 4503 tgl@sss.pgh.pa.us        2404         [ +  + ]:CBC        2604 :     if (IsA(jtnode, RangeTblRef))
                               2405                 :           1209 :         return false;
                               2406         [ +  + ]:           1395 :     else if (IsA(jtnode, FromExpr))
                               2407                 :                :     {
                               2408                 :           1238 :         FromExpr   *f = (FromExpr *) jtnode;
                               2409                 :                :         ListCell   *l;
                               2410                 :                : 
                               2411                 :                :         /* First, recurse to check child joins */
                               2412   [ +  +  +  +  :           2302 :         foreach(l, f->fromlist)
                                              +  + ]
                               2413                 :                :         {
 1791                          2414         [ +  + ]:           1076 :             if (jointree_contains_lateral_outer_refs(root,
                               2415                 :           1076 :                                                      lfirst(l),
                               2416                 :                :                                                      restricted,
                               2417                 :                :                                                      safe_upper_varnos))
 4503                          2418                 :             12 :                 return true;
                               2419                 :                :         }
                               2420                 :                : 
                               2421                 :                :         /* Then check the top-level quals */
                               2422         [ +  + ]:           1226 :         if (restricted &&
 1791                          2423         [ -  + ]:            714 :             !bms_is_subset(pull_varnos_of_level(root, f->quals, 1),
                               2424                 :                :                            safe_upper_varnos))
 4503 tgl@sss.pgh.pa.us        2425                 :UBC           0 :             return true;
                               2426                 :                :     }
 4503 tgl@sss.pgh.pa.us        2427         [ +  - ]:CBC         157 :     else if (IsA(jtnode, JoinExpr))
                               2428                 :                :     {
                               2429                 :            157 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               2430                 :                : 
                               2431                 :                :         /*
                               2432                 :                :          * If this is an outer join, we mustn't allow any upper lateral
                               2433                 :                :          * references in or below it.
                               2434                 :                :          */
                               2435         [ +  + ]:            157 :         if (j->jointype != JOIN_INNER)
                               2436                 :                :         {
                               2437                 :             79 :             restricted = true;
                               2438                 :             79 :             safe_upper_varnos = NULL;
                               2439                 :                :         }
                               2440                 :                : 
                               2441                 :                :         /* Check the child joins */
 1791                          2442         [ -  + ]:            157 :         if (jointree_contains_lateral_outer_refs(root,
                               2443                 :                :                                                  j->larg,
                               2444                 :                :                                                  restricted,
                               2445                 :                :                                                  safe_upper_varnos))
 4503 tgl@sss.pgh.pa.us        2446                 :UBC           0 :             return true;
 1791 tgl@sss.pgh.pa.us        2447         [ -  + ]:CBC         157 :         if (jointree_contains_lateral_outer_refs(root,
                               2448                 :                :                                                  j->rarg,
                               2449                 :                :                                                  restricted,
                               2450                 :                :                                                  safe_upper_varnos))
 4503 tgl@sss.pgh.pa.us        2451                 :UBC           0 :             return true;
                               2452                 :                : 
                               2453                 :                :         /* Check the JOIN's qual clauses */
 4503 tgl@sss.pgh.pa.us        2454         [ +  + ]:CBC         157 :         if (restricted &&
 1791                          2455         [ +  + ]:            145 :             !bms_is_subset(pull_varnos_of_level(root, j->quals, 1),
                               2456                 :                :                            safe_upper_varnos))
 4503                          2457                 :             12 :             return true;
                               2458                 :                :     }
                               2459                 :                :     else
 4503 tgl@sss.pgh.pa.us        2460         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               2461                 :                :              (int) nodeTag(jtnode));
 4503 tgl@sss.pgh.pa.us        2462                 :CBC        1371 :     return false;
                               2463                 :                : }
                               2464                 :                : 
                               2465                 :                : /*
                               2466                 :                :  * Perform pullup_replace_vars everyplace it's needed in the query tree.
                               2467                 :                :  *
                               2468                 :                :  * Caller has already filled *rvcontext with data describing what to
                               2469                 :                :  * substitute for Vars referencing the target subquery.  In addition
                               2470                 :                :  * we need the identity of the containing appendrel if any.
                               2471                 :                :  */
                               2472                 :                : static void
 2330                          2473                 :          21286 : perform_pullup_replace_vars(PlannerInfo *root,
                               2474                 :                :                             pullup_replace_vars_context *rvcontext,
                               2475                 :                :                             AppendRelInfo *containing_appendrel)
                               2476                 :                : {
                               2477                 :          21286 :     Query      *parse = root->parse;
                               2478                 :                :     ListCell   *lc;
                               2479                 :                : 
                               2480                 :                :     /*
                               2481                 :                :      * If we are considering an appendrel child subquery (that is, a UNION ALL
                               2482                 :                :      * member query that we're pulling up), then the only part of the upper
                               2483                 :                :      * query that could reference the child yet is the translated_vars list of
                               2484                 :                :      * the associated AppendRelInfo.  Furthermore, we do not want to force use
                               2485                 :                :      * of PHVs in the AppendRelInfo --- there isn't any outer join between.
                               2486                 :                :      */
 1091                          2487         [ +  + ]:          21286 :     if (containing_appendrel)
                               2488                 :                :     {
  279 rguo@postgresql.org      2489                 :           3190 :         ReplaceWrapOption save_wrap_option = rvcontext->wrap_option;
                               2490                 :                : 
                               2491                 :           3190 :         rvcontext->wrap_option = REPLACE_WRAP_NONE;
 1091 tgl@sss.pgh.pa.us        2492                 :           3190 :         containing_appendrel->translated_vars = (List *)
                               2493                 :           3190 :             pullup_replace_vars((Node *) containing_appendrel->translated_vars,
                               2494                 :                :                                 rvcontext);
  279 rguo@postgresql.org      2495                 :           3190 :         rvcontext->wrap_option = save_wrap_option;
 1091 tgl@sss.pgh.pa.us        2496                 :           3190 :         return;
                               2497                 :                :     }
                               2498                 :                : 
                               2499                 :                :     /*
                               2500                 :                :      * Replace all of the top query's references to the subquery's outputs
                               2501                 :                :      * with copies of the adjusted subtlist items, being careful not to
                               2502                 :                :      * replace any of the jointree structure.  (This'd be a lot cleaner if we
                               2503                 :                :      * could use query_tree_mutator.)  We have to use PHVs in the targetList,
                               2504                 :                :      * returningList, and havingQual, since those are certainly above any
                               2505                 :                :      * outer join.  replace_vars_in_jointree tracks its location in the
                               2506                 :                :      * jointree and uses PHVs or not appropriately.
                               2507                 :                :      */
 2330                          2508                 :          18096 :     parse->targetList = (List *)
                               2509                 :          18096 :         pullup_replace_vars((Node *) parse->targetList, rvcontext);
                               2510                 :          18096 :     parse->returningList = (List *)
                               2511                 :          18096 :         pullup_replace_vars((Node *) parse->returningList, rvcontext);
                               2512                 :                : 
                               2513         [ +  + ]:          18096 :     if (parse->onConflict)
                               2514                 :                :     {
                               2515                 :             22 :         parse->onConflict->onConflictSet = (List *)
                               2516                 :             11 :             pullup_replace_vars((Node *) parse->onConflict->onConflictSet,
                               2517                 :                :                                 rvcontext);
                               2518                 :             11 :         parse->onConflict->onConflictWhere =
                               2519                 :             11 :             pullup_replace_vars(parse->onConflict->onConflictWhere,
                               2520                 :                :                                 rvcontext);
                               2521                 :                : 
                               2522                 :                :         /*
                               2523                 :                :          * We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist
                               2524                 :                :          * can't contain any references to a subquery.
                               2525                 :                :          */
                               2526                 :                :     }
 1360 alvherre@alvh.no-ip.     2527         [ +  + ]:          18096 :     if (parse->mergeActionList)
                               2528                 :                :     {
                               2529   [ +  -  +  +  :           1519 :         foreach(lc, parse->mergeActionList)
                                              +  + ]
                               2530                 :                :         {
                               2531                 :            907 :             MergeAction *action = lfirst(lc);
                               2532                 :                : 
                               2533                 :            907 :             action->qual = pullup_replace_vars(action->qual, rvcontext);
                               2534                 :            907 :             action->targetList = (List *)
                               2535                 :            907 :                 pullup_replace_vars((Node *) action->targetList, rvcontext);
                               2536                 :                :         }
                               2537                 :                :     }
  627 dean.a.rasheed@gmail     2538                 :          18096 :     parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition,
                               2539                 :                :                                                     rvcontext);
 1052 tgl@sss.pgh.pa.us        2540                 :          18096 :     replace_vars_in_jointree((Node *) parse->jointree, rvcontext);
 2330                          2541         [ -  + ]:          18093 :     Assert(parse->setOperations == NULL);
                               2542                 :          18093 :     parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
                               2543                 :                : 
                               2544                 :                :     /*
                               2545                 :                :      * Replace references in the translated_vars lists of appendrels.
                               2546                 :                :      */
                               2547   [ +  +  +  +  :          18111 :     foreach(lc, root->append_rel_list)
                                              +  + ]
                               2548                 :                :     {
                               2549                 :             18 :         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
                               2550                 :                : 
                               2551                 :             18 :         appinfo->translated_vars = (List *)
                               2552                 :             18 :             pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext);
                               2553                 :                :     }
                               2554                 :                : 
                               2555                 :                :     /*
                               2556                 :                :      * Replace references in the joinaliasvars lists of join RTEs and the
                               2557                 :                :      * groupexprs list of group RTE.
                               2558                 :                :      */
                               2559   [ +  -  +  +  :          50578 :     foreach(lc, parse->rtable)
                                              +  + ]
                               2560                 :                :     {
                               2561                 :          32485 :         RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
                               2562                 :                : 
                               2563         [ +  + ]:          32485 :         if (otherrte->rtekind == RTE_JOIN)
                               2564                 :           3452 :             otherrte->joinaliasvars = (List *)
                               2565                 :           3452 :                 pullup_replace_vars((Node *) otherrte->joinaliasvars,
                               2566                 :                :                                     rvcontext);
  463 rguo@postgresql.org      2567         [ +  + ]:          29033 :         else if (otherrte->rtekind == RTE_GROUP)
                               2568                 :            369 :             otherrte->groupexprs = (List *)
                               2569                 :            369 :                 pullup_replace_vars((Node *) otherrte->groupexprs,
                               2570                 :                :                                     rvcontext);
                               2571                 :                :     }
                               2572                 :                : }
                               2573                 :                : 
                               2574                 :                : /*
                               2575                 :                :  * Helper routine for perform_pullup_replace_vars: do pullup_replace_vars on
                               2576                 :                :  * every expression in the jointree, without changing the jointree structure
                               2577                 :                :  * itself.  Ugly, but there's no other way...
                               2578                 :                :  */
                               2579                 :                : static void
 5950 tgl@sss.pgh.pa.us        2580                 :          47299 : replace_vars_in_jointree(Node *jtnode,
                               2581                 :                :                          pullup_replace_vars_context *context)
                               2582                 :                : {
 8367                          2583         [ -  + ]:          47299 :     if (jtnode == NULL)
 8367 tgl@sss.pgh.pa.us        2584                 :UBC           0 :         return;
 8367 tgl@sss.pgh.pa.us        2585         [ +  + ]:CBC       47299 :     if (IsA(jtnode, RangeTblRef))
                               2586                 :                :     {
                               2587                 :                :         /*
                               2588                 :                :          * If the RangeTblRef refers to a LATERAL subquery (that isn't the
                               2589                 :                :          * same subquery we're pulling up), it might contain references to the
                               2590                 :                :          * target subquery, which we must replace.  We drive this from the
                               2591                 :                :          * jointree scan, rather than a scan of the rtable, so that we can
                               2592                 :                :          * avoid processing no-longer-referenced RTEs.
                               2593                 :                :          */
 4869                          2594                 :          23744 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               2595                 :                : 
                               2596         [ +  + ]:          23744 :         if (varno != context->varno) /* ignore target subquery itself */
                               2597                 :                :         {
                               2598                 :           5648 :             RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
                               2599                 :                : 
                               2600         [ -  + ]:           5648 :             Assert(rte != context->target_rte);
                               2601         [ +  + ]:           5648 :             if (rte->lateral)
                               2602                 :                :             {
                               2603   [ -  +  +  +  :            461 :                 switch (rte->rtekind)
                                           -  -  - ]
                               2604                 :                :                 {
 3798 tgl@sss.pgh.pa.us        2605                 :UBC           0 :                     case RTE_RELATION:
                               2606                 :                :                         /* shouldn't be marked LATERAL unless tablesample */
                               2607         [ #  # ]:              0 :                         Assert(rte->tablesample);
                               2608                 :              0 :                         rte->tablesample = (TableSampleClause *)
                               2609                 :              0 :                             pullup_replace_vars((Node *) rte->tablesample,
                               2610                 :                :                                                 context);
                               2611                 :              0 :                         break;
 4869 tgl@sss.pgh.pa.us        2612                 :CBC         225 :                     case RTE_SUBQUERY:
                               2613                 :            225 :                         rte->subquery =
                               2614                 :            225 :                             pullup_replace_vars_subquery(rte->subquery,
                               2615                 :                :                                                          context);
                               2616                 :            225 :                         break;
                               2617                 :            182 :                     case RTE_FUNCTION:
 4409                          2618                 :            182 :                         rte->functions = (List *)
                               2619                 :            182 :                             pullup_replace_vars((Node *) rte->functions,
                               2620                 :                :                                                 context);
 4869                          2621                 :            182 :                         break;
 3206 alvherre@alvh.no-ip.     2622                 :             54 :                     case RTE_TABLEFUNC:
                               2623                 :             54 :                         rte->tablefunc = (TableFunc *)
                               2624                 :             54 :                             pullup_replace_vars((Node *) rte->tablefunc,
                               2625                 :                :                                                 context);
                               2626                 :             54 :                         break;
 4869 tgl@sss.pgh.pa.us        2627                 :UBC           0 :                     case RTE_VALUES:
                               2628                 :              0 :                         rte->values_lists = (List *)
                               2629                 :              0 :                             pullup_replace_vars((Node *) rte->values_lists,
                               2630                 :                :                                                 context);
                               2631                 :              0 :                         break;
                               2632                 :              0 :                     case RTE_JOIN:
                               2633                 :                :                     case RTE_CTE:
                               2634                 :                :                     case RTE_NAMEDTUPLESTORE:
                               2635                 :                :                     case RTE_RESULT:
                               2636                 :                :                     case RTE_GROUP:
                               2637                 :                :                         /* these shouldn't be marked LATERAL */
                               2638                 :              0 :                         Assert(false);
                               2639                 :                :                         break;
                               2640                 :                :                 }
                               2641                 :                :             }
                               2642                 :                :         }
                               2643                 :                :     }
 8367 tgl@sss.pgh.pa.us        2644         [ +  + ]:CBC       23555 :     else if (IsA(jtnode, FromExpr))
                               2645                 :                :     {
                               2646                 :          19474 :         FromExpr   *f = (FromExpr *) jtnode;
                               2647                 :                :         ListCell   *l;
                               2648                 :                : 
                               2649   [ +  -  +  +  :          40515 :         foreach(l, f->fromlist)
                                              +  + ]
 1052                          2650                 :          21041 :             replace_vars_in_jointree(lfirst(l), context);
 5950                          2651                 :          19474 :         f->quals = pullup_replace_vars(f->quals, context);
                               2652                 :                :     }
 8367                          2653         [ +  - ]:           4081 :     else if (IsA(jtnode, JoinExpr))
                               2654                 :                :     {
                               2655                 :           4081 :         JoinExpr   *j = (JoinExpr *) jtnode;
  279 rguo@postgresql.org      2656                 :           4081 :         ReplaceWrapOption save_wrap_option = context->wrap_option;
                               2657                 :                : 
 1052 tgl@sss.pgh.pa.us        2658                 :           4081 :         replace_vars_in_jointree(j->larg, context);
                               2659                 :           4081 :         replace_vars_in_jointree(j->rarg, context);
                               2660                 :                : 
                               2661                 :                :         /*
                               2662                 :                :          * Use PHVs within the join quals of a full join for variable-free
                               2663                 :                :          * expressions.  Otherwise, we cannot identify which side of the join
                               2664                 :                :          * a pulled-up variable-free expression came from, which can lead to
                               2665                 :                :          * failure to make a plan at all because none of the quals appear to
                               2666                 :                :          * be mergeable or hashable conditions.
                               2667                 :                :          */
 2621                          2668         [ +  + ]:           4081 :         if (j->jointype == JOIN_FULL)
  279 rguo@postgresql.org      2669                 :            314 :             context->wrap_option = REPLACE_WRAP_VARFREE;
                               2670                 :                : 
 5950 tgl@sss.pgh.pa.us        2671                 :           4081 :         j->quals = pullup_replace_vars(j->quals, context);
                               2672                 :                : 
  279 rguo@postgresql.org      2673                 :           4081 :         context->wrap_option = save_wrap_option;
                               2674                 :                :     }
                               2675                 :                :     else
 8181 tgl@sss.pgh.pa.us        2676         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               2677                 :                :              (int) nodeTag(jtnode));
                               2678                 :                : }
                               2679                 :                : 
                               2680                 :                : /*
                               2681                 :                :  * Apply pullup variable replacement throughout an expression tree
                               2682                 :                :  *
                               2683                 :                :  * Returns a modified copy of the tree, so this can't be used where we
                               2684                 :                :  * need to do in-place replacement.
                               2685                 :                :  */
                               2686                 :                : static Node *
 5950 tgl@sss.pgh.pa.us        2687                 :CBC      105588 : pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
                               2688                 :                : {
                               2689                 :         105588 :     return replace_rte_variables(expr,
                               2690                 :                :                                  context->varno, 0,
                               2691                 :                :                                  pullup_replace_vars_callback,
                               2692                 :                :                                  context,
                               2693                 :                :                                  context->outer_hasSubLinks);
                               2694                 :                : }
                               2695                 :                : 
                               2696                 :                : static Node *
                               2697                 :          58571 : pullup_replace_vars_callback(Var *var,
                               2698                 :                :                              replace_rte_variables_context *context)
                               2699                 :                : {
                               2700                 :          58571 :     pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
                               2701                 :          58571 :     int         varattno = var->varattno;
                               2702                 :                :     bool        need_phv;
                               2703                 :                :     Node       *newnode;
                               2704                 :                : 
                               2705                 :                :     /* System columns are not replaced. */
  295 rguo@postgresql.org      2706         [ +  + ]:          58571 :     if (varattno < InvalidAttrNumber)
                               2707                 :             21 :         return (Node *) copyObject(var);
                               2708                 :                : 
                               2709                 :                :     /*
                               2710                 :                :      * We need a PlaceHolderVar if the Var-to-be-replaced has nonempty
                               2711                 :                :      * varnullingrels (unless we find below that the replacement expression is
                               2712                 :                :      * a Var or PlaceHolderVar that we can just add the nullingrels to).  We
                               2713                 :                :      * also need one if the caller has instructed us that certain expression
                               2714                 :                :      * replacements need to be wrapped for identification purposes.
                               2715                 :                :      */
  279                          2716         [ +  + ]:         111154 :     need_phv = (var->varnullingrels != NULL) ||
                               2717         [ +  + ]:          52604 :         (rcon->wrap_option != REPLACE_WRAP_NONE);
                               2718                 :                : 
                               2719                 :                :     /*
                               2720                 :                :      * If PlaceHolderVars are needed, we cache the modified expressions in
                               2721                 :                :      * rcon->rv_cache[].  This is not in hopes of any material speed gain
                               2722                 :                :      * within this function, but to avoid generating identical PHVs with
                               2723                 :                :      * different IDs.  That would result in duplicate evaluations at runtime,
                               2724                 :                :      * and possibly prevent optimizations that rely on recognizing different
                               2725                 :                :      * references to the same subquery output as being equal().  So it's worth
                               2726                 :                :      * a bit of extra effort to avoid it.
                               2727                 :                :      *
                               2728                 :                :      * The cached items have phlevelsup = 0 and phnullingrels = NULL; we'll
                               2729                 :                :      * copy them and adjust those values for this reference site below.
                               2730                 :                :      */
 1052 tgl@sss.pgh.pa.us        2731   [ +  +  +  - ]:          58550 :     if (need_phv &&
 5950                          2732         [ +  - ]:           6929 :         varattno >= InvalidAttrNumber &&
                               2733                 :           6929 :         varattno <= list_length(rcon->targetlist) &&
                               2734         [ +  + ]:           6929 :         rcon->rv_cache[varattno] != NULL)
                               2735                 :                :     {
                               2736                 :                :         /* Just copy the entry and fall through to adjust phlevelsup etc */
                               2737                 :           1418 :         newnode = copyObject(rcon->rv_cache[varattno]);
                               2738                 :                :     }
                               2739                 :                :     else
                               2740                 :                :     {
                               2741                 :                :         /*
                               2742                 :                :          * Generate the replacement expression.  This takes care of expanding
                               2743                 :                :          * wholerow references and dealing with non-default varreturningtype.
                               2744                 :                :          */
  295 rguo@postgresql.org      2745                 :          57132 :         newnode = ReplaceVarFromTargetList(var,
                               2746                 :                :                                            rcon->target_rte,
                               2747                 :                :                                            rcon->targetlist,
                               2748                 :                :                                            rcon->result_relation,
                               2749                 :                :                                            REPLACEVARS_REPORT_ERROR,
                               2750                 :                :                                            0);
                               2751                 :                : 
                               2752                 :                :         /* Insert PlaceHolderVar if needed */
 1052 tgl@sss.pgh.pa.us        2753         [ +  + ]:          57132 :         if (need_phv)
                               2754                 :                :         {
                               2755                 :                :             bool        wrap;
                               2756                 :                : 
  279 rguo@postgresql.org      2757         [ +  + ]:           5511 :             if (rcon->wrap_option == REPLACE_WRAP_ALL)
                               2758                 :                :             {
                               2759                 :                :                 /* Caller told us to wrap all expressions in a PlaceHolderVar */
                               2760                 :            400 :                 wrap = true;
                               2761                 :                :             }
                               2762         [ +  + ]:           5111 :             else if (varattno == InvalidAttrNumber)
                               2763                 :                :             {
                               2764                 :                :                 /*
                               2765                 :                :                  * Insert PlaceHolderVar for whole-tuple reference.  Notice
                               2766                 :                :                  * that we are wrapping one PlaceHolderVar around the whole
                               2767                 :                :                  * RowExpr, rather than putting one around each element of the
                               2768                 :                :                  * row.  This is because we need the expression to yield NULL,
                               2769                 :                :                  * not ROW(NULL,NULL,...) when it is forced to null by an
                               2770                 :                :                  * outer join.
                               2771                 :                :                  */
  295                          2772                 :             36 :                 wrap = true;
                               2773                 :                :             }
                               2774   [ +  -  +  + ]:           5075 :             else if (newnode && IsA(newnode, Var) &&
                               2775         [ +  + ]:           4058 :                      ((Var *) newnode)->varlevelsup == 0)
                               2776                 :                :             {
                               2777                 :                :                 /*
                               2778                 :                :                  * Simple Vars always escape being wrapped, unless they are
                               2779                 :                :                  * lateral references to something outside the subquery being
                               2780                 :                :                  * pulled up and the referenced rel is not under the same
                               2781                 :                :                  * lowest nulling outer join.
                               2782                 :                :                  */
  373                          2783                 :           4050 :                 wrap = false;
 4505 tgl@sss.pgh.pa.us        2784         [ +  + ]:           4050 :                 if (rcon->target_rte->lateral &&
                               2785         [ +  + ]:            705 :                     !bms_is_member(((Var *) newnode)->varno, rcon->relids))
                               2786                 :                :                 {
  373 rguo@postgresql.org      2787                 :             66 :                     nullingrel_info *nullinfo = rcon->nullinfo;
                               2788                 :             66 :                     int         lvarno = ((Var *) newnode)->varno;
                               2789                 :                : 
                               2790   [ +  -  -  + ]:             66 :                     Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
                               2791         [ +  + ]:             66 :                     if (!bms_is_subset(nullinfo->nullingrels[rcon->varno],
                               2792                 :             66 :                                        nullinfo->nullingrels[lvarno]))
                               2793                 :             54 :                         wrap = true;
                               2794                 :                :                 }
                               2795                 :                :             }
 5244 tgl@sss.pgh.pa.us        2796   [ +  -  +  + ]:           1025 :             else if (newnode && IsA(newnode, PlaceHolderVar) &&
                               2797         [ +  - ]:             90 :                      ((PlaceHolderVar *) newnode)->phlevelsup == 0)
                               2798                 :                :             {
                               2799                 :                :                 /* The same rules apply for a PlaceHolderVar */
  373 rguo@postgresql.org      2800                 :             90 :                 wrap = false;
  706 tgl@sss.pgh.pa.us        2801         [ +  + ]:             90 :                 if (rcon->target_rte->lateral &&
                               2802         [ +  - ]:             24 :                     !bms_is_subset(((PlaceHolderVar *) newnode)->phrels,
                               2803                 :             24 :                                    rcon->relids))
                               2804                 :                :                 {
  373 rguo@postgresql.org      2805                 :             24 :                     nullingrel_info *nullinfo = rcon->nullinfo;
                               2806                 :             24 :                     Relids      lvarnos = ((PlaceHolderVar *) newnode)->phrels;
                               2807                 :                :                     int         lvarno;
                               2808                 :                : 
                               2809                 :             24 :                     lvarno = -1;
                               2810         [ +  + ]:             36 :                     while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0)
                               2811                 :                :                     {
                               2812   [ +  -  -  + ]:             24 :                         Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
                               2813         [ +  + ]:             24 :                         if (!bms_is_subset(nullinfo->nullingrels[rcon->varno],
                               2814                 :             24 :                                            nullinfo->nullingrels[lvarno]))
                               2815                 :                :                         {
                               2816                 :             12 :                             wrap = true;
                               2817                 :             12 :                             break;
                               2818                 :                :                         }
                               2819                 :                :                     }
                               2820                 :                :                 }
                               2821                 :                :             }
                               2822                 :                :             else
                               2823                 :                :             {
                               2824                 :                :                 /*
                               2825                 :                :                  * If the node contains Var(s) or PlaceHolderVar(s) of the
                               2826                 :                :                  * subquery being pulled up, or of rels that are under the
                               2827                 :                :                  * same lowest nulling outer join as the subquery, and does
                               2828                 :                :                  * not contain any non-strict constructs, then instead of
                               2829                 :                :                  * adding a PHV on top we can add the required nullingrels to
                               2830                 :                :                  * those Vars/PHVs.  (This is fundamentally a generalization
                               2831                 :                :                  * of the above cases for bare Vars and PHVs.)
                               2832                 :                :                  *
                               2833                 :                :                  * This test is somewhat expensive, but it avoids pessimizing
                               2834                 :                :                  * the plan in cases where the nullingrels get removed again
                               2835                 :                :                  * later by outer join reduction.
                               2836                 :                :                  *
                               2837                 :                :                  * Note that we don't force wrapping of expressions containing
                               2838                 :                :                  * lateral references, so long as they also contain Vars/PHVs
                               2839                 :                :                  * of the subquery, or of rels that are under the same lowest
                               2840                 :                :                  * nulling outer join as the subquery.  This is okay because
                               2841                 :                :                  * of the restriction to strict constructs: if those Vars/PHVs
                               2842                 :                :                  * have been forced to NULL by an outer join then the end
                               2843                 :                :                  * result of the expression will be NULL too, regardless of
                               2844                 :                :                  * the lateral references.  So it's not necessary to force the
                               2845                 :                :                  * expression to be evaluated below the outer join.  This can
                               2846                 :                :                  * be a very valuable optimization, because it may allow us to
                               2847                 :                :                  * avoid using a nested loop to pass the lateral reference
                               2848                 :                :                  * down.
                               2849                 :                :                  *
                               2850                 :                :                  * This analysis could be tighter: in particular, a non-strict
                               2851                 :                :                  * construct hidden within a lower-level PlaceHolderVar is not
                               2852                 :                :                  * reason to add another PHV.  But for now it doesn't seem
                               2853                 :                :                  * worth the code to be more exact.  This is also why it's
                               2854                 :                :                  * preferable to handle bare PHVs in the above branch, rather
                               2855                 :                :                  * than this branch.  We also prefer to handle bare Vars in a
                               2856                 :                :                  * separate branch, as it's cheaper this way and parallels the
                               2857                 :                :                  * handling of PHVs.
                               2858                 :                :                  *
                               2859                 :                :                  * For a LATERAL subquery, we have to check the actual var
                               2860                 :                :                  * membership of the node, but if it's non-lateral then any
                               2861                 :                :                  * level-zero var must belong to the subquery.
                               2862                 :                :                  */
  365                          2863                 :            935 :                 bool        contain_nullable_vars = false;
                               2864                 :                : 
                               2865         [ +  + ]:            935 :                 if (!rcon->target_rte->lateral)
                               2866                 :                :                 {
                               2867         [ +  + ]:            821 :                     if (contain_vars_of_level(newnode, 0))
                               2868                 :            267 :                         contain_nullable_vars = true;
                               2869                 :                :                 }
                               2870                 :                :                 else
                               2871                 :                :                 {
                               2872                 :                :                     Relids      all_varnos;
                               2873                 :                : 
                               2874                 :            114 :                     all_varnos = pull_varnos(rcon->root, newnode);
                               2875         [ +  + ]:            114 :                     if (bms_overlap(all_varnos, rcon->relids))
                               2876                 :             66 :                         contain_nullable_vars = true;
                               2877                 :                :                     else
                               2878                 :                :                     {
                               2879                 :             48 :                         nullingrel_info *nullinfo = rcon->nullinfo;
                               2880                 :                :                         int         varno;
                               2881                 :                : 
                               2882                 :             48 :                         varno = -1;
                               2883         [ +  + ]:             90 :                         while ((varno = bms_next_member(all_varnos, varno)) >= 0)
                               2884                 :                :                         {
                               2885   [ +  -  -  + ]:             54 :                             Assert(varno > 0 && varno <= nullinfo->rtlength);
                               2886         [ +  + ]:             54 :                             if (bms_is_subset(nullinfo->nullingrels[rcon->varno],
                               2887                 :             54 :                                               nullinfo->nullingrels[varno]))
                               2888                 :                :                             {
                               2889                 :             12 :                                 contain_nullable_vars = true;
                               2890                 :             12 :                                 break;
                               2891                 :                :                             }
                               2892                 :                :                         }
                               2893                 :                :                     }
                               2894                 :                :                 }
                               2895                 :                : 
                               2896         [ +  + ]:            935 :                 if (contain_nullable_vars &&
  474 tgl@sss.pgh.pa.us        2897         [ +  + ]:            345 :                     !contain_nonstrict_functions(newnode))
                               2898                 :                :                 {
                               2899                 :                :                     /* No wrap needed */
                               2900                 :            144 :                     wrap = false;
                               2901                 :                :                 }
                               2902                 :                :                 else
                               2903                 :                :                 {
                               2904                 :                :                     /* Else wrap it in a PlaceHolderVar */
                               2905                 :            791 :                     wrap = true;
                               2906                 :                :                 }
                               2907                 :                :             }
                               2908                 :                : 
 5950                          2909         [ +  + ]:           5511 :             if (wrap)
                               2910                 :                :             {
                               2911                 :                :                 newnode = (Node *)
                               2912                 :           1293 :                     make_placeholder_expr(rcon->root,
                               2913                 :                :                                           (Expr *) newnode,
                               2914                 :                :                                           bms_make_singleton(rcon->varno));
                               2915                 :                : 
                               2916                 :                :                 /*
                               2917                 :                :                  * Cache it if possible (ie, if the attno is in range, which
                               2918                 :                :                  * it probably always should be).
                               2919                 :                :                  */
  295 rguo@postgresql.org      2920   [ +  -  +  - ]:           2586 :                 if (varattno >= InvalidAttrNumber &&
 1052 tgl@sss.pgh.pa.us        2921                 :           1293 :                     varattno <= list_length(rcon->targetlist))
                               2922                 :           1293 :                     rcon->rv_cache[varattno] = copyObject(newnode);
                               2923                 :                :             }
                               2924                 :                :         }
                               2925                 :                :     }
                               2926                 :                : 
                               2927                 :                :     /* Propagate any varnullingrels into the replacement expression */
                               2928         [ +  + ]:          58550 :     if (var->varnullingrels != NULL)
                               2929                 :                :     {
                               2930         [ +  + ]:           5946 :         if (IsA(newnode, Var))
                               2931                 :                :         {
                               2932                 :           3751 :             Var        *newvar = (Var *) newnode;
                               2933                 :                : 
  474                          2934         [ -  + ]:           3751 :             Assert(newvar->varlevelsup == 0);
 1052                          2935                 :           3751 :             newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
                               2936                 :           3751 :                                                      var->varnullingrels);
                               2937                 :                :         }
                               2938         [ +  + ]:           2195 :         else if (IsA(newnode, PlaceHolderVar))
                               2939                 :                :         {
                               2940                 :           2051 :             PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
                               2941                 :                : 
  474                          2942         [ -  + ]:           2051 :             Assert(newphv->phlevelsup == 0);
 1052                          2943                 :           2051 :             newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
                               2944                 :           2051 :                                                     var->varnullingrels);
                               2945                 :                :         }
                               2946                 :                :         else
                               2947                 :                :         {
                               2948                 :                :             /*
                               2949                 :                :              * There should be Vars/PHVs within the expression that we can
                               2950                 :                :              * modify.  Vars/PHVs of the subquery should have the full
                               2951                 :                :              * var->varnullingrels added to them, but if there are lateral
                               2952                 :                :              * references within the expression, those must be marked with
                               2953                 :                :              * only the nullingrels that potentially apply to them.  (This
                               2954                 :                :              * corresponds to the fact that the expression will now be
                               2955                 :                :              * evaluated at the join level of the Var that we are replacing:
                               2956                 :                :              * the lateral references may have bubbled up through fewer outer
                               2957                 :                :              * joins than the subquery's Vars have.  Per the discussion above,
                               2958                 :                :              * we'll still get the right answers.)  That relid set could be
                               2959                 :                :              * different for different lateral relations, so we have to do
                               2960                 :                :              * this work for each one.
                               2961                 :                :              *
                               2962                 :                :              * (Currently, the restrictions in is_simple_subquery() mean that
                               2963                 :                :              * at most we have to remove the lowest outer join's relid from
                               2964                 :                :              * the nullingrels of a lateral reference.  However, we might
                               2965                 :                :              * relax those restrictions someday, so let's do this right.)
                               2966                 :                :              */
  382                          2967         [ +  + ]:            144 :             if (rcon->target_rte->lateral)
                               2968                 :                :             {
                               2969                 :             42 :                 nullingrel_info *nullinfo = rcon->nullinfo;
                               2970                 :                :                 Relids      lvarnos;
                               2971                 :                :                 int         lvarno;
                               2972                 :                : 
                               2973                 :                :                 /*
                               2974                 :                :                  * Identify lateral varnos used within newnode.  We must do
                               2975                 :                :                  * this before injecting var->varnullingrels into the tree.
                               2976                 :                :                  */
                               2977                 :             42 :                 lvarnos = pull_varnos(rcon->root, newnode);
                               2978                 :             42 :                 lvarnos = bms_del_members(lvarnos, rcon->relids);
                               2979                 :                :                 /* For each one, add relevant nullingrels if any */
                               2980                 :             42 :                 lvarno = -1;
                               2981         [ +  + ]:             84 :                 while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0)
                               2982                 :                :                 {
                               2983                 :                :                     Relids      lnullingrels;
                               2984                 :                : 
                               2985   [ +  -  -  + ]:             42 :                     Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
                               2986                 :             42 :                     lnullingrels = bms_intersect(var->varnullingrels,
                               2987                 :             42 :                                                  nullinfo->nullingrels[lvarno]);
                               2988         [ +  + ]:             42 :                     if (!bms_is_empty(lnullingrels))
                               2989                 :             24 :                         newnode = add_nulling_relids(newnode,
                               2990                 :             24 :                                                      bms_make_singleton(lvarno),
                               2991                 :                :                                                      lnullingrels);
                               2992                 :                :                 }
                               2993                 :                :             }
                               2994                 :                : 
                               2995                 :                :             /* Finally, deal with Vars/PHVs of the subquery itself */
  474                          2996                 :            144 :             newnode = add_nulling_relids(newnode,
  384                          2997                 :            144 :                                          rcon->relids,
  474                          2998                 :            144 :                                          var->varnullingrels);
                               2999                 :                :             /* Assert we did put the varnullingrels into the expression */
                               3000         [ -  + ]:            144 :             Assert(bms_is_subset(var->varnullingrels,
                               3001                 :                :                                  pull_varnos(rcon->root, newnode)));
                               3002                 :                :         }
                               3003                 :                :     }
                               3004                 :                : 
                               3005                 :                :     /* Must adjust varlevelsup if replaced Var is within a subquery */
                               3006         [ +  + ]:          58550 :     if (var->varlevelsup > 0)
                               3007                 :            613 :         IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
                               3008                 :                : 
 5950                          3009                 :          58550 :     return newnode;
                               3010                 :                : }
                               3011                 :                : 
                               3012                 :                : /*
                               3013                 :                :  * Apply pullup variable replacement to a subquery
                               3014                 :                :  *
                               3015                 :                :  * This needs to be different from pullup_replace_vars() because
                               3016                 :                :  * replace_rte_variables will think that it shouldn't increment sublevels_up
                               3017                 :                :  * before entering the Query; so we need to call it with sublevels_up == 1.
                               3018                 :                :  */
                               3019                 :                : static Query *
 4869                          3020                 :            225 : pullup_replace_vars_subquery(Query *query,
                               3021                 :                :                              pullup_replace_vars_context *context)
                               3022                 :                : {
                               3023         [ -  + ]:            225 :     Assert(IsA(query, Query));
                               3024                 :            225 :     return (Query *) replace_rte_variables((Node *) query,
                               3025                 :                :                                            context->varno, 1,
                               3026                 :                :                                            pullup_replace_vars_callback,
                               3027                 :                :                                            context,
                               3028                 :                :                                            NULL);
                               3029                 :                : }
                               3030                 :                : 
                               3031                 :                : 
                               3032                 :                : /*
                               3033                 :                :  * flatten_simple_union_all
                               3034                 :                :  *      Try to optimize top-level UNION ALL structure into an appendrel
                               3035                 :                :  *
                               3036                 :                :  * If a query's setOperations tree consists entirely of simple UNION ALL
                               3037                 :                :  * operations, flatten it into an append relation, which we can process more
                               3038                 :                :  * intelligently than the general setops case.  Otherwise, do nothing.
                               3039                 :                :  *
                               3040                 :                :  * In most cases, this can succeed only for a top-level query, because for a
                               3041                 :                :  * subquery in FROM, the parent query's invocation of pull_up_subqueries would
                               3042                 :                :  * already have flattened the UNION via pull_up_simple_union_all.  But there
                               3043                 :                :  * are a few cases we can support here but not in that code path, for example
                               3044                 :                :  * when the subquery also contains ORDER BY.
                               3045                 :                :  */
                               3046                 :                : void
 5518                          3047                 :           3525 : flatten_simple_union_all(PlannerInfo *root)
                               3048                 :                : {
                               3049                 :           3525 :     Query      *parse = root->parse;
                               3050                 :                :     SetOperationStmt *topop;
                               3051                 :                :     Node       *leftmostjtnode;
                               3052                 :                :     int         leftmostRTI;
                               3053                 :                :     RangeTblEntry *leftmostRTE;
                               3054                 :                :     int         childRTI;
                               3055                 :                :     RangeTblEntry *childRTE;
                               3056                 :                :     RangeTblRef *rtr;
                               3057                 :                : 
                               3058                 :                :     /* Shouldn't be called unless query has setops */
 3221 peter_e@gmx.net          3059                 :           3525 :     topop = castNode(SetOperationStmt, parse->setOperations);
                               3060         [ -  + ]:           3525 :     Assert(topop);
                               3061                 :                : 
                               3062                 :                :     /* Can't optimize away a recursive UNION */
 5518 tgl@sss.pgh.pa.us        3063         [ +  + ]:           3525 :     if (root->hasRecursion)
                               3064                 :           3128 :         return;
                               3065                 :                : 
                               3066                 :                :     /*
                               3067                 :                :      * Recursively check the tree of set operations.  If not all UNION ALL
                               3068                 :                :      * with identical column types, punt.
                               3069                 :                :      */
                               3070         [ +  + ]:           3051 :     if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
                               3071                 :           2654 :         return;
                               3072                 :                : 
                               3073                 :                :     /*
                               3074                 :                :      * Locate the leftmost leaf query in the setops tree.  The upper query's
                               3075                 :                :      * Vars all refer to this RTE (see transformSetOperationStmt).
                               3076                 :                :      */
                               3077                 :            397 :     leftmostjtnode = topop->larg;
                               3078   [ +  -  +  + ]:            605 :     while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
                               3079                 :            208 :         leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
                               3080   [ +  -  -  + ]:            397 :     Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
                               3081                 :            397 :     leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
                               3082                 :            397 :     leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
                               3083         [ -  + ]:            397 :     Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
                               3084                 :                : 
                               3085                 :                :     /*
                               3086                 :                :      * Make a copy of the leftmost RTE and add it to the rtable.  This copy
                               3087                 :                :      * will represent the leftmost leaf query in its capacity as a member of
                               3088                 :                :      * the appendrel.  The original will represent the appendrel as a whole.
                               3089                 :                :      * (We must do things this way because the upper query's Vars have to be
                               3090                 :                :      * seen as referring to the whole appendrel.)
                               3091                 :                :      */
                               3092                 :            397 :     childRTE = copyObject(leftmostRTE);
                               3093                 :            397 :     parse->rtable = lappend(parse->rtable, childRTE);
                               3094                 :            397 :     childRTI = list_length(parse->rtable);
                               3095                 :                : 
                               3096                 :                :     /* Modify the setops tree to reference the child copy */
                               3097                 :            397 :     ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
                               3098                 :                : 
                               3099                 :                :     /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
                               3100                 :            397 :     leftmostRTE->inh = true;
                               3101                 :                : 
                               3102                 :                :     /*
                               3103                 :                :      * Form a RangeTblRef for the appendrel, and insert it into FROM.  The top
                               3104                 :                :      * Query of a setops tree should have had an empty FromClause initially.
                               3105                 :                :      */
                               3106                 :            397 :     rtr = makeNode(RangeTblRef);
                               3107                 :            397 :     rtr->rtindex = leftmostRTI;
                               3108         [ -  + ]:            397 :     Assert(parse->jointree->fromlist == NIL);
                               3109                 :            397 :     parse->jointree->fromlist = list_make1(rtr);
                               3110                 :                : 
                               3111                 :                :     /*
                               3112                 :                :      * Now pretend the query has no setops.  We must do this before trying to
                               3113                 :                :      * do subquery pullup, because of Assert in pull_up_simple_subquery.
                               3114                 :                :      */
                               3115                 :            397 :     parse->setOperations = NULL;
                               3116                 :                : 
                               3117                 :                :     /*
                               3118                 :                :      * Build AppendRelInfo information, and apply pull_up_subqueries to the
                               3119                 :                :      * leaf queries of the UNION ALL.  (We must do that now because they
                               3120                 :                :      * weren't previously referenced by the jointree, and so were missed by
                               3121                 :                :      * the main invocation of pull_up_subqueries.)
                               3122                 :                :      */
                               3123                 :            397 :     pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
                               3124                 :                : }
                               3125                 :                : 
                               3126                 :                : 
                               3127                 :                : /*
                               3128                 :                :  * reduce_outer_joins
                               3129                 :                :  *      Attempt to reduce outer joins to plain inner joins.
                               3130                 :                :  *
                               3131                 :                :  * The idea here is that given a query like
                               3132                 :                :  *      SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
                               3133                 :                :  * we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
                               3134                 :                :  * is strict.  The strict operator will always return NULL, causing the outer
                               3135                 :                :  * WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
                               3136                 :                :  * columns.  Therefore, there's no need for the join to produce null-extended
                               3137                 :                :  * rows in the first place --- which makes it a plain join not an outer join.
                               3138                 :                :  * (This scenario may not be very likely in a query written out by hand, but
                               3139                 :                :  * it's reasonably likely when pushing quals down into complex views.)
                               3140                 :                :  *
                               3141                 :                :  * More generally, an outer join can be reduced in strength if there is a
                               3142                 :                :  * strict qual above it in the qual tree that constrains a Var from the
                               3143                 :                :  * nullable side of the join to be non-null.  (For FULL joins this applies
                               3144                 :                :  * to each side separately.)
                               3145                 :                :  *
                               3146                 :                :  * Another transformation we apply here is to recognize cases like
                               3147                 :                :  *      SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
                               3148                 :                :  * If the join clause is strict for b.y, then only null-extended rows could
                               3149                 :                :  * pass the upper WHERE, and we can conclude that what the query is really
                               3150                 :                :  * specifying is an anti-semijoin.  We change the join type from JOIN_LEFT
                               3151                 :                :  * to JOIN_ANTI.  The IS NULL clause then becomes redundant, and must be
                               3152                 :                :  * removed to prevent bogus selectivity calculations, but we leave it to
                               3153                 :                :  * distribute_qual_to_rels to get rid of such clauses.
                               3154                 :                :  *
                               3155                 :                :  * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
                               3156                 :                :  * JOIN_LEFT.  This saves some code here and in some later planner routines;
                               3157                 :                :  * the main benefit is to reduce the number of jointypes that can appear in
                               3158                 :                :  * SpecialJoinInfo nodes.  Note that we can still generate Paths and Plans
                               3159                 :                :  * that use JOIN_RIGHT (or JOIN_RIGHT_ANTI) by switching the inputs again.
                               3160                 :                :  *
                               3161                 :                :  * To ease recognition of strict qual clauses, we require this routine to be
                               3162                 :                :  * run after expression preprocessing (i.e., qual canonicalization and JOIN
                               3163                 :                :  * alias-var expansion).
                               3164                 :                :  */
                               3165                 :                : void
 7500                          3166                 :          16944 : reduce_outer_joins(PlannerInfo *root)
                               3167                 :                : {
                               3168                 :                :     reduce_outer_joins_pass1_state *state1;
                               3169                 :                :     reduce_outer_joins_pass2_state state2;
                               3170                 :                :     ListCell   *lc;
                               3171                 :                : 
                               3172                 :                :     /*
                               3173                 :                :      * To avoid doing strictness checks on more quals than necessary, we want
                               3174                 :                :      * to stop descending the jointree as soon as there are no outer joins
                               3175                 :                :      * below our current point.  This consideration forces a two-pass process.
                               3176                 :                :      * The first pass gathers information about which base rels appear below
                               3177                 :                :      * each side of each join clause, and about whether there are outer
                               3178                 :                :      * join(s) below each side of each join clause. The second pass examines
                               3179                 :                :      * qual clauses and changes join types as it descends the tree.
                               3180                 :                :      */
 1052                          3181                 :          16944 :     state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
                               3182                 :                : 
                               3183                 :                :     /* planner.c shouldn't have called me if no outer joins */
                               3184   [ +  -  -  + ]:          16944 :     if (state1 == NULL || !state1->contains_outer)
 8181 tgl@sss.pgh.pa.us        3185         [ #  # ]:UBC           0 :         elog(ERROR, "so where are the outer joins?");
                               3186                 :                : 
 1052 tgl@sss.pgh.pa.us        3187                 :CBC       16944 :     state2.inner_reduced = NULL;
                               3188                 :          16944 :     state2.partial_reduced = NIL;
                               3189                 :                : 
 7500                          3190                 :          16944 :     reduce_outer_joins_pass2((Node *) root->parse->jointree,
                               3191                 :                :                              state1, &state2,
                               3192                 :                :                              root, NULL, NIL);
                               3193                 :                : 
                               3194                 :                :     /*
                               3195                 :                :      * If we successfully reduced the strength of any outer joins, we must
                               3196                 :                :      * remove references to those joins as nulling rels.  This is handled as
                               3197                 :                :      * an additional pass, for simplicity and because we can handle all
                               3198                 :                :      * fully-reduced joins in a single pass over the parse tree.
                               3199                 :                :      */
 1052                          3200         [ +  + ]:          16944 :     if (!bms_is_empty(state2.inner_reduced))
                               3201                 :                :     {
                               3202                 :            968 :         root->parse = (Query *)
                               3203                 :            968 :             remove_nulling_relids((Node *) root->parse,
                               3204                 :            968 :                                   state2.inner_reduced,
                               3205                 :                :                                   NULL);
                               3206                 :                :         /* There could be references in the append_rel_list, too */
                               3207                 :            968 :         root->append_rel_list = (List *)
                               3208                 :            968 :             remove_nulling_relids((Node *) root->append_rel_list,
                               3209                 :            968 :                                   state2.inner_reduced,
                               3210                 :                :                                   NULL);
                               3211                 :                :     }
                               3212                 :                : 
                               3213                 :                :     /*
                               3214                 :                :      * Partially-reduced full joins have to be done one at a time, since
                               3215                 :                :      * they'll each need a different setting of except_relids.
                               3216                 :                :      */
                               3217   [ +  +  +  +  :          16969 :     foreach(lc, state2.partial_reduced)
                                              +  + ]
                               3218                 :                :     {
                               3219                 :             25 :         reduce_outer_joins_partial_state *statep = lfirst(lc);
                               3220                 :             25 :         Relids      full_join_relids = bms_make_singleton(statep->full_join_rti);
                               3221                 :                : 
                               3222                 :             25 :         root->parse = (Query *)
                               3223                 :             25 :             remove_nulling_relids((Node *) root->parse,
                               3224                 :                :                                   full_join_relids,
                               3225                 :             25 :                                   statep->unreduced_side);
                               3226                 :             25 :         root->append_rel_list = (List *)
                               3227                 :             25 :             remove_nulling_relids((Node *) root->append_rel_list,
                               3228                 :                :                                   full_join_relids,
                               3229                 :             25 :                                   statep->unreduced_side);
                               3230                 :                :     }
 8347                          3231                 :          16944 : }
                               3232                 :                : 
                               3233                 :                : /*
                               3234                 :                :  * reduce_outer_joins_pass1 - phase 1 data collection
                               3235                 :                :  *
                               3236                 :                :  * Returns a state node describing the given jointree node.
                               3237                 :                :  */
                               3238                 :                : static reduce_outer_joins_pass1_state *
                               3239                 :          96551 : reduce_outer_joins_pass1(Node *jtnode)
                               3240                 :                : {
                               3241                 :                :     reduce_outer_joins_pass1_state *result;
                               3242                 :                : 
    7 michael@paquier.xyz      3243                 :GNC       96551 :     result = palloc_object(reduce_outer_joins_pass1_state);
 8347 tgl@sss.pgh.pa.us        3244                 :CBC       96551 :     result->relids = NULL;
                               3245                 :          96551 :     result->contains_outer = false;
                               3246                 :          96551 :     result->sub_states = NIL;
                               3247                 :                : 
                               3248         [ -  + ]:          96551 :     if (jtnode == NULL)
 8347 tgl@sss.pgh.pa.us        3249                 :UBC           0 :         return result;
 8347 tgl@sss.pgh.pa.us        3250         [ +  + ]:CBC       96551 :     if (IsA(jtnode, RangeTblRef))
                               3251                 :                :     {
                               3252                 :          48159 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               3253                 :                : 
                               3254                 :          48159 :         result->relids = bms_make_singleton(varno);
                               3255                 :                :     }
                               3256         [ +  + ]:          48392 :     else if (IsA(jtnode, FromExpr))
                               3257                 :                :     {
                               3258                 :          18610 :         FromExpr   *f = (FromExpr *) jtnode;
                               3259                 :                :         ListCell   *l;
                               3260                 :                : 
                               3261   [ +  -  +  +  :          38653 :         foreach(l, f->fromlist)
                                              +  + ]
                               3262                 :                :         {
                               3263                 :                :             reduce_outer_joins_pass1_state *sub_state;
                               3264                 :                : 
                               3265                 :          20043 :             sub_state = reduce_outer_joins_pass1(lfirst(l));
                               3266                 :          40086 :             result->relids = bms_add_members(result->relids,
                               3267                 :          20043 :                                              sub_state->relids);
                               3268                 :          20043 :             result->contains_outer |= sub_state->contains_outer;
                               3269                 :          20043 :             result->sub_states = lappend(result->sub_states, sub_state);
                               3270                 :                :         }
                               3271                 :                :     }
                               3272         [ +  - ]:          29782 :     else if (IsA(jtnode, JoinExpr))
                               3273                 :                :     {
                               3274                 :          29782 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               3275                 :                :         reduce_outer_joins_pass1_state *sub_state;
                               3276                 :                : 
                               3277                 :                :         /* join's own RT index is not wanted in result->relids */
                               3278         [ +  + ]:          29782 :         if (IS_OUTER_JOIN(j->jointype))
                               3279                 :          24472 :             result->contains_outer = true;
                               3280                 :                : 
                               3281                 :          29782 :         sub_state = reduce_outer_joins_pass1(j->larg);
                               3282                 :          59564 :         result->relids = bms_add_members(result->relids,
                               3283                 :          29782 :                                          sub_state->relids);
                               3284                 :          29782 :         result->contains_outer |= sub_state->contains_outer;
                               3285                 :          29782 :         result->sub_states = lappend(result->sub_states, sub_state);
                               3286                 :                : 
                               3287                 :          29782 :         sub_state = reduce_outer_joins_pass1(j->rarg);
                               3288                 :          59564 :         result->relids = bms_add_members(result->relids,
                               3289                 :          29782 :                                          sub_state->relids);
                               3290                 :          29782 :         result->contains_outer |= sub_state->contains_outer;
                               3291                 :          29782 :         result->sub_states = lappend(result->sub_states, sub_state);
                               3292                 :                :     }
                               3293                 :                :     else
 8181 tgl@sss.pgh.pa.us        3294         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               3295                 :                :              (int) nodeTag(jtnode));
 8347 tgl@sss.pgh.pa.us        3296                 :CBC       96551 :     return result;
                               3297                 :                : }
                               3298                 :                : 
                               3299                 :                : /*
                               3300                 :                :  * reduce_outer_joins_pass2 - phase 2 processing
                               3301                 :                :  *
                               3302                 :                :  *  jtnode: current jointree node
                               3303                 :                :  *  state1: state data collected by phase 1 for this node
                               3304                 :                :  *  state2: where to accumulate info about successfully-reduced joins
                               3305                 :                :  *  root: toplevel planner state
                               3306                 :                :  *  nonnullable_rels: set of base relids forced non-null by upper quals
                               3307                 :                :  *  forced_null_vars: multibitmapset of Vars forced null by upper quals
                               3308                 :                :  *
                               3309                 :                :  * Returns info in state2 about outer joins that were successfully simplified.
                               3310                 :                :  * Joins that were fully reduced to inner joins are all added to
                               3311                 :                :  * state2->inner_reduced.  If a full join is reduced to a left join,
                               3312                 :                :  * it needs its own entry in state2->partial_reduced, since that will
                               3313                 :                :  * require custom processing to remove only the correct nullingrel markers.
                               3314                 :                :  */
                               3315                 :                : static void
                               3316                 :          42464 : reduce_outer_joins_pass2(Node *jtnode,
                               3317                 :                :                          reduce_outer_joins_pass1_state *state1,
                               3318                 :                :                          reduce_outer_joins_pass2_state *state2,
                               3319                 :                :                          PlannerInfo *root,
                               3320                 :                :                          Relids nonnullable_rels,
                               3321                 :                :                          List *forced_null_vars)
                               3322                 :                : {
                               3323                 :                :     /*
                               3324                 :                :      * pass 2 should never descend as far as an empty subnode or base rel,
                               3325                 :                :      * because it's only called on subtrees marked as contains_outer.
                               3326                 :                :      */
                               3327         [ -  + ]:          42464 :     if (jtnode == NULL)
 8181 tgl@sss.pgh.pa.us        3328         [ #  # ]:UBC           0 :         elog(ERROR, "reached empty jointree");
 8347 tgl@sss.pgh.pa.us        3329         [ -  + ]:CBC       42464 :     if (IsA(jtnode, RangeTblRef))
 8181 tgl@sss.pgh.pa.us        3330         [ #  # ]:UBC           0 :         elog(ERROR, "reached base rel");
 8347 tgl@sss.pgh.pa.us        3331         [ +  + ]:CBC       42464 :     else if (IsA(jtnode, FromExpr))
                               3332                 :                :     {
                               3333                 :          17682 :         FromExpr   *f = (FromExpr *) jtnode;
                               3334                 :                :         ListCell   *l;
                               3335                 :                :         ListCell   *s;
                               3336                 :                :         Relids      pass_nonnullable_rels;
                               3337                 :                :         List       *pass_forced_null_vars;
                               3338                 :                : 
                               3339                 :                :         /* Scan quals to see if we can add any constraints */
 6334                          3340                 :          17682 :         pass_nonnullable_rels = find_nonnullable_rels(f->quals);
                               3341                 :          17682 :         pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
                               3342                 :                :                                                 nonnullable_rels);
                               3343                 :          17682 :         pass_forced_null_vars = find_forced_null_vars(f->quals);
 1127                          3344                 :          17682 :         pass_forced_null_vars = mbms_add_members(pass_forced_null_vars,
                               3345                 :                :                                                  forced_null_vars);
                               3346                 :                :         /* And recurse --- but only into interesting subtrees */
 1052                          3347         [ -  + ]:          17682 :         Assert(list_length(f->fromlist) == list_length(state1->sub_states));
                               3348   [ +  -  +  +  :          36716 :         forboth(l, f->fromlist, s, state1->sub_states)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               3349                 :                :         {
                               3350                 :          19034 :             reduce_outer_joins_pass1_state *sub_state = lfirst(s);
                               3351                 :                : 
 8347                          3352         [ +  + ]:          19034 :             if (sub_state->contains_outer)
 1052                          3353                 :          17697 :                 reduce_outer_joins_pass2(lfirst(l), sub_state,
                               3354                 :                :                                          state2, root,
                               3355                 :                :                                          pass_nonnullable_rels,
                               3356                 :                :                                          pass_forced_null_vars);
                               3357                 :                :         }
 6334                          3358                 :          17682 :         bms_free(pass_nonnullable_rels);
                               3359                 :                :         /* can't so easily clean up var lists, unfortunately */
                               3360                 :                :     }
 8347                          3361         [ +  - ]:          24782 :     else if (IsA(jtnode, JoinExpr))
                               3362                 :                :     {
                               3363                 :          24782 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               3364                 :          24782 :         int         rtindex = j->rtindex;
                               3365                 :          24782 :         JoinType    jointype = j->jointype;
 1052                          3366                 :          24782 :         reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states);
                               3367                 :          24782 :         reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states);
                               3368                 :                : 
                               3369                 :                :         /* Can we simplify this join? */
 8347                          3370   [ +  +  +  +  :          24782 :         switch (jointype)
                                              +  - ]
                               3371                 :                :         {
 6334                          3372                 :            279 :             case JOIN_INNER:
                               3373                 :            279 :                 break;
 8347                          3374                 :          23102 :             case JOIN_LEFT:
                               3375         [ +  + ]:          23102 :                 if (bms_overlap(nonnullable_rels, right_state->relids))
                               3376                 :            997 :                     jointype = JOIN_INNER;
                               3377                 :          23102 :                 break;
                               3378                 :            604 :             case JOIN_RIGHT:
                               3379         [ +  + ]:            604 :                 if (bms_overlap(nonnullable_rels, left_state->relids))
                               3380                 :             40 :                     jointype = JOIN_INNER;
                               3381                 :            604 :                 break;
                               3382                 :            548 :             case JOIN_FULL:
                               3383         [ +  + ]:            548 :                 if (bms_overlap(nonnullable_rels, left_state->relids))
                               3384                 :                :                 {
                               3385         [ +  + ]:             12 :                     if (bms_overlap(nonnullable_rels, right_state->relids))
                               3386                 :              6 :                         jointype = JOIN_INNER;
                               3387                 :                :                     else
                               3388                 :                :                     {
                               3389                 :              6 :                         jointype = JOIN_LEFT;
                               3390                 :                :                         /* Also report partial reduction in state2 */
 1052                          3391                 :              6 :                         report_reduced_full_join(state2, rtindex,
                               3392                 :                :                                                  right_state->relids);
                               3393                 :                :                     }
                               3394                 :                :                 }
                               3395                 :                :                 else
                               3396                 :                :                 {
 8347                          3397         [ +  + ]:            536 :                     if (bms_overlap(nonnullable_rels, right_state->relids))
                               3398                 :                :                     {
                               3399                 :             19 :                         jointype = JOIN_RIGHT;
                               3400                 :                :                         /* Also report partial reduction in state2 */
 1052                          3401                 :             19 :                         report_reduced_full_join(state2, rtindex,
                               3402                 :                :                                                  left_state->relids);
                               3403                 :                :                     }
                               3404                 :                :                 }
 8347                          3405                 :            548 :                 break;
 6139                          3406                 :            249 :             case JOIN_SEMI:
                               3407                 :                :             case JOIN_ANTI:
                               3408                 :                : 
                               3409                 :                :                 /*
                               3410                 :                :                  * These could only have been introduced by pull_up_sublinks,
                               3411                 :                :                  * so there's no way that upper quals could refer to their
                               3412                 :                :                  * righthand sides, and no point in checking.  We don't expect
                               3413                 :                :                  * to see JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI yet.
                               3414                 :                :                  */
                               3415                 :            249 :                 break;
 8347 tgl@sss.pgh.pa.us        3416                 :UBC           0 :             default:
 6334                          3417         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                               3418                 :                :                      (int) jointype);
                               3419                 :                :                 break;
                               3420                 :                :         }
                               3421                 :                : 
                               3422                 :                :         /*
                               3423                 :                :          * Convert JOIN_RIGHT to JOIN_LEFT.  Note that in the case where we
                               3424                 :                :          * reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
                               3425                 :                :          * longer matches the internal ordering of any CoalesceExpr's built to
                               3426                 :                :          * represent merged join variables.  We don't care about that at
                               3427                 :                :          * present, but be wary of it ...
                               3428                 :                :          */
 6334 tgl@sss.pgh.pa.us        3429         [ +  + ]:CBC       24782 :         if (jointype == JOIN_RIGHT)
                               3430                 :                :         {
                               3431                 :                :             Node       *tmparg;
                               3432                 :                : 
                               3433                 :            583 :             tmparg = j->larg;
                               3434                 :            583 :             j->larg = j->rarg;
                               3435                 :            583 :             j->rarg = tmparg;
                               3436                 :            583 :             jointype = JOIN_LEFT;
 1052                          3437                 :            583 :             right_state = linitial(state1->sub_states);
                               3438                 :            583 :             left_state = lsecond(state1->sub_states);
                               3439                 :                :         }
                               3440                 :                : 
                               3441                 :                :         /*
                               3442                 :                :          * See if we can reduce JOIN_LEFT to JOIN_ANTI.  This is the case if
                               3443                 :                :          * the join's own quals are strict for any var that was forced null by
                               3444                 :                :          * higher qual levels.  NOTE: there are other ways that we could
                               3445                 :                :          * detect an anti-join, in particular if we were to check whether Vars
                               3446                 :                :          * coming from the RHS must be non-null because of table constraints.
                               3447                 :                :          * That seems complicated and expensive though (in particular, one
                               3448                 :                :          * would have to be wary of lower outer joins). For the moment this
                               3449                 :                :          * seems sufficient.
                               3450                 :                :          */
 6334                          3451         [ +  + ]:          24782 :         if (jointype == JOIN_LEFT)
                               3452                 :                :         {
                               3453                 :                :             List       *nonnullable_vars;
                               3454                 :                :             Bitmapset  *overlap;
                               3455                 :                : 
                               3456                 :                :             /* Find Vars in j->quals that must be non-null in joined rows */
 1138                          3457                 :          22694 :             nonnullable_vars = find_nonnullable_vars(j->quals);
                               3458                 :                : 
                               3459                 :                :             /*
                               3460                 :                :              * It's not sufficient to check whether nonnullable_vars and
                               3461                 :                :              * forced_null_vars overlap: we need to know if the overlap
                               3462                 :                :              * includes any RHS variables.
                               3463                 :                :              */
 1127                          3464                 :          22694 :             overlap = mbms_overlap_sets(nonnullable_vars, forced_null_vars);
                               3465         [ +  + ]:          22694 :             if (bms_overlap(overlap, right_state->relids))
 6334                          3466                 :            584 :                 jointype = JOIN_ANTI;
                               3467                 :                :         }
                               3468                 :                : 
                               3469                 :                :         /*
                               3470                 :                :          * Apply the jointype change, if any, to both jointree node and RTE.
                               3471                 :                :          * Also, if we changed an RTE to INNER, add its RTI to inner_reduced.
                               3472                 :                :          */
 6139                          3473   [ +  +  +  + ]:          24782 :         if (rtindex && jointype != j->jointype)
                               3474                 :                :         {
 7500                          3475                 :           2216 :             RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
                               3476                 :                : 
 8347                          3477         [ -  + ]:           2216 :             Assert(rte->rtekind == RTE_JOIN);
                               3478         [ -  + ]:           2216 :             Assert(rte->jointype == j->jointype);
 6139                          3479                 :           2216 :             rte->jointype = jointype;
 1052                          3480         [ +  + ]:           2216 :             if (jointype == JOIN_INNER)
                               3481                 :           1043 :                 state2->inner_reduced = bms_add_member(state2->inner_reduced,
                               3482                 :                :                                                        rtindex);
                               3483                 :                :         }
 6139                          3484                 :          24782 :         j->jointype = jointype;
                               3485                 :                : 
                               3486                 :                :         /* Only recurse if there's more to do below here */
 8347                          3487   [ +  +  +  + ]:          24782 :         if (left_state->contains_outer || right_state->contains_outer)
                               3488                 :                :         {
                               3489                 :                :             Relids      local_nonnullable_rels;
                               3490                 :                :             List       *local_forced_null_vars;
                               3491                 :                :             Relids      pass_nonnullable_rels;
                               3492                 :                :             List       *pass_forced_null_vars;
                               3493                 :                : 
                               3494                 :                :             /*
                               3495                 :                :              * If this join is (now) inner, we can add any constraints its
                               3496                 :                :              * quals provide to those we got from above.  But if it is outer,
                               3497                 :                :              * we can pass down the local constraints only into the nullable
                               3498                 :                :              * side, because an outer join never eliminates any rows from its
                               3499                 :                :              * non-nullable side.  Also, there is no point in passing upper
                               3500                 :                :              * constraints into the nullable side, since if there were any
                               3501                 :                :              * we'd have been able to reduce the join.  (In the case of upper
                               3502                 :                :              * forced-null constraints, we *must not* pass them into the
                               3503                 :                :              * nullable side --- they either applied here, or not.) The upshot
                               3504                 :                :              * is that we pass either the local or the upper constraints,
                               3505                 :                :              * never both, to the children of an outer join.
                               3506                 :                :              *
                               3507                 :                :              * Note that a SEMI join works like an inner join here: it's okay
                               3508                 :                :              * to pass down both local and upper constraints.  (There can't be
                               3509                 :                :              * any upper constraints affecting its inner side, but it's not
                               3510                 :                :              * worth having a separate code path to avoid passing them.)
                               3511                 :                :              *
                               3512                 :                :              * At a FULL join we just punt and pass nothing down --- is it
                               3513                 :                :              * possible to be smarter?
                               3514                 :                :              */
 8346                          3515         [ +  + ]:           7789 :             if (jointype != JOIN_FULL)
                               3516                 :                :             {
 6334                          3517                 :           7721 :                 local_nonnullable_rels = find_nonnullable_rels(j->quals);
                               3518                 :           7721 :                 local_forced_null_vars = find_forced_null_vars(j->quals);
 5435                          3519   [ +  +  +  + ]:           7721 :                 if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
                               3520                 :                :                 {
                               3521                 :                :                     /* OK to merge upper and local constraints */
 6334                          3522                 :            508 :                     local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
                               3523                 :                :                                                              nonnullable_rels);
 1127                          3524                 :            508 :                     local_forced_null_vars = mbms_add_members(local_forced_null_vars,
                               3525                 :                :                                                               forced_null_vars);
                               3526                 :                :                 }
                               3527                 :                :             }
                               3528                 :                :             else
                               3529                 :                :             {
                               3530                 :                :                 /* no use in calculating these */
 6334                          3531                 :             68 :                 local_nonnullable_rels = NULL;
                               3532                 :             68 :                 local_forced_null_vars = NIL;
                               3533                 :                :             }
                               3534                 :                : 
 8347                          3535         [ +  + ]:           7789 :             if (left_state->contains_outer)
                               3536                 :                :             {
 5435                          3537   [ +  +  +  + ]:           7418 :                 if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
                               3538                 :                :                 {
                               3539                 :                :                     /* pass union of local and upper constraints */
 6334                          3540                 :            402 :                     pass_nonnullable_rels = local_nonnullable_rels;
                               3541                 :            402 :                     pass_forced_null_vars = local_forced_null_vars;
                               3542                 :                :                 }
 5365 bruce@momjian.us         3543         [ +  + ]:           7016 :                 else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
                               3544                 :                :                 {
                               3545                 :                :                     /* can't pass local constraints to non-nullable side */
 6334 tgl@sss.pgh.pa.us        3546                 :           6962 :                     pass_nonnullable_rels = nonnullable_rels;
                               3547                 :           6962 :                     pass_forced_null_vars = forced_null_vars;
                               3548                 :                :                 }
                               3549                 :                :                 else
                               3550                 :                :                 {
                               3551                 :                :                     /* no constraints pass through JOIN_FULL */
                               3552                 :             54 :                     pass_nonnullable_rels = NULL;
                               3553                 :             54 :                     pass_forced_null_vars = NIL;
                               3554                 :                :                 }
 1052                          3555                 :           7418 :                 reduce_outer_joins_pass2(j->larg, left_state,
                               3556                 :                :                                          state2, root,
                               3557                 :                :                                          pass_nonnullable_rels,
                               3558                 :                :                                          pass_forced_null_vars);
                               3559                 :                :             }
                               3560                 :                : 
 8347                          3561         [ +  + ]:           7789 :             if (right_state->contains_outer)
                               3562                 :                :             {
 3101                          3563         [ +  + ]:            405 :                 if (jointype != JOIN_FULL)  /* ie, INNER/LEFT/SEMI/ANTI */
                               3564                 :                :                 {
                               3565                 :                :                     /* pass appropriate constraints, per comment above */
 6334                          3566                 :            391 :                     pass_nonnullable_rels = local_nonnullable_rels;
                               3567                 :            391 :                     pass_forced_null_vars = local_forced_null_vars;
                               3568                 :                :                 }
                               3569                 :                :                 else
                               3570                 :                :                 {
                               3571                 :                :                     /* no constraints pass through JOIN_FULL */
                               3572                 :             14 :                     pass_nonnullable_rels = NULL;
                               3573                 :             14 :                     pass_forced_null_vars = NIL;
                               3574                 :                :                 }
 1052                          3575                 :            405 :                 reduce_outer_joins_pass2(j->rarg, right_state,
                               3576                 :                :                                          state2, root,
                               3577                 :                :                                          pass_nonnullable_rels,
                               3578                 :                :                                          pass_forced_null_vars);
                               3579                 :                :             }
 6334                          3580                 :           7789 :             bms_free(local_nonnullable_rels);
                               3581                 :                :         }
                               3582                 :                :     }
                               3583                 :                :     else
 8181 tgl@sss.pgh.pa.us        3584         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               3585                 :                :              (int) nodeTag(jtnode));
 8347 tgl@sss.pgh.pa.us        3586                 :CBC       42464 : }
                               3587                 :                : 
                               3588                 :                : /* Helper for reduce_outer_joins_pass2 */
                               3589                 :                : static void
 1052                          3590                 :             25 : report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
                               3591                 :                :                          int rtindex, Relids relids)
                               3592                 :                : {
                               3593                 :                :     reduce_outer_joins_partial_state *statep;
                               3594                 :                : 
    7 michael@paquier.xyz      3595                 :GNC          25 :     statep = palloc_object(reduce_outer_joins_partial_state);
 1052 tgl@sss.pgh.pa.us        3596                 :CBC          25 :     statep->full_join_rti = rtindex;
                               3597                 :             25 :     statep->unreduced_side = relids;
                               3598                 :             25 :     state2->partial_reduced = lappend(state2->partial_reduced, statep);
                               3599                 :             25 : }
                               3600                 :                : 
                               3601                 :                : 
                               3602                 :                : /*
                               3603                 :                :  * remove_useless_result_rtes
                               3604                 :                :  *      Attempt to remove RTE_RESULT RTEs from the join tree.
                               3605                 :                :  *      Also, elide single-child FromExprs where possible.
                               3606                 :                :  *
                               3607                 :                :  * We can remove RTE_RESULT entries from the join tree using the knowledge
                               3608                 :                :  * that RTE_RESULT returns exactly one row and has no output columns.  Hence,
                               3609                 :                :  * if one is inner-joined to anything else, we can delete it.  Optimizations
                               3610                 :                :  * are also possible for some outer-join cases, as detailed below.
                               3611                 :                :  *
                               3612                 :                :  * This pass also replaces single-child FromExprs with their child node
                               3613                 :                :  * where possible.  It's appropriate to do that here and not earlier because
                               3614                 :                :  * RTE_RESULT removal might reduce a multiple-child FromExpr to have only one
                               3615                 :                :  * child.  We can remove such a FromExpr if its quals are empty, or if it's
                               3616                 :                :  * semantically valid to merge the quals into those of the parent node.
                               3617                 :                :  * While removing unnecessary join tree nodes has some micro-efficiency value,
                               3618                 :                :  * the real reason to do this is to eliminate cases where the nullable side of
                               3619                 :                :  * an outer join node is a FromExpr whose single child is another outer join.
                               3620                 :                :  * To correctly determine whether the two outer joins can commute,
                               3621                 :                :  * deconstruct_jointree() must treat any quals of such a FromExpr as being
                               3622                 :                :  * degenerate quals of the upper outer join.  The best way to do that is to
                               3623                 :                :  * make them actually *be* quals of the upper join, by dropping the FromExpr
                               3624                 :                :  * and hoisting the quals up into the upper join's quals.  (Note that there is
                               3625                 :                :  * no hazard when the intermediate FromExpr has multiple children, since then
                               3626                 :                :  * it represents an inner join that cannot commute with the upper outer join.)
                               3627                 :                :  * As long as we have to do that, we might as well elide such FromExprs
                               3628                 :                :  * everywhere.
                               3629                 :                :  *
                               3630                 :                :  * Some of these optimizations depend on recognizing empty (constant-true)
                               3631                 :                :  * quals for FromExprs and JoinExprs.  That makes it useful to apply this
                               3632                 :                :  * optimization pass after expression preprocessing, since that will have
                               3633                 :                :  * eliminated constant-true quals, allowing more cases to be recognized as
                               3634                 :                :  * optimizable.  What's more, the usual reason for an RTE_RESULT to be present
                               3635                 :                :  * is that we pulled up a subquery or VALUES clause, thus very possibly
                               3636                 :                :  * replacing Vars with constants, making it more likely that a qual can be
                               3637                 :                :  * reduced to constant true.  Also, because some optimizations depend on
                               3638                 :                :  * the outer-join type, it's best to have done reduce_outer_joins() first.
                               3639                 :                :  *
                               3640                 :                :  * A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this
                               3641                 :                :  * process: we must remove the RTE_RESULT's relid from the PHV's phrels, but
                               3642                 :                :  * we must not reduce the phrels set to empty.  If that would happen, and
                               3643                 :                :  * the RTE_RESULT is an immediate child of an outer join, we have to give up
                               3644                 :                :  * and not remove the RTE_RESULT: there is noplace else to evaluate the
                               3645                 :                :  * PlaceHolderVar.  (That is, in such cases the RTE_RESULT *does* have output
                               3646                 :                :  * columns.)  But if the RTE_RESULT is an immediate child of an inner join,
                               3647                 :                :  * we can usually change the PlaceHolderVar's phrels so as to evaluate it at
                               3648                 :                :  * the inner join instead.  This is OK because we really only care that PHVs
                               3649                 :                :  * are evaluated above or below the correct outer joins.  We can't, however,
                               3650                 :                :  * postpone the evaluation of a PHV to above where it is used; so there are
                               3651                 :                :  * some checks below on whether output PHVs are laterally referenced in the
                               3652                 :                :  * other join input rel(s).
                               3653                 :                :  *
                               3654                 :                :  * We used to try to do this work as part of pull_up_subqueries() where the
                               3655                 :                :  * potentially-optimizable cases get introduced; but it's way simpler, and
                               3656                 :                :  * more effective, to do it separately.
                               3657                 :                :  */
                               3658                 :                : void
 2515                          3659                 :         115224 : remove_useless_result_rtes(PlannerInfo *root)
                               3660                 :                : {
 1052                          3661                 :         115224 :     Relids      dropped_outer_joins = NULL;
                               3662                 :                :     ListCell   *cell;
                               3663                 :                : 
                               3664                 :                :     /* Top level of jointree must always be a FromExpr */
 2515                          3665         [ -  + ]:         115224 :     Assert(IsA(root->parse->jointree, FromExpr));
                               3666                 :                :     /* Recurse ... */
                               3667                 :         230448 :     root->parse->jointree = (FromExpr *)
 1052                          3668                 :         115224 :         remove_useless_results_recurse(root,
                               3669                 :         115224 :                                        (Node *) root->parse->jointree,
                               3670                 :                :                                        NULL,
                               3671                 :                :                                        &dropped_outer_joins);
                               3672                 :                :     /* We should still have a FromExpr */
 2515                          3673         [ -  + ]:         115224 :     Assert(IsA(root->parse->jointree, FromExpr));
                               3674                 :                : 
                               3675                 :                :     /*
                               3676                 :                :      * If we removed any outer-join nodes from the jointree, run around and
                               3677                 :                :      * remove references to those joins as nulling rels.  (There could be such
                               3678                 :                :      * references in PHVs that we pulled up out of the original subquery that
                               3679                 :                :      * the RESULT rel replaced.  This is kosher on the grounds that we now
                               3680                 :                :      * know that such an outer join wouldn't really have nulled anything.)  We
                               3681                 :                :      * don't do this during the main recursion, for simplicity and because we
                               3682                 :                :      * can handle all such joins in a single pass over the parse tree.
                               3683                 :                :      */
 1052                          3684         [ +  + ]:         115224 :     if (!bms_is_empty(dropped_outer_joins))
                               3685                 :                :     {
                               3686                 :             30 :         root->parse = (Query *)
                               3687                 :             30 :             remove_nulling_relids((Node *) root->parse,
                               3688                 :                :                                   dropped_outer_joins,
                               3689                 :                :                                   NULL);
                               3690                 :                :         /* There could be references in the append_rel_list, too */
                               3691                 :             30 :         root->append_rel_list = (List *)
                               3692                 :             30 :             remove_nulling_relids((Node *) root->append_rel_list,
                               3693                 :                :                                   dropped_outer_joins,
                               3694                 :                :                                   NULL);
                               3695                 :                :     }
                               3696                 :                : 
                               3697                 :                :     /*
                               3698                 :                :      * Remove any PlanRowMark referencing an RTE_RESULT RTE.  We obviously
                               3699                 :                :      * must do that for any RTE_RESULT that we just removed.  But one for a
                               3700                 :                :      * RTE that we did not remove can be dropped anyway: since the RTE has
                               3701                 :                :      * only one possible output row, there is no need for EPQ to mark and
                               3702                 :                :      * restore that row.
                               3703                 :                :      *
                               3704                 :                :      * It's necessary, not optional, to remove the PlanRowMark for a surviving
                               3705                 :                :      * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
                               3706                 :                :      * RTE_RESULT, which the executor has no support for.
                               3707                 :                :      */
 2347                          3708   [ +  +  +  +  :         116213 :     foreach(cell, root->rowMarks)
                                              +  + ]
                               3709                 :                :     {
 2515                          3710                 :            989 :         PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
                               3711                 :                : 
                               3712         [ +  + ]:            989 :         if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
 2347                          3713                 :            420 :             root->rowMarks = foreach_delete_current(root->rowMarks, cell);
                               3714                 :                :     }
 2515                          3715                 :         115224 : }
                               3716                 :                : 
                               3717                 :                : /*
                               3718                 :                :  * remove_useless_results_recurse
                               3719                 :                :  *      Recursive guts of remove_useless_result_rtes.
                               3720                 :                :  *
                               3721                 :                :  * This recursively processes the jointree and returns a modified jointree.
                               3722                 :                :  * In addition, the RT indexes of any removed outer-join nodes are added to
                               3723                 :                :  * *dropped_outer_joins.
                               3724                 :                :  *
                               3725                 :                :  * jtnode is the current jointree node.  If it could be valid to merge
                               3726                 :                :  * its quals into those of the parent node, parent_quals should point to
                               3727                 :                :  * the parent's quals list; otherwise, pass NULL for parent_quals.
                               3728                 :                :  * (Note that in some cases, parent_quals points to the quals of a parent
                               3729                 :                :  * more than one level up in the tree.)
                               3730                 :                :  */
                               3731                 :                : static Node *
 1052                          3732                 :         299018 : remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
                               3733                 :                :                                Node **parent_quals,
                               3734                 :                :                                Relids *dropped_outer_joins)
                               3735                 :                : {
 2515                          3736         [ -  + ]:         299018 :     Assert(jtnode != NULL);
                               3737         [ +  + ]:         299018 :     if (IsA(jtnode, RangeTblRef))
                               3738                 :                :     {
                               3739                 :                :         /* Can't immediately do anything with a RangeTblRef */
                               3740                 :                :     }
                               3741         [ +  + ]:         150369 :     else if (IsA(jtnode, FromExpr))
                               3742                 :                :     {
                               3743                 :         118700 :         FromExpr   *f = (FromExpr *) jtnode;
                               3744                 :         118700 :         Relids      result_relids = NULL;
                               3745                 :                :         ListCell   *cell;
                               3746                 :                : 
                               3747                 :                :         /*
                               3748                 :                :          * We can drop RTE_RESULT rels from the fromlist so long as at least
                               3749                 :                :          * one child remains, since joining to a one-row table changes
                               3750                 :                :          * nothing.  (But we can't drop a RTE_RESULT that computes PHV(s) that
                               3751                 :                :          * are needed by some sibling.  The cleanup transformation below would
                               3752                 :                :          * reassign the PHVs to be computed at the join, which is too late for
                               3753                 :                :          * the sibling's use.)  The easiest way to mechanize this rule is to
                               3754                 :                :          * modify the list in-place.
                               3755                 :                :          */
 2347                          3756   [ +  -  +  +  :         239156 :         foreach(cell, f->fromlist)
                                              +  + ]
                               3757                 :                :         {
 2515                          3758                 :         120456 :             Node       *child = (Node *) lfirst(cell);
                               3759                 :                :             int         varno;
                               3760                 :                : 
                               3761                 :                :             /* Recursively transform child, allowing it to push up quals ... */
 1052                          3762                 :         120456 :             child = remove_useless_results_recurse(root, child,
                               3763                 :                :                                                    &f->quals,
                               3764                 :                :                                                    dropped_outer_joins);
                               3765                 :                :             /* ... and stick it back into the tree */
 2515                          3766                 :         120456 :             lfirst(cell) = child;
                               3767                 :                : 
                               3768                 :                :             /*
                               3769                 :                :              * If it's an RTE_RESULT with at least one sibling, and no sibling
                               3770                 :                :              * references dependent PHVs, we can drop it.  We don't yet know
                               3771                 :                :              * what the inner join's final relid set will be, so postpone
                               3772                 :                :              * cleanup of PHVs etc till after this loop.
                               3773                 :                :              */
                               3774   [ +  +  +  + ]:         123288 :             if (list_length(f->fromlist) > 1 &&
 2195                          3775                 :           2832 :                 (varno = get_result_relid(root, child)) != 0 &&
                               3776         [ +  + ]:            173 :                 !find_dependent_phvs_in_jointree(root, (Node *) f, varno))
                               3777                 :                :             {
 2347                          3778                 :            161 :                 f->fromlist = foreach_delete_current(f->fromlist, cell);
 2515                          3779                 :            161 :                 result_relids = bms_add_member(result_relids, varno);
                               3780                 :                :             }
                               3781                 :                :         }
                               3782                 :                : 
                               3783                 :                :         /*
                               3784                 :                :          * Clean up if we dropped any RTE_RESULT RTEs.  This is a bit
                               3785                 :                :          * inefficient if there's more than one, but it seems better to
                               3786                 :                :          * optimize the support code for the single-relid case.
                               3787                 :                :          */
                               3788         [ +  + ]:         118700 :         if (result_relids)
                               3789                 :                :         {
                               3790                 :            155 :             int         varno = -1;
                               3791                 :                : 
                               3792         [ +  + ]:            316 :             while ((varno = bms_next_member(result_relids, varno)) >= 0)
                               3793                 :            161 :                 remove_result_refs(root, varno, (Node *) f);
                               3794                 :                :         }
                               3795                 :                : 
                               3796                 :                :         /*
                               3797                 :                :          * If the FromExpr now has only one child, see if we can elide it.
                               3798                 :                :          * This is always valid if there are no quals, except at the top of
                               3799                 :                :          * the jointree (since Query.jointree is required to point to a
                               3800                 :                :          * FromExpr).  Otherwise, we can do it if we can push the quals up to
                               3801                 :                :          * the parent node.
                               3802                 :                :          *
                               3803                 :                :          * Note: while it would not be terribly hard to generalize this
                               3804                 :                :          * transformation to merge multi-child FromExprs into their parent
                               3805                 :                :          * FromExpr, that risks making the parent join too expensive to plan.
                               3806                 :                :          * We leave it to later processing to decide heuristically whether
                               3807                 :                :          * that's a good idea.  Pulling up a single child is always OK,
                               3808                 :                :          * however.
                               3809                 :                :          */
 1052                          3810         [ +  + ]:         118700 :         if (list_length(f->fromlist) == 1 &&
                               3811         [ +  + ]:         117728 :             f != root->parse->jointree &&
                               3812   [ +  +  +  + ]:           3362 :             (f->quals == NULL || parent_quals != NULL))
                               3813                 :                :         {
                               3814                 :                :             /*
                               3815                 :                :              * Merge any quals up to parent.  They should be in implicit-AND
                               3816                 :                :              * format by now, so we just need to concatenate lists.  Put the
                               3817                 :                :              * child quals at the front, on the grounds that they should
                               3818                 :                :              * nominally be evaluated earlier.
                               3819                 :                :              */
                               3820         [ +  + ]:           1401 :             if (f->quals != NULL)
                               3821                 :            715 :                 *parent_quals = (Node *)
                               3822                 :            715 :                     list_concat(castNode(List, f->quals),
                               3823                 :            715 :                                 castNode(List, *parent_quals));
 2515                          3824                 :           1401 :             return (Node *) linitial(f->fromlist);
                               3825                 :                :         }
                               3826                 :                :     }
                               3827         [ +  - ]:          31669 :     else if (IsA(jtnode, JoinExpr))
                               3828                 :                :     {
                               3829                 :          31669 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               3830                 :                :         int         varno;
                               3831                 :                : 
                               3832                 :                :         /*
                               3833                 :                :          * First, recurse.  We can absorb pushed-up FromExpr quals from either
                               3834                 :                :          * child into this node if the jointype is INNER, since then this is
                               3835                 :                :          * equivalent to a FromExpr.  When the jointype is LEFT, we can absorb
                               3836                 :                :          * quals from the RHS child into the current node, as they're
                               3837                 :                :          * essentially degenerate quals of the outer join.  Moreover, if we've
                               3838                 :                :          * been passed down a parent_quals pointer then we can allow quals of
                               3839                 :                :          * the LHS child to be absorbed into the parent.  (This is important
                               3840                 :                :          * to ensure we remove single-child FromExprs immediately below
                               3841                 :                :          * commutable left joins.)  For other jointypes, we can't move child
                               3842                 :                :          * quals up, or at least there's no particular reason to.
                               3843                 :                :          */
 1052                          3844                 :          31669 :         j->larg = remove_useless_results_recurse(root, j->larg,
                               3845         [ +  + ]:          31669 :                                                  (j->jointype == JOIN_INNER) ?
                               3846                 :                :                                                  &j->quals :
  911                          3847                 :          25066 :                                                  (j->jointype == JOIN_LEFT) ?
                               3848         [ +  + ]:          25066 :                                                  parent_quals : NULL,
                               3849                 :                :                                                  dropped_outer_joins);
 1052                          3850                 :          31669 :         j->rarg = remove_useless_results_recurse(root, j->rarg,
                               3851         [ +  + ]:          31669 :                                                  (j->jointype == JOIN_INNER ||
                               3852         [ +  + ]:          25066 :                                                   j->jointype == JOIN_LEFT) ?
                               3853                 :                :                                                  &j->quals : NULL,
                               3854                 :                :                                                  dropped_outer_joins);
                               3855                 :                : 
                               3856                 :                :         /* Apply join-type-specific optimization rules */
 2515                          3857   [ +  +  +  +  :          31669 :         switch (j->jointype)
                                                 - ]
                               3858                 :                :         {
                               3859                 :           6603 :             case JOIN_INNER:
                               3860                 :                : 
                               3861                 :                :                 /*
                               3862                 :                :                  * An inner join is equivalent to a FromExpr, so if either
                               3863                 :                :                  * side was simplified to an RTE_RESULT rel, we can replace
                               3864                 :                :                  * the join with a FromExpr with just the other side.
                               3865                 :                :                  * Furthermore, we can elide that FromExpr according to the
                               3866                 :                :                  * same rules as above.
                               3867                 :                :                  *
                               3868                 :                :                  * Just as in the FromExpr case, we can't simplify if the
                               3869                 :                :                  * other input rel references any PHVs that are marked as to
                               3870                 :                :                  * be evaluated at the RTE_RESULT rel, because we can't
                               3871                 :                :                  * postpone their evaluation in that case.  But we only have
                               3872                 :                :                  * to check this in cases where it's syntactically legal for
                               3873                 :                :                  * the other input to have a LATERAL reference to the
                               3874                 :                :                  * RTE_RESULT rel.  Only RHSes of inner and left joins are
                               3875                 :                :                  * allowed to have such refs.
                               3876                 :                :                  */
 2195                          3877         [ +  + ]:           6603 :                 if ((varno = get_result_relid(root, j->larg)) != 0 &&
                               3878         [ +  - ]:             53 :                     !find_dependent_phvs_in_jointree(root, j->rarg, varno))
                               3879                 :                :                 {
 2515                          3880                 :             53 :                     remove_result_refs(root, varno, j->rarg);
 1052                          3881   [ +  +  +  + ]:             53 :                     if (j->quals != NULL && parent_quals == NULL)
 2515                          3882                 :              6 :                         jtnode = (Node *)
                               3883                 :              6 :                             makeFromExpr(list_make1(j->rarg), j->quals);
                               3884                 :                :                     else
                               3885                 :                :                     {
                               3886                 :                :                         /* Merge any quals up to parent */
 1052                          3887         [ +  + ]:             47 :                         if (j->quals != NULL)
                               3888                 :             35 :                             *parent_quals = (Node *)
                               3889                 :             35 :                                 list_concat(castNode(List, j->quals),
                               3890                 :             35 :                                             castNode(List, *parent_quals));
 2515                          3891                 :             47 :                         jtnode = j->rarg;
                               3892                 :                :                     }
                               3893                 :                :                 }
                               3894         [ +  + ]:           6550 :                 else if ((varno = get_result_relid(root, j->rarg)) != 0)
                               3895                 :                :                 {
                               3896                 :            400 :                     remove_result_refs(root, varno, j->larg);
 1052                          3897   [ +  +  +  + ]:            400 :                     if (j->quals != NULL && parent_quals == NULL)
 2515                          3898                 :              6 :                         jtnode = (Node *)
                               3899                 :              6 :                             makeFromExpr(list_make1(j->larg), j->quals);
                               3900                 :                :                     else
                               3901                 :                :                     {
                               3902                 :                :                         /* Merge any quals up to parent */
 1052                          3903         [ +  + ]:            394 :                         if (j->quals != NULL)
                               3904                 :            258 :                             *parent_quals = (Node *)
                               3905                 :            258 :                                 list_concat(castNode(List, j->quals),
                               3906                 :            258 :                                             castNode(List, *parent_quals));
 2515                          3907                 :            394 :                         jtnode = j->larg;
                               3908                 :                :                     }
                               3909                 :                :                 }
                               3910                 :           6603 :                 break;
                               3911                 :          22110 :             case JOIN_LEFT:
                               3912                 :                : 
                               3913                 :                :                 /*
                               3914                 :                :                  * We can simplify this case if the RHS is an RTE_RESULT, with
                               3915                 :                :                  * two different possibilities:
                               3916                 :                :                  *
                               3917                 :                :                  * If the qual is empty (JOIN ON TRUE), then the join can be
                               3918                 :                :                  * strength-reduced to a plain inner join, since each LHS row
                               3919                 :                :                  * necessarily has exactly one join partner.  So we can always
                               3920                 :                :                  * discard the RHS, much as in the JOIN_INNER case above.
                               3921                 :                :                  * (Again, the LHS could not contain a lateral reference to
                               3922                 :                :                  * the RHS.)
                               3923                 :                :                  *
                               3924                 :                :                  * Otherwise, it's still true that each LHS row should be
                               3925                 :                :                  * returned exactly once, and since the RHS returns no columns
                               3926                 :                :                  * (unless there are PHVs that have to be evaluated there), we
                               3927                 :                :                  * don't much care if it's null-extended or not.  So in this
                               3928                 :                :                  * case also, we can just ignore the qual and discard the left
                               3929                 :                :                  * join.
                               3930                 :                :                  */
                               3931         [ +  + ]:          22110 :                 if ((varno = get_result_relid(root, j->rarg)) != 0 &&
                               3932         [ +  + ]:             75 :                     (j->quals == NULL ||
 2195                          3933         [ -  + ]:             45 :                      !find_dependent_phvs(root, varno)))
                               3934                 :                :                 {
 2515                          3935                 :             30 :                     remove_result_refs(root, varno, j->larg);
 1052                          3936                 :             30 :                     *dropped_outer_joins = bms_add_member(*dropped_outer_joins,
                               3937                 :                :                                                           j->rtindex);
 2515                          3938                 :             30 :                     jtnode = j->larg;
                               3939                 :                :                 }
                               3940                 :          22110 :                 break;
                               3941                 :           1637 :             case JOIN_SEMI:
                               3942                 :                : 
                               3943                 :                :                 /*
                               3944                 :                :                  * We may simplify this case if the RHS is an RTE_RESULT; the
                               3945                 :                :                  * join qual becomes effectively just a filter qual for the
                               3946                 :                :                  * LHS, since we should either return the LHS row or not.  The
                               3947                 :                :                  * filter clause must go into a new FromExpr if we can't push
                               3948                 :                :                  * it up to the parent.
                               3949                 :                :                  *
                               3950                 :                :                  * There is a fine point about PHVs that are supposed to be
                               3951                 :                :                  * evaluated at the RHS.  Such PHVs could only appear in the
                               3952                 :                :                  * semijoin's qual, since the rest of the query cannot
                               3953                 :                :                  * reference any outputs of the semijoin's RHS.  Therefore,
                               3954                 :                :                  * they can't actually go to null before being examined, and
                               3955                 :                :                  * it'd be OK to just remove the PHV wrapping.  We don't have
                               3956                 :                :                  * infrastructure for that, but remove_result_refs() will
                               3957                 :                :                  * relabel them as to be evaluated at the LHS, which is fine.
                               3958                 :                :                  *
                               3959                 :                :                  * Also, we don't need to worry about removing traces of the
                               3960                 :                :                  * join's rtindex, since it hasn't got one.
                               3961                 :                :                  */
                               3962         [ +  + ]:           1637 :                 if ((varno = get_result_relid(root, j->rarg)) != 0)
                               3963                 :                :                 {
 1052                          3964         [ -  + ]:             18 :                     Assert(j->rtindex == 0);
 2515                          3965                 :             18 :                     remove_result_refs(root, varno, j->larg);
 1052                          3966   [ +  -  -  + ]:             18 :                     if (j->quals != NULL && parent_quals == NULL)
 2515 tgl@sss.pgh.pa.us        3967                 :UBC           0 :                         jtnode = (Node *)
                               3968                 :              0 :                             makeFromExpr(list_make1(j->larg), j->quals);
                               3969                 :                :                     else
                               3970                 :                :                     {
                               3971                 :                :                         /* Merge any quals up to parent */
 1052 tgl@sss.pgh.pa.us        3972         [ +  - ]:CBC          18 :                         if (j->quals != NULL)
                               3973                 :             18 :                             *parent_quals = (Node *)
                               3974                 :             18 :                                 list_concat(castNode(List, j->quals),
                               3975                 :             18 :                                             castNode(List, *parent_quals));
 2515                          3976                 :             18 :                         jtnode = j->larg;
                               3977                 :                :                     }
                               3978                 :                :                 }
                               3979                 :           1637 :                 break;
                               3980                 :           1319 :             case JOIN_FULL:
                               3981                 :                :             case JOIN_ANTI:
                               3982                 :                :                 /* We have no special smarts for these cases */
                               3983                 :           1319 :                 break;
 2515 tgl@sss.pgh.pa.us        3984                 :UBC           0 :             default:
                               3985                 :                :                 /* Note: JOIN_RIGHT should be gone at this point */
                               3986         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                               3987                 :                :                      (int) j->jointype);
                               3988                 :                :                 break;
                               3989                 :                :         }
                               3990                 :                :     }
                               3991                 :                :     else
                               3992         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               3993                 :                :              (int) nodeTag(jtnode));
 2515 tgl@sss.pgh.pa.us        3994                 :CBC      297617 :     return jtnode;
                               3995                 :                : }
                               3996                 :                : 
                               3997                 :                : /*
                               3998                 :                :  * get_result_relid
                               3999                 :                :  *      If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid;
                               4000                 :                :  *      otherwise return 0.
                               4001                 :                :  */
                               4002                 :                : static int
                               4003                 :          39732 : get_result_relid(PlannerInfo *root, Node *jtnode)
                               4004                 :                : {
                               4005                 :                :     int         varno;
                               4006                 :                : 
                               4007         [ +  + ]:          39732 :     if (!IsA(jtnode, RangeTblRef))
                               4008                 :           3383 :         return 0;
                               4009                 :          36349 :     varno = ((RangeTblRef *) jtnode)->rtindex;
                               4010         [ +  + ]:          36349 :     if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
                               4011                 :          35630 :         return 0;
                               4012                 :            719 :     return varno;
                               4013                 :                : }
                               4014                 :                : 
                               4015                 :                : /*
                               4016                 :                :  * remove_result_refs
                               4017                 :                :  *      Helper routine for dropping an unneeded RTE_RESULT RTE.
                               4018                 :                :  *
                               4019                 :                :  * This doesn't physically remove the RTE from the jointree, because that's
                               4020                 :                :  * more easily handled in remove_useless_results_recurse.  What it does do
                               4021                 :                :  * is the necessary cleanup in the rest of the tree: we must adjust any PHVs
                               4022                 :                :  * that may reference the RTE.  Be sure to call this at a point where the
                               4023                 :                :  * jointree is valid (no disconnected nodes).
                               4024                 :                :  *
                               4025                 :                :  * Note that we don't need to process the append_rel_list, since RTEs
                               4026                 :                :  * referenced directly in the jointree won't be appendrel members.
                               4027                 :                :  *
                               4028                 :                :  * varno is the RTE_RESULT's relid.
                               4029                 :                :  * newjtloc is the jointree location at which any PHVs referencing the
                               4030                 :                :  * RTE_RESULT should be evaluated instead.
                               4031                 :                :  */
                               4032                 :                : static void
                               4033                 :            662 : remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
                               4034                 :                : {
                               4035                 :                :     /* Fix up PlaceHolderVars as needed */
                               4036                 :                :     /* If there are no PHVs anywhere, we can skip this bit */
                               4037         [ +  + ]:            662 :     if (root->glob->lastPHId != 0)
                               4038                 :                :     {
                               4039                 :                :         Relids      subrelids;
                               4040                 :                : 
 1052                          4041                 :            140 :         subrelids = get_relids_in_jointree(newjtloc, true, false);
 2515                          4042         [ -  + ]:            140 :         Assert(!bms_is_empty(subrelids));
                               4043                 :            140 :         substitute_phv_relids((Node *) root->parse, varno, subrelids);
 1091                          4044                 :            140 :         fix_append_rel_relids(root, varno, subrelids);
                               4045                 :                :     }
                               4046                 :                : 
                               4047                 :                :     /*
                               4048                 :                :      * We also need to remove any PlanRowMark referencing the RTE, but we
                               4049                 :                :      * postpone that work until we return to remove_useless_result_rtes.
                               4050                 :                :      */
 2515                          4051                 :            662 : }
                               4052                 :                : 
                               4053                 :                : 
                               4054                 :                : /*
                               4055                 :                :  * find_dependent_phvs - are there any PlaceHolderVars whose relids are
                               4056                 :                :  * exactly the given varno?
                               4057                 :                :  *
                               4058                 :                :  * find_dependent_phvs should be used when we want to see if there are
                               4059                 :                :  * any such PHVs anywhere in the Query.  Another use-case is to see if
                               4060                 :                :  * a subtree of the join tree contains such PHVs; but for that, we have
                               4061                 :                :  * to look not only at the join tree nodes themselves but at the
                               4062                 :                :  * referenced RTEs.  For that, use find_dependent_phvs_in_jointree.
                               4063                 :                :  */
                               4064                 :                : 
                               4065                 :                : typedef struct
                               4066                 :                : {
                               4067                 :                :     Relids      relids;
                               4068                 :                :     int         sublevels_up;
                               4069                 :                : } find_dependent_phvs_context;
                               4070                 :                : 
                               4071                 :                : static bool
                               4072                 :           1200 : find_dependent_phvs_walker(Node *node,
                               4073                 :                :                            find_dependent_phvs_context *context)
                               4074                 :                : {
                               4075         [ +  + ]:           1200 :     if (node == NULL)
                               4076                 :            282 :         return false;
                               4077         [ +  + ]:            918 :     if (IsA(node, PlaceHolderVar))
                               4078                 :                :     {
                               4079                 :             78 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               4080                 :                : 
                               4081   [ +  -  +  + ]:            156 :         if (phv->phlevelsup == context->sublevels_up &&
                               4082                 :             78 :             bms_equal(context->relids, phv->phrels))
                               4083                 :             57 :             return true;
                               4084                 :                :         /* fall through to examine children */
                               4085                 :                :     }
                               4086         [ +  + ]:            861 :     if (IsA(node, Query))
                               4087                 :                :     {
                               4088                 :                :         /* Recurse into subselects */
                               4089                 :                :         bool        result;
                               4090                 :                : 
                               4091                 :             24 :         context->sublevels_up++;
                               4092                 :             24 :         result = query_tree_walker((Query *) node,
                               4093                 :                :                                    find_dependent_phvs_walker,
                               4094                 :                :                                    context, 0);
                               4095                 :             24 :         context->sublevels_up--;
                               4096                 :             24 :         return result;
                               4097                 :                :     }
                               4098                 :                :     /* Shouldn't need to handle most planner auxiliary nodes here */
                               4099         [ -  + ]:            837 :     Assert(!IsA(node, SpecialJoinInfo));
                               4100         [ -  + ]:            837 :     Assert(!IsA(node, PlaceHolderInfo));
                               4101         [ -  + ]:            837 :     Assert(!IsA(node, MinMaxAggInfo));
                               4102                 :                : 
  384 peter@eisentraut.org     4103                 :            837 :     return expression_tree_walker(node, find_dependent_phvs_walker, context);
                               4104                 :                : }
                               4105                 :                : 
                               4106                 :                : static bool
 2195 tgl@sss.pgh.pa.us        4107                 :             45 : find_dependent_phvs(PlannerInfo *root, int varno)
                               4108                 :                : {
                               4109                 :                :     find_dependent_phvs_context context;
                               4110                 :                : 
                               4111                 :                :     /* If there are no PHVs anywhere, we needn't work hard */
                               4112         [ -  + ]:             45 :     if (root->glob->lastPHId == 0)
 2195 tgl@sss.pgh.pa.us        4113                 :UBC           0 :         return false;
                               4114                 :                : 
 2515 tgl@sss.pgh.pa.us        4115                 :CBC          45 :     context.relids = bms_make_singleton(varno);
                               4116                 :             45 :     context.sublevels_up = 0;
                               4117                 :                : 
  384 peter@eisentraut.org     4118         [ +  - ]:             45 :     if (query_tree_walker(root->parse, find_dependent_phvs_walker, &context, 0))
 1052 tgl@sss.pgh.pa.us        4119                 :             45 :         return true;
                               4120                 :                :     /* The append_rel_list could be populated already, so check it too */
 1052 tgl@sss.pgh.pa.us        4121         [ #  # ]:UBC           0 :     if (expression_tree_walker((Node *) root->append_rel_list,
                               4122                 :                :                                find_dependent_phvs_walker,
                               4123                 :                :                                &context))
                               4124                 :              0 :         return true;
                               4125                 :              0 :     return false;
                               4126                 :                : }
                               4127                 :                : 
                               4128                 :                : static bool
 2195 tgl@sss.pgh.pa.us        4129                 :CBC         226 : find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno)
                               4130                 :                : {
                               4131                 :                :     find_dependent_phvs_context context;
                               4132                 :                :     Relids      subrelids;
                               4133                 :                :     int         relid;
                               4134                 :                : 
                               4135                 :                :     /* If there are no PHVs anywhere, we needn't work hard */
                               4136         [ +  + ]:            226 :     if (root->glob->lastPHId == 0)
                               4137                 :            193 :         return false;
                               4138                 :                : 
                               4139                 :             33 :     context.relids = bms_make_singleton(varno);
                               4140                 :             33 :     context.sublevels_up = 0;
                               4141                 :                : 
                               4142                 :                :     /*
                               4143                 :                :      * See if the jointree fragment itself contains references (in join quals)
                               4144                 :                :      */
                               4145         [ -  + ]:             33 :     if (find_dependent_phvs_walker(node, &context))
 2195 tgl@sss.pgh.pa.us        4146                 :UBC           0 :         return true;
                               4147                 :                : 
                               4148                 :                :     /*
                               4149                 :                :      * Otherwise, identify the set of referenced RTEs (we can ignore joins,
                               4150                 :                :      * since they should be flattened already, so their join alias lists no
                               4151                 :                :      * longer matter), and tediously check each RTE.  We can ignore RTEs that
                               4152                 :                :      * are not marked LATERAL, though, since they couldn't possibly contain
                               4153                 :                :      * any cross-references to other RTEs.
                               4154                 :                :      */
 1052 tgl@sss.pgh.pa.us        4155                 :CBC          33 :     subrelids = get_relids_in_jointree(node, false, false);
 2195                          4156                 :             33 :     relid = -1;
                               4157         [ +  + ]:             72 :     while ((relid = bms_next_member(subrelids, relid)) >= 0)
                               4158                 :                :     {
                               4159                 :             51 :         RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
                               4160                 :                : 
                               4161   [ +  +  +  - ]:             63 :         if (rte->lateral &&
  384 peter@eisentraut.org     4162                 :             12 :             range_table_entry_walker(rte, find_dependent_phvs_walker, &context, 0))
 2195 tgl@sss.pgh.pa.us        4163                 :             12 :             return true;
                               4164                 :                :     }
                               4165                 :                : 
                               4166                 :             21 :     return false;
                               4167                 :                : }
                               4168                 :                : 
                               4169                 :                : /*
                               4170                 :                :  * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up
                               4171                 :                :  * a subquery or removing an RTE_RESULT jointree item
                               4172                 :                :  *
                               4173                 :                :  * Find any PlaceHolderVar nodes in the given tree that reference the
                               4174                 :                :  * pulled-up relid, and change them to reference the replacement relid(s).
                               4175                 :                :  *
                               4176                 :                :  * NOTE: although this has the form of a walker, we cheat and modify the
                               4177                 :                :  * nodes in-place.  This should be OK since the tree was copied by
                               4178                 :                :  * pullup_replace_vars earlier.  Avoid scribbling on the original values of
                               4179                 :                :  * the bitmapsets, though, because expression_tree_mutator doesn't copy those.
                               4180                 :                :  */
                               4181                 :                : 
                               4182                 :                : typedef struct
                               4183                 :                : {
                               4184                 :                :     int         varno;
                               4185                 :                :     int         sublevels_up;
                               4186                 :                :     Relids      subrelids;
                               4187                 :                : } substitute_phv_relids_context;
                               4188                 :                : 
                               4189                 :                : static bool
 2515                          4190                 :         136347 : substitute_phv_relids_walker(Node *node,
                               4191                 :                :                              substitute_phv_relids_context *context)
                               4192                 :                : {
 6334                          4193         [ +  + ]:         136347 :     if (node == NULL)
                               4194                 :          51759 :         return false;
 6266                          4195         [ +  + ]:          84588 :     if (IsA(node, PlaceHolderVar))
                               4196                 :                :     {
                               4197                 :           3846 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               4198                 :                : 
 5016                          4199   [ +  +  +  + ]:           7676 :         if (phv->phlevelsup == context->sublevels_up &&
                               4200                 :           3830 :             bms_is_member(context->varno, phv->phrels))
                               4201                 :                :         {
 6266                          4202                 :           5492 :             phv->phrels = bms_union(phv->phrels,
                               4203                 :           2746 :                                     context->subrelids);
                               4204                 :           2746 :             phv->phrels = bms_del_member(phv->phrels,
                               4205                 :                :                                          context->varno);
                               4206                 :                :             /* Assert we haven't broken the PHV */
 2515                          4207         [ -  + ]:           2746 :             Assert(!bms_is_empty(phv->phrels));
                               4208                 :                :         }
                               4209                 :                :         /* fall through to examine children */
                               4210                 :                :     }
 5016                          4211         [ +  + ]:          84588 :     if (IsA(node, Query))
                               4212                 :                :     {
                               4213                 :                :         /* Recurse into subselects */
                               4214                 :                :         bool        result;
                               4215                 :                : 
                               4216                 :           2234 :         context->sublevels_up++;
                               4217                 :           2234 :         result = query_tree_walker((Query *) node,
                               4218                 :                :                                    substitute_phv_relids_walker,
                               4219                 :                :                                    context, 0);
                               4220                 :           2234 :         context->sublevels_up--;
                               4221                 :           2234 :         return result;
                               4222                 :                :     }
                               4223                 :                :     /* Shouldn't need to handle planner auxiliary nodes here */
 6265                          4224         [ -  + ]:          82354 :     Assert(!IsA(node, SpecialJoinInfo));
                               4225         [ -  + ]:          82354 :     Assert(!IsA(node, AppendRelInfo));
                               4226         [ -  + ]:          82354 :     Assert(!IsA(node, PlaceHolderInfo));
 5522                          4227         [ -  + ]:          82354 :     Assert(!IsA(node, MinMaxAggInfo));
                               4228                 :                : 
  384 peter@eisentraut.org     4229                 :          82354 :     return expression_tree_walker(node, substitute_phv_relids_walker, context);
                               4230                 :                : }
                               4231                 :                : 
                               4232                 :                : static void
 2515 tgl@sss.pgh.pa.us        4233                 :           1218 : substitute_phv_relids(Node *node, int varno, Relids subrelids)
                               4234                 :                : {
                               4235                 :                :     substitute_phv_relids_context context;
                               4236                 :                : 
 6334                          4237                 :           1218 :     context.varno = varno;
 5016                          4238                 :           1218 :     context.sublevels_up = 0;
 6334                          4239                 :           1218 :     context.subrelids = subrelids;
                               4240                 :                : 
                               4241                 :                :     /*
                               4242                 :                :      * Must be prepared to start with a Query or a bare expression tree.
                               4243                 :                :      */
                               4244                 :           1218 :     query_or_expression_tree_walker(node,
                               4245                 :                :                                     substitute_phv_relids_walker,
                               4246                 :                :                                     &context,
                               4247                 :                :                                     0);
 8367                          4248                 :           1218 : }
                               4249                 :                : 
                               4250                 :                : /*
                               4251                 :                :  * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
                               4252                 :                :  *
                               4253                 :                :  * When we pull up a subquery, any AppendRelInfo references to the subquery's
                               4254                 :                :  * RT index have to be replaced by the substituted relid (and there had better
                               4255                 :                :  * be only one).  We also need to apply substitute_phv_relids to their
                               4256                 :                :  * translated_vars lists, since those might contain PlaceHolderVars.
                               4257                 :                :  *
                               4258                 :                :  * We assume we may modify the AppendRelInfo nodes in-place.
                               4259                 :                :  */
                               4260                 :                : static void
 1091                          4261                 :           4300 : fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids)
                               4262                 :                : {
                               4263                 :                :     ListCell   *l;
 7257                          4264                 :           4300 :     int         subvarno = -1;
                               4265                 :                : 
                               4266                 :                :     /*
                               4267                 :                :      * We only want to extract the member relid once, but we mustn't fail
                               4268                 :                :      * immediately if there are multiple members; it could be that none of the
                               4269                 :                :      * AppendRelInfo nodes refer to it.  So compute it on first use. Note that
                               4270                 :                :      * bms_singleton_member will complain if set is not singleton.
                               4271                 :                :      */
 1091                          4272   [ +  +  +  +  :          10194 :     foreach(l, root->append_rel_list)
                                              +  + ]
                               4273                 :                :     {
 7257                          4274                 :           5894 :         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
                               4275                 :                : 
                               4276                 :                :         /* The parent_relid shouldn't ever be a pullup target */
                               4277         [ -  + ]:           5894 :         Assert(appinfo->parent_relid != varno);
                               4278                 :                : 
                               4279         [ +  + ]:           5894 :         if (appinfo->child_relid == varno)
                               4280                 :                :         {
                               4281         [ +  - ]:           3190 :             if (subvarno < 0)
                               4282                 :           3190 :                 subvarno = bms_singleton_member(subrelids);
                               4283                 :           3190 :             appinfo->child_relid = subvarno;
                               4284                 :                :         }
                               4285                 :                : 
                               4286                 :                :         /* Also fix up any PHVs in its translated vars */
 1091                          4287         [ +  + ]:           5894 :         if (root->glob->lastPHId != 0)
                               4288                 :             81 :             substitute_phv_relids((Node *) appinfo->translated_vars,
                               4289                 :                :                                   varno, subrelids);
                               4290                 :                :     }
 7257                          4291                 :           4300 : }
                               4292                 :                : 
                               4293                 :                : /*
                               4294                 :                :  * get_relids_in_jointree: get set of RT indexes present in a jointree
                               4295                 :                :  *
                               4296                 :                :  * Base-relation relids are always included in the result.
                               4297                 :                :  * If include_outer_joins is true, outer-join RT indexes are included.
                               4298                 :                :  * If include_inner_joins is true, inner-join RT indexes are included.
                               4299                 :                :  *
                               4300                 :                :  * Note that for most purposes in the planner, outer joins are included
                               4301                 :                :  * in standard relid sets.  Setting include_inner_joins true is only
                               4302                 :                :  * appropriate for special purposes during subquery flattening.
                               4303                 :                :  */
                               4304                 :                : Relids
 1052                          4305                 :          53283 : get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
                               4306                 :                :                        bool include_inner_joins)
                               4307                 :                : {
 8348                          4308                 :          53283 :     Relids      result = NULL;
                               4309                 :                : 
 8367                          4310         [ -  + ]:          53283 :     if (jtnode == NULL)
 8367 tgl@sss.pgh.pa.us        4311                 :UBC           0 :         return result;
 8367 tgl@sss.pgh.pa.us        4312         [ +  + ]:CBC       53283 :     if (IsA(jtnode, RangeTblRef))
                               4313                 :                :     {
                               4314                 :          26846 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               4315                 :                : 
 8348                          4316                 :          26846 :         result = bms_make_singleton(varno);
                               4317                 :                :     }
 8367                          4318         [ +  + ]:          26437 :     else if (IsA(jtnode, FromExpr))
                               4319                 :                :     {
                               4320                 :          23248 :         FromExpr   *f = (FromExpr *) jtnode;
                               4321                 :                :         ListCell   *l;
                               4322                 :                : 
                               4323   [ +  -  +  +  :          47132 :         foreach(l, f->fromlist)
                                              +  + ]
                               4324                 :                :         {
 8348                          4325                 :          23884 :             result = bms_join(result,
 6331                          4326                 :          23884 :                               get_relids_in_jointree(lfirst(l),
                               4327                 :                :                                                      include_outer_joins,
                               4328                 :                :                                                      include_inner_joins));
                               4329                 :                :         }
                               4330                 :                :     }
 8367                          4331         [ +  - ]:           3189 :     else if (IsA(jtnode, JoinExpr))
                               4332                 :                :     {
                               4333                 :           3189 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4334                 :                : 
 1052                          4335                 :           3189 :         result = get_relids_in_jointree(j->larg,
                               4336                 :                :                                         include_outer_joins,
                               4337                 :                :                                         include_inner_joins);
 6331                          4338                 :           3189 :         result = bms_join(result,
                               4339                 :                :                           get_relids_in_jointree(j->rarg,
                               4340                 :                :                                                  include_outer_joins,
                               4341                 :                :                                                  include_inner_joins));
 1052                          4342         [ +  + ]:           3189 :         if (j->rtindex)
                               4343                 :                :         {
                               4344         [ +  + ]:           3026 :             if (j->jointype == JOIN_INNER)
                               4345                 :                :             {
                               4346         [ +  + ]:           1355 :                 if (include_inner_joins)
                               4347                 :            537 :                     result = bms_add_member(result, j->rtindex);
                               4348                 :                :             }
                               4349                 :                :             else
                               4350                 :                :             {
                               4351         [ +  + ]:           1671 :                 if (include_outer_joins)
                               4352                 :           1089 :                     result = bms_add_member(result, j->rtindex);
                               4353                 :                :             }
                               4354                 :                :         }
                               4355                 :                :     }
                               4356                 :                :     else
 8181 tgl@sss.pgh.pa.us        4357         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               4358                 :                :              (int) nodeTag(jtnode));
 8367 tgl@sss.pgh.pa.us        4359                 :CBC       53283 :     return result;
                               4360                 :                : }
                               4361                 :                : 
                               4362                 :                : /*
                               4363                 :                :  * get_relids_for_join: get set of base+OJ RT indexes making up a join
                               4364                 :                :  */
                               4365                 :                : Relids
 2514                          4366                 :            179 : get_relids_for_join(Query *query, int joinrelid)
                               4367                 :                : {
                               4368                 :                :     Node       *jtnode;
                               4369                 :                : 
                               4370                 :            179 :     jtnode = find_jointree_node_for_rel((Node *) query->jointree,
                               4371                 :                :                                         joinrelid);
 8367                          4372         [ -  + ]:            179 :     if (!jtnode)
 8181 tgl@sss.pgh.pa.us        4373         [ #  # ]:UBC           0 :         elog(ERROR, "could not find join node %d", joinrelid);
 1052 tgl@sss.pgh.pa.us        4374                 :CBC         179 :     return get_relids_in_jointree(jtnode, true, false);
                               4375                 :                : }
                               4376                 :                : 
                               4377                 :                : /*
                               4378                 :                :  * find_jointree_node_for_rel: locate jointree node for a base or join RT index
                               4379                 :                :  *
                               4380                 :                :  * Returns NULL if not found
                               4381                 :                :  */
                               4382                 :                : static Node *
 8367                          4383                 :            865 : find_jointree_node_for_rel(Node *jtnode, int relid)
                               4384                 :                : {
                               4385         [ -  + ]:            865 :     if (jtnode == NULL)
 8367 tgl@sss.pgh.pa.us        4386                 :UBC           0 :         return NULL;
 8367 tgl@sss.pgh.pa.us        4387         [ +  + ]:CBC         865 :     if (IsA(jtnode, RangeTblRef))
                               4388                 :                :     {
                               4389                 :            227 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               4390                 :                : 
                               4391         [ -  + ]:            227 :         if (relid == varno)
 8367 tgl@sss.pgh.pa.us        4392                 :UBC           0 :             return jtnode;
                               4393                 :                :     }
 8367 tgl@sss.pgh.pa.us        4394         [ +  + ]:CBC         638 :     else if (IsA(jtnode, FromExpr))
                               4395                 :                :     {
                               4396                 :            184 :         FromExpr   *f = (FromExpr *) jtnode;
                               4397                 :                :         ListCell   *l;
                               4398                 :                : 
                               4399   [ +  -  +  -  :            193 :         foreach(l, f->fromlist)
                                              +  - ]
                               4400                 :                :         {
                               4401                 :            193 :             jtnode = find_jointree_node_for_rel(lfirst(l), relid);
                               4402         [ +  + ]:            193 :             if (jtnode)
                               4403                 :            184 :                 return jtnode;
                               4404                 :                :         }
                               4405                 :                :     }
                               4406         [ +  - ]:            454 :     else if (IsA(jtnode, JoinExpr))
                               4407                 :                :     {
                               4408                 :            454 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4409                 :                : 
                               4410         [ +  + ]:            454 :         if (relid == j->rtindex)
                               4411                 :            179 :             return jtnode;
                               4412                 :            275 :         jtnode = find_jointree_node_for_rel(j->larg, relid);
                               4413         [ +  + ]:            275 :         if (jtnode)
                               4414                 :             57 :             return jtnode;
                               4415                 :            218 :         jtnode = find_jointree_node_for_rel(j->rarg, relid);
                               4416         [ +  - ]:            218 :         if (jtnode)
                               4417                 :            218 :             return jtnode;
                               4418                 :                :     }
                               4419                 :                :     else
 8181 tgl@sss.pgh.pa.us        4420         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                               4421                 :                :              (int) nodeTag(jtnode));
 8367 tgl@sss.pgh.pa.us        4422                 :CBC         227 :     return NULL;
                               4423                 :                : }
                               4424                 :                : 
                               4425                 :                : /*
                               4426                 :                :  * get_nullingrels: collect info about which outer joins null which relations
                               4427                 :                :  *
                               4428                 :                :  * The result struct contains, for each leaf relation used in the query,
                               4429                 :                :  * the set of relids of outer joins that potentially null that rel.
                               4430                 :                :  */
                               4431                 :                : static nullingrel_info *
  382                          4432                 :            583 : get_nullingrels(Query *parse)
                               4433                 :                : {
                               4434                 :            583 :     nullingrel_info *result = palloc_object(nullingrel_info);
                               4435                 :                : 
                               4436                 :            583 :     result->rtlength = list_length(parse->rtable);
                               4437                 :            583 :     result->nullingrels = palloc0_array(Relids, result->rtlength + 1);
                               4438                 :            583 :     get_nullingrels_recurse((Node *) parse->jointree, NULL, result);
                               4439                 :            583 :     return result;
                               4440                 :                : }
                               4441                 :                : 
                               4442                 :                : /*
                               4443                 :                :  * Recursive guts of get_nullingrels().
                               4444                 :                :  *
                               4445                 :                :  * Note: at any recursion level, the passed-down upper_nullingrels must be
                               4446                 :                :  * treated as a constant, but it can be stored directly into *info
                               4447                 :                :  * if we're at leaf level.  Upper recursion levels do not free their mutated
                               4448                 :                :  * copies of the nullingrels, because those are probably referenced by
                               4449                 :                :  * at least one leaf rel.
                               4450                 :                :  */
                               4451                 :                : static void
                               4452                 :           3096 : get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels,
                               4453                 :                :                         nullingrel_info *info)
                               4454                 :                : {
                               4455         [ -  + ]:           3096 :     if (jtnode == NULL)
  382 tgl@sss.pgh.pa.us        4456                 :UBC           0 :         return;
  382 tgl@sss.pgh.pa.us        4457         [ +  + ]:CBC        3096 :     if (IsA(jtnode, RangeTblRef))
                               4458                 :                :     {
                               4459                 :           1637 :         int         varno = ((RangeTblRef *) jtnode)->rtindex;
                               4460                 :                : 
                               4461   [ +  -  -  + ]:           1637 :         Assert(varno > 0 && varno <= info->rtlength);
                               4462                 :           1637 :         info->nullingrels[varno] = upper_nullingrels;
                               4463                 :                :     }
                               4464         [ +  + ]:           1459 :     else if (IsA(jtnode, FromExpr))
                               4465                 :                :     {
                               4466                 :            625 :         FromExpr   *f = (FromExpr *) jtnode;
                               4467                 :                :         ListCell   *l;
                               4468                 :                : 
                               4469   [ +  -  +  +  :           1470 :         foreach(l, f->fromlist)
                                              +  + ]
                               4470                 :                :         {
                               4471                 :            845 :             get_nullingrels_recurse(lfirst(l), upper_nullingrels, info);
                               4472                 :                :         }
                               4473                 :                :     }
                               4474         [ +  - ]:            834 :     else if (IsA(jtnode, JoinExpr))
                               4475                 :                :     {
                               4476                 :            834 :         JoinExpr   *j = (JoinExpr *) jtnode;
                               4477                 :                :         Relids      local_nullingrels;
                               4478                 :                : 
                               4479   [ +  +  +  -  :            834 :         switch (j->jointype)
                                                 - ]
                               4480                 :                :         {
                               4481                 :            303 :             case JOIN_INNER:
                               4482                 :            303 :                 get_nullingrels_recurse(j->larg, upper_nullingrels, info);
                               4483                 :            303 :                 get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
                               4484                 :            303 :                 break;
                               4485                 :            528 :             case JOIN_LEFT:
                               4486                 :                :             case JOIN_SEMI:
                               4487                 :                :             case JOIN_ANTI:
                               4488                 :            528 :                 local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
                               4489                 :                :                                                    j->rtindex);
                               4490                 :            528 :                 get_nullingrels_recurse(j->larg, upper_nullingrels, info);
                               4491                 :            528 :                 get_nullingrels_recurse(j->rarg, local_nullingrels, info);
                               4492                 :            528 :                 break;
                               4493                 :              3 :             case JOIN_FULL:
                               4494                 :              3 :                 local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
                               4495                 :                :                                                    j->rtindex);
                               4496                 :              3 :                 get_nullingrels_recurse(j->larg, local_nullingrels, info);
                               4497                 :              3 :                 get_nullingrels_recurse(j->rarg, local_nullingrels, info);
                               4498                 :              3 :                 break;
  382 tgl@sss.pgh.pa.us        4499                 :UBC           0 :             case JOIN_RIGHT:
                               4500                 :              0 :                 local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
                               4501                 :                :                                                    j->rtindex);
                               4502                 :              0 :                 get_nullingrels_recurse(j->larg, local_nullingrels, info);
                               4503                 :              0 :                 get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
                               4504                 :              0 :                 break;
                               4505                 :              0 :             default:
                               4506         [ #  # ]:              0 :                 elog(ERROR, "unrecognized join type: %d",
                               4507                 :                :                      (int) j->jointype);
                               4508                 :                :                 break;
                               4509                 :                :         }
                               4510                 :                :     }
                               4511                 :                :     else
                               4512         [ #  # ]:              0 :         elog(ERROR, "unrecognized node type: %d",
                               4513                 :                :              (int) nodeTag(jtnode));
                               4514                 :                : }
        

Generated by: LCOV version 2.4-beta