LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/prep - prepjointree.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 93.7 % 1472 1379 93 55 1324 1 25
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 49 49 9 40 1
Baseline: lcov-20260827-baseline Branches: 78.2 % 1106 865 3 238 45 820
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 4 4 4
(7,30] days: 100.0 % 47 47 47
(30,360] days: 87.6 % 105 92 13 4 88
(360..) days: 93.9 % 1316 1236 80 1236
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 3 3 3
(360..) days: 100.0 % 44 44 7 37
Branch coverage date bins:
(7,30] days: 97.7 % 44 43 1 43
(30,360] days: 74.6 % 63 47 2 14 2 45
(360..) days: 77.6 % 999 775 224 775

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

Generated by: LCOV version 2.0-1