LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/prep - prepjointree.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DUB DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 94.1 % 1542 1451 91 55 1396 1 25
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 53 53 9 44 1
Baseline: lcov-20261128-baseline Branches: 79.1 % 1172 927 3 242 1 45 881
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 19 19 19
(30,360] days: 92.5 % 227 210 17 55 155
(360..) days: 94.3 % 1296 1222 74 1222
Function coverage date bins:
(30,360] days: 100.0 % 9 9 2 7
(360..) days: 100.0 % 44 44 7 37
Branch coverage date bins:
(7,30] days: 100.0 % 10 10 10
(30,360] days: 84.0 % 175 147 3 25 1 45 101
(360..) days: 78.0 % 987 770 217 770

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

Generated by: LCOV version 2.0-1