LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/plan - setrefs.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC EUB ECB DCB
Current: 1a1248818fb8b8b0353c292c632d6a6af77e8209 vs 8e82d6610e7280d7870c0c36ff1c797e3cfb3e09 Lines: 97.1 % 1212 1177 35 16 6 1155 15
Current Date: 2026-10-12 11:56:10 +0200 Functions: 100.0 % 51 51 1 7 43
Baseline: lcov-20261012-baseline Branches: 81.8 % 850 695 1 1 153 6 3 686 1 3
Baseline Date: 2026-10-12 10:36:06 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 28 28 28
(30,360] days: 100.0 % 35 35 6 29
(360..) days: 97.0 % 1149 1114 35 16 1098
Function coverage date bins:
(1,7] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 1 1 1
(360..) days: 100.0 % 48 48 1 7 40
Branch coverage date bins:
(1,7] days: 95.5 % 22 21 1 21
(30,360] days: 94.4 % 18 17 1 3 14
(360..) days: 80.7 % 814 657 1 152 6 651 1 3

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * setrefs.c
                                  4                 :                :  *    Post-processing of a completed plan tree: fix references to subplan
                                  5                 :                :  *    vars, compute regproc values for operators, etc
                                  6                 :                :  *
                                  7                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  8                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  9                 :                :  *
                                 10                 :                :  *
                                 11                 :                :  * IDENTIFICATION
                                 12                 :                :  *    src/backend/optimizer/plan/setrefs.c
                                 13                 :                :  *
                                 14                 :                :  *-------------------------------------------------------------------------
                                 15                 :                :  */
                                 16                 :                : #include "postgres.h"
                                 17                 :                : 
                                 18                 :                : #include "access/transam.h"
                                 19                 :                : #include "catalog/pg_type.h"
                                 20                 :                : #include "nodes/makefuncs.h"
                                 21                 :                : #include "nodes/nodeFuncs.h"
                                 22                 :                : #include "optimizer/optimizer.h"
                                 23                 :                : #include "optimizer/pathnode.h"
                                 24                 :                : #include "optimizer/planmain.h"
                                 25                 :                : #include "optimizer/planner.h"
                                 26                 :                : #include "optimizer/subselect.h"
                                 27                 :                : #include "optimizer/tlist.h"
                                 28                 :                : #include "parser/parse_relation.h"
                                 29                 :                : #include "rewrite/rewriteManip.h"
                                 30                 :                : #include "tcop/utility.h"
                                 31                 :                : #include "utils/syscache.h"
                                 32                 :                : 
                                 33                 :                : 
                                 34                 :                : typedef enum
                                 35                 :                : {
                                 36                 :                :     NRM_EQUAL,                  /* expect exact match of nullingrels */
                                 37                 :                :     NRM_SUPERSET,               /* actual Var may have a superset of input */
                                 38                 :                : } NullingRelsMatch;
                                 39                 :                : 
                                 40                 :                : typedef struct
                                 41                 :                : {
                                 42                 :                :     int         varno;          /* RT index of Var */
                                 43                 :                :     AttrNumber  varattno;       /* attr number of Var */
                                 44                 :                :     AttrNumber  resno;          /* TLE position of Var */
                                 45                 :                :     Bitmapset  *varnullingrels; /* Var's varnullingrels */
                                 46                 :                : } tlist_vinfo;
                                 47                 :                : 
                                 48                 :                : typedef struct
                                 49                 :                : {
                                 50                 :                :     List       *tlist;          /* underlying target list */
                                 51                 :                :     int         num_vars;       /* number of plain Var tlist entries */
                                 52                 :                :     bool        has_ph_vars;    /* are there PlaceHolderVar entries? */
                                 53                 :                :     bool        has_non_vars;   /* are there other entries? */
                                 54                 :                :     tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER];    /* has num_vars entries */
                                 55                 :                : } indexed_tlist;
                                 56                 :                : 
                                 57                 :                : typedef struct
                                 58                 :                : {
                                 59                 :                :     PlannerInfo *root;
                                 60                 :                :     int         rtoffset;
                                 61                 :                :     double      num_exec;
                                 62                 :                : } fix_scan_expr_context;
                                 63                 :                : 
                                 64                 :                : typedef struct
                                 65                 :                : {
                                 66                 :                :     PlannerInfo *root;
                                 67                 :                :     indexed_tlist *outer_itlist;
                                 68                 :                :     indexed_tlist *inner_itlist;
                                 69                 :                :     Index       acceptable_rel;
                                 70                 :                :     int         rtoffset;
                                 71                 :                :     NullingRelsMatch nrm_match;
                                 72                 :                :     double      num_exec;
                                 73                 :                : } fix_join_expr_context;
                                 74                 :                : 
                                 75                 :                : typedef struct
                                 76                 :                : {
                                 77                 :                :     PlannerInfo *root;
                                 78                 :                :     indexed_tlist *subplan_itlist;
                                 79                 :                :     int         newvarno;
                                 80                 :                :     int         rtoffset;
                                 81                 :                :     double      num_exec;
                                 82                 :                : } fix_upper_expr_context;
                                 83                 :                : 
                                 84                 :                : typedef struct
                                 85                 :                : {
                                 86                 :                :     PlannerInfo *root;
                                 87                 :                :     indexed_tlist *subplan_itlist;
                                 88                 :                :     int         newvarno;
                                 89                 :                : } fix_windowagg_cond_context;
                                 90                 :                : 
                                 91                 :                : /* Context info for flatten_rtes_walker() */
                                 92                 :                : typedef struct
                                 93                 :                : {
                                 94                 :                :     PlannerGlobal *glob;
                                 95                 :                :     Query      *query;
                                 96                 :                : } flatten_rtes_walker_context;
                                 97                 :                : 
                                 98                 :                : /*
                                 99                 :                :  * Selecting the best alternative in an AlternativeSubPlan expression requires
                                100                 :                :  * estimating how many times that expression will be evaluated.  For an
                                101                 :                :  * expression in a plan node's targetlist, the plan's estimated number of
                                102                 :                :  * output rows is clearly what to use, but for an expression in a qual it's
                                103                 :                :  * far less clear.  Since AlternativeSubPlans aren't heavily used, we don't
                                104                 :                :  * want to expend a lot of cycles making such estimates.  What we use is twice
                                105                 :                :  * the number of output rows.  That's not entirely unfounded: we know that
                                106                 :                :  * clause_selectivity() would fall back to a default selectivity estimate
                                107                 :                :  * of 0.5 for any SubPlan, so if the qual containing the SubPlan is the last
                                108                 :                :  * to be applied (which it likely would be, thanks to order_qual_clauses()),
                                109                 :                :  * this matches what we could have estimated in a far more laborious fashion.
                                110                 :                :  * Obviously there are many other scenarios, but it's probably not worth the
                                111                 :                :  * trouble to try to improve on this estimate, especially not when we don't
                                112                 :                :  * have a better estimate for the selectivity of the SubPlan qual itself.
                                113                 :                :  */
                                114                 :                : #define NUM_EXEC_TLIST(parentplan)  ((parentplan)->plan_rows)
                                115                 :                : #define NUM_EXEC_QUAL(parentplan)   ((parentplan)->plan_rows * 2.0)
                                116                 :                : 
                                117                 :                : /*
                                118                 :                :  * Check if a Const node is a regclass value.  We accept plain OID too,
                                119                 :                :  * since a regclass Const will get folded to that type if it's an argument
                                120                 :                :  * to oideq or similar operators.  (This might result in some extraneous
                                121                 :                :  * values in a plan's list of relation dependencies, but the worst result
                                122                 :                :  * would be occasional useless replans.)
                                123                 :                :  */
                                124                 :                : #define ISREGCLASSCONST(con) \
                                125                 :                :     (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
                                126                 :                :      !(con)->constisnull)
                                127                 :                : 
                                128                 :                : #define fix_scan_list(root, lst, rtoffset, num_exec) \
                                129                 :                :     ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))
                                130                 :                : 
                                131                 :                : static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
                                132                 :                : static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
                                133                 :                : static bool flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt);
                                134                 :                : static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
                                135                 :                :                                    RangeTblEntry *rte);
                                136                 :                : static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
                                137                 :                : static Plan *set_indexonlyscan_references(PlannerInfo *root,
                                138                 :                :                                           IndexOnlyScan *plan,
                                139                 :                :                                           int rtoffset);
                                140                 :                : static Plan *set_subqueryscan_references(PlannerInfo *root,
                                141                 :                :                                          SubqueryScan *plan,
                                142                 :                :                                          int rtoffset);
                                143                 :                : static Plan *clean_up_removed_plan_level(Plan *parent, Plan *child);
                                144                 :                : static void set_foreignscan_references(PlannerInfo *root,
                                145                 :                :                                        ForeignScan *fscan,
                                146                 :                :                                        int rtoffset);
                                147                 :                : static void set_customscan_references(PlannerInfo *root,
                                148                 :                :                                       CustomScan *cscan,
                                149                 :                :                                       int rtoffset);
                                150                 :                : static Plan *set_append_references(PlannerInfo *root,
                                151                 :                :                                    Append *aplan,
                                152                 :                :                                    int rtoffset);
                                153                 :                : static Plan *set_mergeappend_references(PlannerInfo *root,
                                154                 :                :                                         MergeAppend *mplan,
                                155                 :                :                                         int rtoffset);
                                156                 :                : static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset);
                                157                 :                : static Relids offset_relid_set(Relids relids, int rtoffset);
                                158                 :                : static List *offset_relid_set_list(List *relid_sets, int rtoffset);
                                159                 :                : static Node *fix_dummy_setop_vars_mutator(Node *node, int *first_child_relid);
                                160                 :                : static Node *fix_scan_expr(PlannerInfo *root, Node *node,
                                161                 :                :                            int rtoffset, double num_exec);
                                162                 :                : static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
                                163                 :                : static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
                                164                 :                : static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
                                165                 :                : static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
                                166                 :                : static void set_param_references(PlannerInfo *root, Plan *plan);
                                167                 :                : static Node *convert_combining_aggrefs(Node *node, void *context);
                                168                 :                : static void set_dummy_tlist_references(Plan *plan, int rtoffset);
                                169                 :                : static indexed_tlist *build_tlist_index(List *tlist);
                                170                 :                : static Var *search_indexed_tlist_for_var(Var *var,
                                171                 :                :                                          indexed_tlist *itlist,
                                172                 :                :                                          int newvarno,
                                173                 :                :                                          int rtoffset,
                                174                 :                :                                          NullingRelsMatch nrm_match);
                                175                 :                : static Var *search_indexed_tlist_for_phv(PlaceHolderVar *phv,
                                176                 :                :                                          indexed_tlist *itlist,
                                177                 :                :                                          int newvarno,
                                178                 :                :                                          NullingRelsMatch nrm_match);
                                179                 :                : static Var *search_indexed_tlist_for_non_var(Expr *node,
                                180                 :                :                                              indexed_tlist *itlist,
                                181                 :                :                                              int newvarno);
                                182                 :                : static Var *search_indexed_tlist_for_sortgroupref(Expr *node,
                                183                 :                :                                                   Index sortgroupref,
                                184                 :                :                                                   indexed_tlist *itlist,
                                185                 :                :                                                   int newvarno);
                                186                 :                : static List *fix_join_expr(PlannerInfo *root,
                                187                 :                :                            List *clauses,
                                188                 :                :                            indexed_tlist *outer_itlist,
                                189                 :                :                            indexed_tlist *inner_itlist,
                                190                 :                :                            Index acceptable_rel,
                                191                 :                :                            int rtoffset,
                                192                 :                :                            NullingRelsMatch nrm_match,
                                193                 :                :                            double num_exec);
                                194                 :                : static Node *fix_join_expr_mutator(Node *node,
                                195                 :                :                                    fix_join_expr_context *context);
                                196                 :                : static Node *fix_upper_expr(PlannerInfo *root,
                                197                 :                :                             Node *node,
                                198                 :                :                             indexed_tlist *subplan_itlist,
                                199                 :                :                             int newvarno,
                                200                 :                :                             int rtoffset,
                                201                 :                :                             double num_exec);
                                202                 :                : static Node *fix_upper_expr_mutator(Node *node,
                                203                 :                :                                     fix_upper_expr_context *context);
                                204                 :                : static List *set_returning_clause_references(PlannerInfo *root,
                                205                 :                :                                              List *rlist,
                                206                 :                :                                              Plan *topplan,
                                207                 :                :                                              Index resultRelation,
                                208                 :                :                                              int rtoffset);
                                209                 :                : static List *set_windowagg_runcondition_references(PlannerInfo *root,
                                210                 :                :                                                    List *runcondition,
                                211                 :                :                                                    Plan *plan);
                                212                 :                : 
                                213                 :                : static void record_elided_node(PlannerGlobal *glob, int plan_node_id,
                                214                 :                :                                NodeTag elided_type, Bitmapset *relids,
                                215                 :                :                                List *child_append_relid_sets);
                                216                 :                : 
                                217                 :                : 
                                218                 :                : /*****************************************************************************
                                219                 :                :  *
                                220                 :                :  *      SUBPLAN REFERENCES
                                221                 :                :  *
                                222                 :                :  *****************************************************************************/
                                223                 :                : 
                                224                 :                : /*
                                225                 :                :  * set_plan_references
                                226                 :                :  *
                                227                 :                :  * This is the final processing pass of the planner/optimizer.  The plan
                                228                 :                :  * tree is complete; we just have to adjust some representational details
                                229                 :                :  * for the convenience of the executor:
                                230                 :                :  *
                                231                 :                :  * 1. We flatten the various subquery rangetables into a single list, and
                                232                 :                :  * zero out RangeTblEntry fields that are not useful to the executor.
                                233                 :                :  *
                                234                 :                :  * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
                                235                 :                :  *
                                236                 :                :  * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
                                237                 :                :  * subplans.
                                238                 :                :  *
                                239                 :                :  * 4. Aggrefs in Agg plan nodes need to be adjusted in some cases involving
                                240                 :                :  * partial aggregation or minmax aggregate optimization.
                                241                 :                :  *
                                242                 :                :  * 5. PARAM_MULTIEXPR Params are replaced by regular PARAM_EXEC Params,
                                243                 :                :  * now that we have finished planning all MULTIEXPR subplans.
                                244                 :                :  *
                                245                 :                :  * 6. AlternativeSubPlan expressions are replaced by just one of their
                                246                 :                :  * alternatives, using an estimate of how many times they'll be executed.
                                247                 :                :  *
                                248                 :                :  * 7. We compute regproc OIDs for operators (ie, we look up the function
                                249                 :                :  * that implements each op).
                                250                 :                :  *
                                251                 :                :  * 8. We create lists of specific objects that the plan depends on.
                                252                 :                :  * This will be used by plancache.c to drive invalidation of cached plans.
                                253                 :                :  * Relation dependencies are represented by OIDs, and everything else by
                                254                 :                :  * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
                                255                 :                :  * Currently, relations, user-defined functions, and domains are the only
                                256                 :                :  * types of objects that are explicitly tracked this way.
                                257                 :                :  *
                                258                 :                :  * 9. We assign every plan node in the tree a unique ID.
                                259                 :                :  *
                                260                 :                :  * We also perform one final optimization step, which is to delete
                                261                 :                :  * SubqueryScan, Append, and MergeAppend plan nodes that aren't doing
                                262                 :                :  * anything useful.  The reason for doing this last is that
                                263                 :                :  * it can't readily be done before set_plan_references, because it would
                                264                 :                :  * break set_upper_references: the Vars in the child plan's top tlist
                                265                 :                :  * wouldn't match up with the Vars in the outer plan tree.  A SubqueryScan
                                266                 :                :  * serves a necessary function as a buffer between outer query and subquery
                                267                 :                :  * variable numbering ... but after we've flattened the rangetable this is
                                268                 :                :  * no longer a problem, since then there's only one rtindex namespace.
                                269                 :                :  * Likewise, Append and MergeAppend buffer between the parent and child vars
                                270                 :                :  * of an appendrel, but we don't need to worry about that once we've done
                                271                 :                :  * set_plan_references.
                                272                 :                :  *
                                273                 :                :  * set_plan_references recursively traverses the whole plan tree.
                                274                 :                :  *
                                275                 :                :  * The return value is normally the same Plan node passed in, but can be
                                276                 :                :  * different when the passed-in Plan is a node we decide isn't needed.
                                277                 :                :  *
                                278                 :                :  * The flattened rangetable entries are appended to root->glob->finalrtable.
                                279                 :                :  * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
                                280                 :                :  * RT indexes of ModifyTable result relations to root->glob->resultRelations,
                                281                 :                :  * and flattened AppendRelInfos are appended to root->glob->appendRelations.
                                282                 :                :  * Plan dependencies are appended to root->glob->relationOids (for relations)
                                283                 :                :  * and root->glob->invalItems (for everything else).
                                284                 :                :  *
                                285                 :                :  * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
                                286                 :                :  * to process targetlist and qual expressions.  We can assume that the Plan
                                287                 :                :  * nodes were just built by the planner and are not multiply referenced, but
                                288                 :                :  * it's not so safe to assume that for expression tree nodes.
                                289                 :                :  */
                                290                 :                : Plan *
 5518 tgl@sss.pgh.pa.us         291                 :CBC      386224 : set_plan_references(PlannerInfo *root, Plan *plan)
                                292                 :                : {
                                293                 :                :     Plan       *result;
                                294                 :         386224 :     PlannerGlobal *glob = root->glob;
 7172                           295                 :         386224 :     int         rtoffset = list_length(glob->finalrtable);
                                296                 :                :     ListCell   *lc;
                                297                 :                : 
                                298                 :                :     /*
                                299                 :                :      * Add all the query's RTEs to the flattened rangetable.  The live ones
                                300                 :                :      * will have their rangetable indexes increased by rtoffset.  (Additional
                                301                 :                :      * RTEs, not referenced by the Plan tree, might get added after those.)
                                302                 :                :      */
 4905                           303                 :         386224 :     add_rtes_to_flat_rtable(root, false);
                                304                 :                : 
                                305                 :                :     /*
                                306                 :                :      * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
                                307                 :                :      */
 5518                           308   [ +  +  +  +  :         396835 :     foreach(lc, root->rowMarks)
                                              +  + ]
                                309                 :                :     {
 3472                           310                 :          10611 :         PlanRowMark *rc = lfirst_node(PlanRowMark, lc);
                                311                 :                :         PlanRowMark *newrc;
                                312                 :                : 
                                313                 :                :         /* sanity check on existing row marks */
  414 akorotkov@postgresql      314   [ +  -  -  + ]:          10611 :         Assert(root->simple_rel_array[rc->rti] != NULL &&
                                315                 :                :                root->simple_rte_array[rc->rti] != NULL);
                                316                 :                : 
                                317                 :                :         /* flat copy is enough since all fields are scalars */
  306 michael@paquier.xyz       318                 :          10611 :         newrc = palloc_object(PlanRowMark);
 6195 tgl@sss.pgh.pa.us         319                 :          10611 :         memcpy(newrc, rc, sizeof(PlanRowMark));
                                320                 :                : 
                                321                 :                :         /* adjust indexes ... but *not* the rowmarkId */
 6209                           322                 :          10611 :         newrc->rti += rtoffset;
                                323                 :          10611 :         newrc->prti += rtoffset;
                                324                 :                : 
                                325                 :          10611 :         glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
                                326                 :                :     }
                                327                 :                : 
                                328                 :                :     /*
                                329                 :                :      * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
                                330                 :                :      * We assume the AppendRelInfos were built during planning and don't need
                                331                 :                :      * to be copied.
                                332                 :                :      */
 2497                           333   [ +  +  +  +  :         432734 :     foreach(lc, root->append_rel_list)
                                              +  + ]
                                334                 :                :     {
                                335                 :          46510 :         AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
                                336                 :                : 
                                337                 :                :         /* adjust RT indexes */
                                338                 :          46510 :         appinfo->parent_relid += rtoffset;
                                339                 :          46510 :         appinfo->child_relid += rtoffset;
                                340                 :                : 
                                341                 :                :         /*
                                342                 :                :          * Rather than adjust the translated_vars entries, just drop 'em.
                                343                 :                :          * Neither the executor nor EXPLAIN currently need that data.
                                344                 :                :          */
                                345                 :          46510 :         appinfo->translated_vars = NIL;
                                346                 :                : 
                                347                 :          46510 :         glob->appendRelations = lappend(glob->appendRelations, appinfo);
                                348                 :                :     }
                                349                 :                : 
                                350                 :                :     /* If needed, create workspace for processing AlternativeSubPlans */
 1854                           351         [ +  + ]:         386224 :     if (root->hasAlternativeSubPlans)
                                352                 :                :     {
   56 michael@paquier.xyz       353                 :GNC         784 :         root->isAltSubplan = palloc0_array(bool, list_length(glob->subplans));
                                354                 :            784 :         root->isUsedSubplan = palloc0_array(bool, list_length(glob->subplans));
                                355                 :                :     }
                                356                 :                : 
                                357                 :                :     /* Now fix the Plan tree */
 1854 tgl@sss.pgh.pa.us         358                 :CBC      386224 :     result = set_plan_refs(root, plan, rtoffset);
                                359                 :                : 
                                360                 :                :     /*
                                361                 :                :      * If we have AlternativeSubPlans, it is likely that we now have some
                                362                 :                :      * unreferenced subplans in glob->subplans.  To avoid expending cycles on
                                363                 :                :      * those subplans later, get rid of them by setting those list entries to
                                364                 :                :      * NULL.  (Note: we can't do this immediately upon processing an
                                365                 :                :      * AlternativeSubPlan, because there may be multiple copies of the
                                366                 :                :      * AlternativeSubPlan, and they can get resolved differently.)
                                367                 :                :      */
                                368         [ +  + ]:         386224 :     if (root->hasAlternativeSubPlans)
                                369                 :                :     {
                                370   [ +  -  +  +  :           3756 :         foreach(lc, glob->subplans)
                                              +  + ]
                                371                 :                :         {
                                372                 :           2972 :             int         ndx = foreach_current_index(lc);
                                373                 :                : 
                                374                 :                :             /*
                                375                 :                :              * If it was used by some AlternativeSubPlan in this query level,
                                376                 :                :              * but wasn't selected as best by any AlternativeSubPlan, then we
                                377                 :                :              * don't need it.  Do not touch subplans that aren't parts of
                                378                 :                :              * AlternativeSubPlans.
                                379                 :                :              */
                                380   [ +  +  +  + ]:           2972 :             if (root->isAltSubplan[ndx] && !root->isUsedSubplan[ndx])
                                381                 :           1258 :                 lfirst(lc) = NULL;
                                382                 :                :         }
                                383                 :                :     }
                                384                 :                : 
                                385                 :         386224 :     return result;
                                386                 :                : }
                                387                 :                : 
                                388                 :                : /*
                                389                 :                :  * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
                                390                 :                :  *
                                391                 :                :  * This can recurse into subquery plans; "recursing" is true if so.
                                392                 :                :  *
                                393                 :                :  * This also seems like a good place to add the query's RTEPermissionInfos to
                                394                 :                :  * the flat rteperminfos.
                                395                 :                :  */
                                396                 :                : static void
 4905                           397                 :         386457 : add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
                                398                 :                : {
                                399                 :         386457 :     PlannerGlobal *glob = root->glob;
                                400                 :                :     Index       rti;
                                401                 :                :     ListCell   *lc;
                                402                 :                : 
                                403                 :                :     /*
                                404                 :                :      * Record enough information to make it possible for code that looks at
                                405                 :                :      * the final range table to understand how it was constructed. (If
                                406                 :                :      * finalrtable is still NIL, then this is the very topmost PlannerInfo,
                                407                 :                :      * which will always have plan_name == NULL and rtoffset == 0; we omit the
                                408                 :                :      * degenerate list entry.)
                                409                 :                :      */
  244 rhaas@postgresql.org      410         [ +  + ]:         386457 :     if (root->glob->finalrtable != NIL)
                                411                 :                :     {
                                412                 :          62252 :         SubPlanRTInfo *rtinfo = makeNode(SubPlanRTInfo);
                                413                 :                : 
                                414                 :          62252 :         rtinfo->plan_name = root->plan_name;
                                415                 :          62252 :         rtinfo->rtoffset = list_length(root->glob->finalrtable);
                                416                 :                : 
                                417                 :                :         /* When recursing = true, it's an unplanned or dummy subquery. */
                                418                 :          62252 :         rtinfo->dummy = recursing;
                                419                 :                : 
                                420                 :          62252 :         root->glob->subrtinfos = lappend(root->glob->subrtinfos, rtinfo);
                                421                 :                :     }
                                422                 :                : 
                                423                 :                :     /*
                                424                 :                :      * Add the query's own RTEs to the flattened rangetable.
                                425                 :                :      *
                                426                 :                :      * At top level, we must add all RTEs so that their indexes in the
                                427                 :                :      * flattened rangetable match up with their original indexes.  When
                                428                 :                :      * recursing, we only care about extracting relation RTEs (and subquery
                                429                 :                :      * RTEs that were once relation RTEs).
                                430                 :                :      */
 4905 tgl@sss.pgh.pa.us         431   [ +  -  +  +  :        1105707 :     foreach(lc, root->parse->rtable)
                                              +  + ]
                                432                 :                :     {
                                433                 :         719250 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                                434                 :                : 
 1363                           435   [ +  +  +  + ]:         719250 :         if (!recursing || rte->rtekind == RTE_RELATION ||
                                436   [ +  +  -  + ]:            205 :             (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
 1406 alvherre@alvh.no-ip.      437                 :         719045 :             add_rte_to_flat_rtable(glob, root->parse->rteperminfos, rte);
                                438                 :                :     }
                                439                 :                : 
                                440                 :                :     /*
                                441                 :                :      * If there are any dead subqueries, they are not referenced in the Plan
                                442                 :                :      * tree, so we must add RTEs contained in them to the flattened rtable
                                443                 :                :      * separately.  (If we failed to do this, the executor would not perform
                                444                 :                :      * expected permission checks for tables mentioned in such subqueries.)
                                445                 :                :      *
                                446                 :                :      * Note: this pass over the rangetable can't be combined with the previous
                                447                 :                :      * one, because that would mess up the numbering of the live RTEs in the
                                448                 :                :      * flattened rangetable.
                                449                 :                :      */
 4905 tgl@sss.pgh.pa.us         450                 :         386457 :     rti = 1;
                                451   [ +  -  +  +  :        1105707 :     foreach(lc, root->parse->rtable)
                                              +  + ]
                                452                 :                :     {
                                453                 :         719250 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                                454                 :                : 
                                455                 :                :         /*
                                456                 :                :          * We should ignore inheritance-parent RTEs: their contents have been
                                457                 :                :          * pulled up into our rangetable already.  Also ignore any subquery
                                458                 :                :          * RTEs without matching RelOptInfos, as they likewise have been
                                459                 :                :          * pulled up.
                                460                 :                :          */
 4685                           461   [ +  +  +  + ]:         719250 :         if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
                                462         [ +  - ]:          59045 :             rti < root->simple_rel_array_size)
                                463                 :                :         {
 4905                           464                 :          59045 :             RelOptInfo *rel = root->simple_rel_array[rti];
                                465                 :                : 
                                466         [ +  + ]:          59045 :             if (rel != NULL)
                                467                 :                :             {
 3400                           468         [ -  + ]:          29914 :                 Assert(rel->relid == rti);   /* sanity check on array */
                                469                 :                : 
                                470                 :                :                 /*
                                471                 :                :                  * The subquery might never have been planned at all, if it
                                472                 :                :                  * was excluded on the basis of self-contradictory constraints
                                473                 :                :                  * in our query level.  In this case apply
                                474                 :                :                  * flatten_unplanned_rtes.
                                475                 :                :                  *
                                476                 :                :                  * If it was planned but the result rel is dummy, we assume
                                477                 :                :                  * that it has been omitted from our plan tree (see
                                478                 :                :                  * set_subquery_pathlist), and recurse to pull up its RTEs.
                                479                 :                :                  *
                                480                 :                :                  * Otherwise, it should be represented by a SubqueryScan node
                                481                 :                :                  * somewhere in our plan tree, and we'll pull up its RTEs when
                                482                 :                :                  * we process that plan node.
                                483                 :                :                  *
                                484                 :                :                  * However, if we're recursing, then we should pull up RTEs
                                485                 :                :                  * whether the subquery is dummy or not, because we've found
                                486                 :                :                  * that some upper query level is treating this one as dummy,
                                487                 :                :                  * and so we won't scan this level's plan tree at all.
                                488                 :                :                  */
 3871                           489         [ +  + ]:          29914 :                 if (rel->subroot == NULL)
 4905                           490                 :             21 :                     flatten_unplanned_rtes(glob, rte);
 3871                           491   [ +  +  +  + ]:          59746 :                 else if (recursing ||
                                492                 :          29853 :                          IS_DUMMY_REL(fetch_upper_rel(rel->subroot,
                                493                 :                :                                                       UPPERREL_FINAL, NULL)))
 4905                           494                 :            233 :                     add_rtes_to_flat_rtable(rel->subroot, true);
                                495                 :                :             }
                                496                 :                :         }
                                497                 :         719250 :         rti++;
                                498                 :                :     }
                                499                 :         386457 : }
                                500                 :                : 
                                501                 :                : /*
                                502                 :                :  * Extract RangeTblEntries from a subquery that was never planned at all
                                503                 :                :  */
                                504                 :                : 
                                505                 :                : static void
                                506                 :             21 : flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
                                507                 :                : {
 1406 alvherre@alvh.no-ip.      508                 :             21 :     flatten_rtes_walker_context cxt = {glob, rte->subquery};
                                509                 :                : 
                                510                 :                :     /* Use query_tree_walker to find all RTEs in the parse tree */
 4905 tgl@sss.pgh.pa.us         511                 :             21 :     (void) query_tree_walker(rte->subquery,
                                512                 :                :                              flatten_rtes_walker,
                                513                 :                :                              &cxt,
                                514                 :                :                              QTW_EXAMINE_RTES_BEFORE);
                                515                 :             21 : }
                                516                 :                : 
                                517                 :                : static bool
 1406 alvherre@alvh.no-ip.      518                 :            545 : flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt)
                                519                 :                : {
 4905 tgl@sss.pgh.pa.us         520         [ +  + ]:            545 :     if (node == NULL)
                                521                 :            314 :         return false;
                                522         [ +  + ]:            231 :     if (IsA(node, RangeTblEntry))
                                523                 :                :     {
                                524                 :             17 :         RangeTblEntry *rte = (RangeTblEntry *) node;
                                525                 :                : 
                                526                 :                :         /* As above, we need only save relation RTEs and former relations */
 1363                           527         [ -  + ]:             17 :         if (rte->rtekind == RTE_RELATION ||
 1363 tgl@sss.pgh.pa.us         528   [ #  #  #  # ]:UBC           0 :             (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
 1406 alvherre@alvh.no-ip.      529                 :CBC          17 :             add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
 4905 tgl@sss.pgh.pa.us         530                 :             17 :         return false;
                                531                 :                :     }
                                532         [ +  + ]:            214 :     if (IsA(node, Query))
                                533                 :                :     {
                                534                 :                :         /*
                                535                 :                :          * Recurse into subselects.  Must update cxt->query to this query so
                                536                 :                :          * that the rtable and rteperminfos correspond with each other.
                                537                 :                :          */
 1337                           538                 :              6 :         Query      *save_query = cxt->query;
                                539                 :                :         bool        result;
                                540                 :                : 
 1406 alvherre@alvh.no-ip.      541                 :              6 :         cxt->query = (Query *) node;
 1337 tgl@sss.pgh.pa.us         542                 :              6 :         result = query_tree_walker((Query *) node,
                                543                 :                :                                    flatten_rtes_walker,
                                544                 :                :                                    cxt,
                                545                 :                :                                    QTW_EXAMINE_RTES_BEFORE);
                                546                 :              6 :         cxt->query = save_query;
                                547                 :              6 :         return result;
                                548                 :                :     }
  683 peter@eisentraut.org      549                 :            208 :     return expression_tree_walker(node, flatten_rtes_walker, cxt);
                                550                 :                : }
                                551                 :                : 
                                552                 :                : /*
                                553                 :                :  * Add (a copy of) the given RTE to the final rangetable and also the
                                554                 :                :  * corresponding RTEPermissionInfo, if any, to final rteperminfos.
                                555                 :                :  *
                                556                 :                :  * In the flat rangetable, we zero out substructure pointers that are not
                                557                 :                :  * needed by the executor; this reduces the storage space and copying cost
                                558                 :                :  * for cached plans.  We keep only the ctename, alias, eref Alias fields,
                                559                 :                :  * which are needed by EXPLAIN, and perminfoindex which is needed by the
                                560                 :                :  * executor to fetch the RTE's RTEPermissionInfo.
                                561                 :                :  */
                                562                 :                : static void
 1406 alvherre@alvh.no-ip.      563                 :         719062 : add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
                                564                 :                :                        RangeTblEntry *rte)
                                565                 :                : {
                                566                 :                :     RangeTblEntry *newrte;
                                567                 :                : 
                                568                 :                :     /* flat copy to duplicate all the scalar fields */
  306 michael@paquier.xyz       569                 :         719062 :     newrte = palloc_object(RangeTblEntry);
 4905 tgl@sss.pgh.pa.us         570                 :         719062 :     memcpy(newrte, rte, sizeof(RangeTblEntry));
                                571                 :                : 
                                572                 :                :     /* zap unneeded sub-structure */
 4097                           573                 :         719062 :     newrte->tablesample = NULL;
 4905                           574                 :         719062 :     newrte->subquery = NULL;
                                575                 :         719062 :     newrte->joinaliasvars = NIL;
 2468                           576                 :         719062 :     newrte->joinleftcols = NIL;
                                577                 :         719062 :     newrte->joinrightcols = NIL;
 2021 peter@eisentraut.org      578                 :         719062 :     newrte->join_using_alias = NULL;
 4708 tgl@sss.pgh.pa.us         579                 :         719062 :     newrte->functions = NIL;
 3505 alvherre@alvh.no-ip.      580                 :         719062 :     newrte->tablefunc = NULL;
 4905 tgl@sss.pgh.pa.us         581                 :         719062 :     newrte->values_lists = NIL;
 3595                           582                 :         719062 :     newrte->coltypes = NIL;
                                583                 :         719062 :     newrte->coltypmods = NIL;
                                584                 :         719062 :     newrte->colcollations = NIL;
  762 rguo@postgresql.org       585                 :         719062 :     newrte->groupexprs = NIL;
 4101 tgl@sss.pgh.pa.us         586                 :         719062 :     newrte->securityQuals = NIL;
                                587                 :                : 
 4905                           588                 :         719062 :     glob->finalrtable = lappend(glob->finalrtable, newrte);
                                589                 :                : 
                                590                 :                :     /*
                                591                 :                :      * If it's a plain relation RTE (or a subquery that was once a view
                                592                 :                :      * reference), add the relation OID to relationOids.  Also add its new RT
                                593                 :                :      * index to the set of relations to be potentially accessed during
                                594                 :                :      * execution.
                                595                 :                :      *
                                596                 :                :      * We do this even though the RTE might be unreferenced in the plan tree;
                                597                 :                :      * this would correspond to cases such as views that were expanded, child
                                598                 :                :      * tables that were eliminated by constraint exclusion, etc. Schema
                                599                 :                :      * invalidation on such a rel must still force rebuilding of the plan.
                                600                 :                :      *
                                601                 :                :      * Note we don't bother to avoid making duplicate list entries.  We could,
                                602                 :                :      * but it would probably cost more cycles than it would save.
                                603                 :                :      */
 1363                           604         [ +  + ]:         719062 :     if (newrte->rtekind == RTE_RELATION ||
                                605   [ +  +  +  + ]:         328819 :         (newrte->rtekind == RTE_SUBQUERY && OidIsValid(newrte->relid)))
                                606                 :                :     {
 4905                           607                 :         402716 :         glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
  612 amitlan@postgresql.o      608                 :         402716 :         glob->allRelids = bms_add_member(glob->allRelids,
                                609                 :         402716 :                                          list_length(glob->finalrtable));
                                610                 :                :     }
                                611                 :                : 
                                612                 :                :     /*
                                613                 :                :      * Add a copy of the RTEPermissionInfo, if any, corresponding to this RTE
                                614                 :                :      * to the flattened global list.
                                615                 :                :      */
 1406 alvherre@alvh.no-ip.      616         [ +  + ]:         719062 :     if (rte->perminfoindex > 0)
                                617                 :                :     {
                                618                 :                :         RTEPermissionInfo *perminfo;
                                619                 :                :         RTEPermissionInfo *newperminfo;
                                620                 :                : 
                                621                 :                :         /* Get the existing one from this query's rteperminfos. */
                                622                 :         367586 :         perminfo = getRTEPermissionInfo(rteperminfos, newrte);
                                623                 :                : 
                                624                 :                :         /*
                                625                 :                :          * Add a new one to finalrteperminfos and copy the contents of the
                                626                 :                :          * existing one into it.  Note that addRTEPermissionInfo() also
                                627                 :                :          * updates newrte->perminfoindex to point to newperminfo in
                                628                 :                :          * finalrteperminfos.
                                629                 :                :          */
                                630                 :         367586 :         newrte->perminfoindex = 0;   /* expected by addRTEPermissionInfo() */
                                631                 :         367586 :         newperminfo = addRTEPermissionInfo(&glob->finalrteperminfos, newrte);
                                632                 :         367586 :         memcpy(newperminfo, perminfo, sizeof(RTEPermissionInfo));
                                633                 :                :     }
 4905 tgl@sss.pgh.pa.us         634                 :         719062 : }
                                635                 :                : 
                                636                 :                : /*
                                637                 :                :  * set_plan_refs: recurse through the Plan nodes of a single subquery level
                                638                 :                :  */
                                639                 :                : static Plan *
 5518                           640                 :        2143072 : set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
                                641                 :                : {
                                642                 :                :     ListCell   *l;
                                643                 :                : 
10627 bruce@momjian.us          644         [ +  + ]:        2143072 :     if (plan == NULL)
 7813 tgl@sss.pgh.pa.us         645                 :        1229030 :         return NULL;
                                646                 :                : 
                                647                 :                :     /* Assign this node a unique ID. */
 4032 rhaas@postgresql.org      648                 :         914042 :     plan->plan_node_id = root->glob->lastPlanNodeId++;
                                649                 :                : 
                                650                 :                :     /*
                                651                 :                :      * Plan-type-specific fixes
                                652                 :                :      */
 9913 tgl@sss.pgh.pa.us         653   [ +  +  +  +  :         914042 :     switch (nodeTag(plan))
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                              +  - ]
                                654                 :                :     {
                                655                 :         173303 :         case T_SeqScan:
                                656                 :                :             {
 6906 bruce@momjian.us          657                 :         173303 :                 SeqScan    *splan = (SeqScan *) plan;
                                658                 :                : 
 1891 peter@eisentraut.org      659                 :         173303 :                 splan->scan.scanrelid += rtoffset;
                                660                 :         173303 :                 splan->scan.plan.targetlist =
                                661                 :         173303 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                662                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
                                663                 :         173303 :                 splan->scan.plan.qual =
                                664                 :         173303 :                     fix_scan_list(root, splan->scan.plan.qual,
                                665                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                666                 :                :             }
 9913 tgl@sss.pgh.pa.us         667                 :         173303 :             break;
 4168 simon@2ndQuadrant.co      668                 :            262 :         case T_SampleScan:
                                669                 :                :             {
 4160 bruce@momjian.us          670                 :            262 :                 SampleScan *splan = (SampleScan *) plan;
                                671                 :                : 
 4097 tgl@sss.pgh.pa.us         672                 :            262 :                 splan->scan.scanrelid += rtoffset;
                                673                 :            262 :                 splan->scan.plan.targetlist =
 2206                           674                 :            262 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                675                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 4097                           676                 :            262 :                 splan->scan.plan.qual =
 2206                           677                 :            262 :                     fix_scan_list(root, splan->scan.plan.qual,
                                678                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 4097                           679                 :            262 :                 splan->tablesample = (TableSampleClause *)
 2206                           680                 :            262 :                     fix_scan_expr(root, (Node *) splan->tablesample,
                                681                 :                :                                   rtoffset, 1);
                                682                 :                :             }
 4168 simon@2ndQuadrant.co      683                 :            262 :             break;
 9913 tgl@sss.pgh.pa.us         684                 :         102519 :         case T_IndexScan:
                                685                 :                :             {
 6906 bruce@momjian.us          686                 :         102519 :                 IndexScan  *splan = (IndexScan *) plan;
                                687                 :                : 
 7172 tgl@sss.pgh.pa.us         688                 :         102519 :                 splan->scan.scanrelid += rtoffset;
                                689                 :         102519 :                 splan->scan.plan.targetlist =
 2206                           690                 :         102519 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                691                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 7172                           692                 :         102519 :                 splan->scan.plan.qual =
 2206                           693                 :         102519 :                     fix_scan_list(root, splan->scan.plan.qual,
                                694                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 7172                           695                 :         102519 :                 splan->indexqual =
 2206                           696                 :         102519 :                     fix_scan_list(root, splan->indexqual,
                                697                 :                :                                   rtoffset, 1);
 7172                           698                 :         102519 :                 splan->indexqualorig =
 2206                           699                 :         102519 :                     fix_scan_list(root, splan->indexqualorig,
                                700                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 5793                           701                 :         102519 :                 splan->indexorderby =
 2206                           702                 :         102519 :                     fix_scan_list(root, splan->indexorderby,
                                703                 :                :                                   rtoffset, 1);
 5793                           704                 :         102519 :                 splan->indexorderbyorig =
 2206                           705                 :         102519 :                     fix_scan_list(root, splan->indexorderbyorig,
                                706                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                707                 :                :             }
 9626                           708                 :         102519 :             break;
 5480                           709                 :          11423 :         case T_IndexOnlyScan:
                                710                 :                :             {
 5237 bruce@momjian.us          711                 :          11423 :                 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
                                712                 :                : 
 5480 tgl@sss.pgh.pa.us         713                 :          11423 :                 return set_indexonlyscan_references(root, splan, rtoffset);
                                714                 :                :             }
                                715                 :                :             break;
 7846                           716                 :          17911 :         case T_BitmapIndexScan:
                                717                 :                :             {
 7172                           718                 :          17911 :                 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
                                719                 :                : 
                                720                 :          17911 :                 splan->scan.scanrelid += rtoffset;
                                721                 :                :                 /* no need to fix targetlist and qual */
                                722         [ -  + ]:          17911 :                 Assert(splan->scan.plan.targetlist == NIL);
                                723         [ -  + ]:          17911 :                 Assert(splan->scan.plan.qual == NIL);
                                724                 :          17911 :                 splan->indexqual =
 2206                           725                 :          17911 :                     fix_scan_list(root, splan->indexqual, rtoffset, 1);
 7172                           726                 :          17911 :                 splan->indexqualorig =
 2206                           727                 :          17911 :                     fix_scan_list(root, splan->indexqualorig,
                                728                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                729                 :                :             }
 7846                           730                 :          17911 :             break;
                                731                 :          17441 :         case T_BitmapHeapScan:
                                732                 :                :             {
 7172                           733                 :          17441 :                 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
                                734                 :                : 
                                735                 :          17441 :                 splan->scan.scanrelid += rtoffset;
                                736                 :          17441 :                 splan->scan.plan.targetlist =
 2206                           737                 :          17441 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                738                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 7172                           739                 :          17441 :                 splan->scan.plan.qual =
 2206                           740                 :          17441 :                     fix_scan_list(root, splan->scan.plan.qual,
                                741                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 7172                           742                 :          17441 :                 splan->bitmapqualorig =
 2206                           743                 :          17441 :                     fix_scan_list(root, splan->bitmapqualorig,
                                744                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                745                 :                :             }
 7846                           746                 :          17441 :             break;
 9626                           747                 :            562 :         case T_TidScan:
                                748                 :                :             {
 6906 bruce@momjian.us          749                 :            562 :                 TidScan    *splan = (TidScan *) plan;
                                750                 :                : 
 7172 tgl@sss.pgh.pa.us         751                 :            562 :                 splan->scan.scanrelid += rtoffset;
                                752                 :            562 :                 splan->scan.plan.targetlist =
 2206                           753                 :            562 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                754                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 7172                           755                 :            562 :                 splan->scan.plan.qual =
 2206                           756                 :            562 :                     fix_scan_list(root, splan->scan.plan.qual,
                                757                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 7172                           758                 :            562 :                 splan->tidquals =
 2206                           759                 :            562 :                     fix_scan_list(root, splan->tidquals,
                                760                 :                :                                   rtoffset, 1);
                                761                 :                :             }
 9913                           762                 :            562 :             break;
 2053 drowley@postgresql.o      763                 :           1643 :         case T_TidRangeScan:
                                764                 :                :             {
                                765                 :           1643 :                 TidRangeScan *splan = (TidRangeScan *) plan;
                                766                 :                : 
                                767                 :           1643 :                 splan->scan.scanrelid += rtoffset;
                                768                 :           1643 :                 splan->scan.plan.targetlist =
                                769                 :           1643 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                770                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
                                771                 :           1643 :                 splan->scan.plan.qual =
                                772                 :           1643 :                     fix_scan_list(root, splan->scan.plan.qual,
                                773                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                774                 :           1643 :                 splan->tidrangequals =
                                775                 :           1643 :                     fix_scan_list(root, splan->tidrangequals,
                                776                 :                :                                   rtoffset, 1);
                                777                 :                :             }
                                778                 :           1643 :             break;
 9509 tgl@sss.pgh.pa.us         779                 :          29625 :         case T_SubqueryScan:
                                780                 :                :             /* Needs special treatment, see comments below */
 5518                           781                 :          29625 :             return set_subqueryscan_references(root,
                                782                 :                :                                                (SubqueryScan *) plan,
                                783                 :                :                                                rtoffset);
 8919                           784                 :          35194 :         case T_FunctionScan:
                                785                 :                :             {
 7172                           786                 :          35194 :                 FunctionScan *splan = (FunctionScan *) plan;
                                787                 :                : 
                                788                 :          35194 :                 splan->scan.scanrelid += rtoffset;
                                789                 :          35194 :                 splan->scan.plan.targetlist =
 2206                           790                 :          35194 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                791                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 7172                           792                 :          35194 :                 splan->scan.plan.qual =
 2206                           793                 :          35194 :                     fix_scan_list(root, splan->scan.plan.qual,
                                794                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 4708                           795                 :          35194 :                 splan->functions =
 2206                           796                 :          35194 :                     fix_scan_list(root, splan->functions, rtoffset, 1);
                                797                 :                :             }
 8919                           798                 :          35194 :             break;
 3505 alvherre@alvh.no-ip.      799                 :            602 :         case T_TableFuncScan:
                                800                 :                :             {
                                801                 :            602 :                 TableFuncScan *splan = (TableFuncScan *) plan;
                                802                 :                : 
                                803                 :            602 :                 splan->scan.scanrelid += rtoffset;
                                804                 :            602 :                 splan->scan.plan.targetlist =
 2206 tgl@sss.pgh.pa.us         805                 :            602 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                806                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 3505 alvherre@alvh.no-ip.      807                 :            602 :                 splan->scan.plan.qual =
 2206 tgl@sss.pgh.pa.us         808                 :            602 :                     fix_scan_list(root, splan->scan.plan.qual,
                                809                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 3505 alvherre@alvh.no-ip.      810                 :            602 :                 splan->tablefunc = (TableFunc *)
 2206 tgl@sss.pgh.pa.us         811                 :            602 :                     fix_scan_expr(root, (Node *) splan->tablefunc,
                                812                 :                :                                   rtoffset, 1);
                                813                 :                :             }
 3505 alvherre@alvh.no-ip.      814                 :            602 :             break;
 7376 mail@joeconway.com        815                 :           6779 :         case T_ValuesScan:
                                816                 :                :             {
 7172 tgl@sss.pgh.pa.us         817                 :           6779 :                 ValuesScan *splan = (ValuesScan *) plan;
                                818                 :                : 
                                819                 :           6779 :                 splan->scan.scanrelid += rtoffset;
                                820                 :           6779 :                 splan->scan.plan.targetlist =
 2206                           821                 :           6779 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                822                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 7172                           823                 :           6779 :                 splan->scan.plan.qual =
 2206                           824                 :           6779 :                     fix_scan_list(root, splan->scan.plan.qual,
                                825                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
 7172                           826                 :           6779 :                 splan->values_lists =
 2206                           827                 :           6779 :                     fix_scan_list(root, splan->values_lists,
                                828                 :                :                                   rtoffset, 1);
                                829                 :                :             }
 7376 mail@joeconway.com        830                 :           6779 :             break;
 6582 tgl@sss.pgh.pa.us         831                 :           3309 :         case T_CteScan:
                                832                 :                :             {
 6332 bruce@momjian.us          833                 :           3309 :                 CteScan    *splan = (CteScan *) plan;
                                834                 :                : 
 6582 tgl@sss.pgh.pa.us         835                 :           3309 :                 splan->scan.scanrelid += rtoffset;
                                836                 :           3309 :                 splan->scan.plan.targetlist =
 2206                           837                 :           3309 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                838                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 6582                           839                 :           3309 :                 splan->scan.plan.qual =
 2206                           840                 :           3309 :                     fix_scan_list(root, splan->scan.plan.qual,
                                841                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                842                 :                :             }
 6582                           843                 :           3309 :             break;
 3482 kgrittn@postgresql.o      844                 :            407 :         case T_NamedTuplestoreScan:
                                845                 :                :             {
                                846                 :            407 :                 NamedTuplestoreScan *splan = (NamedTuplestoreScan *) plan;
                                847                 :                : 
                                848                 :            407 :                 splan->scan.scanrelid += rtoffset;
                                849                 :            407 :                 splan->scan.plan.targetlist =
 2206 tgl@sss.pgh.pa.us         850                 :            407 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                851                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 3482 kgrittn@postgresql.o      852                 :            407 :                 splan->scan.plan.qual =
 2206 tgl@sss.pgh.pa.us         853                 :            407 :                     fix_scan_list(root, splan->scan.plan.qual,
                                854                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                855                 :                :             }
 3482 kgrittn@postgresql.o      856                 :            407 :             break;
 6582 tgl@sss.pgh.pa.us         857                 :            692 :         case T_WorkTableScan:
                                858                 :                :             {
                                859                 :            692 :                 WorkTableScan *splan = (WorkTableScan *) plan;
                                860                 :                : 
                                861                 :            692 :                 splan->scan.scanrelid += rtoffset;
                                862                 :            692 :                 splan->scan.plan.targetlist =
 2206                           863                 :            692 :                     fix_scan_list(root, splan->scan.plan.targetlist,
                                864                 :                :                                   rtoffset, NUM_EXEC_TLIST(plan));
 6582                           865                 :            692 :                 splan->scan.plan.qual =
 2206                           866                 :            692 :                     fix_scan_list(root, splan->scan.plan.qual,
                                867                 :                :                                   rtoffset, NUM_EXEC_QUAL(plan));
                                868                 :                :             }
 6582                           869                 :            692 :             break;
 5713                           870                 :           1115 :         case T_ForeignScan:
 4182 rhaas@postgresql.org      871                 :           1115 :             set_foreignscan_references(root, (ForeignScan *) plan, rtoffset);
 5713 tgl@sss.pgh.pa.us         872                 :           1115 :             break;
 4357 rhaas@postgresql.org      873                 :GBC          10 :         case T_CustomScan:
 4182                           874                 :             10 :             set_customscan_references(root, (CustomScan *) plan, rtoffset);
 4357                           875                 :             10 :             break;
                                876                 :                : 
 9913 tgl@sss.pgh.pa.us         877                 :CBC      110978 :         case T_NestLoop:
                                878                 :                :         case T_MergeJoin:
                                879                 :                :         case T_HashJoin:
 5518                           880                 :         110978 :             set_join_references(root, (Join *) plan, rtoffset);
 9913                           881                 :         110978 :             break;
                                882                 :                : 
 4002 rhaas@postgresql.org      883                 :           1267 :         case T_Gather:
                                884                 :                :         case T_GatherMerge:
                                885                 :                :             {
 3252                           886                 :           1267 :                 set_upper_references(root, plan, rtoffset);
                                887                 :           1267 :                 set_param_references(root, plan);
                                888                 :                :             }
 4002                           889                 :           1267 :             break;
                                890                 :                : 
 8671 tgl@sss.pgh.pa.us         891                 :          32061 :         case T_Hash:
 2628 andres@anarazel.de        892                 :          32061 :             set_hash_references(root, plan, rtoffset);
                                893                 :          32061 :             break;
                                894                 :                : 
 1916 drowley@postgresql.o      895                 :           1532 :         case T_Memoize:
                                896                 :                :             {
                                897                 :           1532 :                 Memoize    *mplan = (Memoize *) plan;
                                898                 :                : 
                                899                 :                :                 /*
                                900                 :                :                  * Memoize does not evaluate its targetlist.  It just uses the
                                901                 :                :                  * same targetlist from its outer subnode.
                                902                 :                :                  */
 1966                           903                 :           1532 :                 set_dummy_tlist_references(plan, rtoffset);
                                904                 :                : 
 1916                           905                 :           1532 :                 mplan->param_exprs = fix_scan_list(root, mplan->param_exprs,
                                906                 :                :                                                    rtoffset,
                                907                 :                :                                                    NUM_EXEC_TLIST(plan));
 2019                           908                 :           1532 :                 break;
                                909                 :                :             }
                                910                 :                : 
 9913 tgl@sss.pgh.pa.us         911                 :          71818 :         case T_Material:
                                912                 :                :         case T_Sort:
                                913                 :                :         case T_IncrementalSort:
                                914                 :                :         case T_Unique:
                                915                 :                :         case T_SetOp:
                                916                 :                : 
                                917                 :                :             /*
                                918                 :                :              * These plan types don't actually bother to evaluate their
                                919                 :                :              * targetlists, because they just return their unmodified input
                                920                 :                :              * tuples.  Even though the targetlist won't be used by the
                                921                 :                :              * executor, we fix it up for possible use by EXPLAIN (not to
                                922                 :                :              * mention ease of debugging --- wrong varnos are very confusing).
                                923                 :                :              */
 7171                           924                 :          71818 :             set_dummy_tlist_references(plan, rtoffset);
                                925                 :                : 
                                926                 :                :             /*
                                927                 :                :              * Since these plan types don't check quals either, we should not
                                928                 :                :              * find any qual expression attached to them.
                                929                 :                :              */
 7813                           930         [ -  + ]:          71818 :             Assert(plan->qual == NIL);
 9913                           931                 :          71818 :             break;
 6209                           932                 :           6435 :         case T_LockRows:
                                933                 :                :             {
                                934                 :           6435 :                 LockRows   *splan = (LockRows *) plan;
                                935                 :                : 
                                936                 :                :                 /*
                                937                 :                :                  * Like the plan types above, LockRows doesn't evaluate its
                                938                 :                :                  * tlist or quals.  But we have to fix up the RT indexes in
                                939                 :                :                  * its rowmarks.
                                940                 :                :                  */
                                941                 :           6435 :                 set_dummy_tlist_references(plan, rtoffset);
                                942         [ -  + ]:           6435 :                 Assert(splan->plan.qual == NIL);
                                943                 :                : 
                                944   [ +  -  +  +  :          14635 :                 foreach(l, splan->rowMarks)
                                              +  + ]
                                945                 :                :                 {
 6195                           946                 :           8200 :                     PlanRowMark *rc = (PlanRowMark *) lfirst(l);
                                947                 :                : 
 6209                           948                 :           8200 :                     rc->rti += rtoffset;
                                949                 :           8200 :                     rc->prti += rtoffset;
                                950                 :                :                 }
                                951                 :                :             }
                                952                 :           6435 :             break;
 8189                           953                 :           3552 :         case T_Limit:
                                954                 :                :             {
 6906 bruce@momjian.us          955                 :           3552 :                 Limit      *splan = (Limit *) plan;
                                956                 :                : 
                                957                 :                :                 /*
                                958                 :                :                  * Like the plan types above, Limit doesn't evaluate its tlist
                                959                 :                :                  * or quals.  It does have live expressions for limit/offset,
                                960                 :                :                  * however; and those cannot contain subplan variable refs, so
                                961                 :                :                  * fix_scan_expr works for them.
                                962                 :                :                  */
 7171 tgl@sss.pgh.pa.us         963                 :           3552 :                 set_dummy_tlist_references(plan, rtoffset);
 7172                           964         [ -  + ]:           3552 :                 Assert(splan->plan.qual == NIL);
                                965                 :                : 
                                966                 :           3552 :                 splan->limitOffset =
 2206                           967                 :           3552 :                     fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
 7172                           968                 :           3552 :                 splan->limitCount =
 2206                           969                 :           3552 :                     fix_scan_expr(root, splan->limitCount, rtoffset, 1);
                                970                 :                :             }
 8189                           971                 :           3552 :             break;
 9913                           972                 :          37830 :         case T_Agg:
                                973                 :                :             {
 3760                           974                 :          37830 :                 Agg        *agg = (Agg *) plan;
                                975                 :                : 
                                976                 :                :                 /*
                                977                 :                :                  * If this node is combining partial-aggregation results, we
                                978                 :                :                  * must convert its Aggrefs to contain references to the
                                979                 :                :                  * partial-aggregate subexpressions that will be available
                                980                 :                :                  * from the child plan node.
                                981                 :                :                  */
                                982         [ +  + ]:          37830 :                 if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
                                983                 :                :                 {
                                984                 :           1238 :                     plan->targetlist = (List *)
                                985                 :           1238 :                         convert_combining_aggrefs((Node *) plan->targetlist,
                                986                 :                :                                                   NULL);
                                987                 :           1238 :                     plan->qual = (List *)
                                988                 :           1238 :                         convert_combining_aggrefs((Node *) plan->qual,
                                989                 :                :                                                   NULL);
                                990                 :                :                 }
                                991                 :                : 
                                992                 :          37830 :                 set_upper_references(root, plan, rtoffset);
                                993                 :                :             }
                                994                 :          37830 :             break;
 9913                           995                 :            226 :         case T_Group:
 5518                           996                 :            226 :             set_upper_references(root, plan, rtoffset);
 9913                           997                 :            226 :             break;
 6086                           998                 :           2498 :         case T_WindowAgg:
                                999                 :                :             {
 6072 bruce@momjian.us         1000                 :           2498 :                 WindowAgg  *wplan = (WindowAgg *) plan;
                               1001                 :                : 
                               1002                 :                :                 /*
                               1003                 :                :                  * Adjust the WindowAgg's run conditions by swapping the
                               1004                 :                :                  * WindowFuncs references out to instead reference the Var in
                               1005                 :                :                  * the scan slot so that when the executor evaluates the
                               1006                 :                :                  * runCondition, it receives the WindowFunc's value from the
                               1007                 :                :                  * slot that the result has just been stored into rather than
                               1008                 :                :                  * evaluating the WindowFunc all over again.
                               1009                 :                :                  */
 1648 drowley@postgresql.o     1010                 :           2498 :                 wplan->runCondition = set_windowagg_runcondition_references(root,
                               1011                 :                :                                                                             wplan->runCondition,
                               1012                 :                :                                                                             (Plan *) wplan);
                               1013                 :                : 
 5518 tgl@sss.pgh.pa.us        1014                 :           2498 :                 set_upper_references(root, plan, rtoffset);
                               1015                 :                : 
                               1016                 :                :                 /*
                               1017                 :                :                  * Like Limit node limit/offset expressions, WindowAgg has
                               1018                 :                :                  * frame offset expressions, which cannot contain subplan
                               1019                 :                :                  * variable refs, so fix_scan_expr works for them.
                               1020                 :                :                  */
 6086                          1021                 :           2498 :                 wplan->startOffset =
 2206                          1022                 :           2498 :                     fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
 6086                          1023                 :           2498 :                 wplan->endOffset =
 2206                          1024                 :           2498 :                     fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
 1648 drowley@postgresql.o     1025                 :           2498 :                 wplan->runCondition = fix_scan_list(root,
                               1026                 :                :                                                     wplan->runCondition,
                               1027                 :                :                                                     rtoffset,
                               1028                 :                :                                                     NUM_EXEC_TLIST(plan));
                               1029                 :           2498 :                 wplan->runConditionOrig = fix_scan_list(root,
                               1030                 :                :                                                         wplan->runConditionOrig,
                               1031                 :                :                                                         rtoffset,
                               1032                 :                :                                                         NUM_EXEC_TLIST(plan));
                               1033                 :                :             }
 6086 tgl@sss.pgh.pa.us        1034                 :           2498 :             break;
 9913                          1035                 :         151617 :         case T_Result:
                               1036                 :                :             {
 6906 bruce@momjian.us         1037                 :         151617 :                 Result     *splan = (Result *) plan;
                               1038                 :                : 
                               1039                 :                :                 /*
                               1040                 :                :                  * Result may or may not have a subplan; if not, it's more
                               1041                 :                :                  * like a scan node than an upper node.
                               1042                 :                :                  */
 7172 tgl@sss.pgh.pa.us        1043         [ +  + ]:         151617 :                 if (splan->plan.lefttree != NULL)
 5518                          1044                 :           9753 :                     set_upper_references(root, plan, rtoffset);
                               1045                 :                :                 else
                               1046                 :                :                 {
                               1047                 :                :                     int         first_child_relid;
                               1048                 :                : 
                               1049                 :                :                     /*
                               1050                 :                :                      * The tlist of a childless Result could contain
                               1051                 :                :                      * unresolved ROWID_VAR Vars, in case it's representing a
                               1052                 :                :                      * target relation which is completely empty because of
                               1053                 :                :                      * constraint exclusion.  Replace any such Vars by null
                               1054                 :                :                      * constants, as though they'd been resolved for a leaf
                               1055                 :                :                      * scan node that doesn't support them.  We could have
                               1056                 :                :                      * fix_scan_expr do this, but since the case is only
                               1057                 :                :                      * expected to occur here, it seems safer to special-case
                               1058                 :                :                      * it here and keep the assertions that ROWID_VARs
                               1059                 :                :                      * shouldn't be seen by fix_scan_expr.
                               1060                 :                :                      *
                               1061                 :                :                      * We also must handle the case where set operations have
                               1062                 :                :                      * been proven empty, resulting in a dummy Result node.
                               1063                 :                :                      * Because prepunion.c uses varno 0 for setop targetlists,
                               1064                 :                :                      * that's what we'll find here.  Replace such Vars with
                               1065                 :                :                      * Vars pointing at the Result's lowest-numbered replaced
                               1066                 :                :                      * rel, which will be its leftmost set-op child.  While we
                               1067                 :                :                      * can assume that ROWID_VARs are at top level, varno 0
                               1068                 :                :                      * Vars might be buried in coercion expressions, so that
                               1069                 :                :                      * needs a recursive traversal.  Without this, EXPLAIN
                               1070                 :                :                      * will have trouble displaying targetlists of dummy set
                               1071                 :                :                      * operations.
                               1072                 :                :                      *
                               1073                 :                :                      * Note that some Results have empty relids, leading to
                               1074                 :                :                      * first_child_relid being negative.  We assume such
                               1075                 :                :                      * Results can't contain any varno 0 Vars.
                               1076                 :                :                      */
    7                          1077                 :         141864 :                     first_child_relid = bms_next_member(splan->relids, -1);
 2021                          1078   [ +  +  +  +  :         328397 :                     foreach(l, splan->plan.targetlist)
                                              +  + ]
                               1079                 :                :                     {
                               1080                 :         186533 :                         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               1081                 :         186533 :                         Var        *var = (Var *) tle->expr;
                               1082                 :                : 
    7                          1083   [ +  -  +  +  :         186533 :                         if (var && IsA(var, Var) && var->varno == ROWID_VAR)
                                              +  + ]
                               1084                 :             64 :                             tle->expr = (Expr *) makeNullConst(var->vartype,
                               1085                 :                :                                                                var->vartypmod,
                               1086                 :                :                                                                var->varcollid);
                               1087         [ +  + ]:         186469 :                         else if (first_child_relid > 0)
                               1088                 :         186069 :                             tle->expr = (Expr *)
                               1089                 :         186069 :                                 fix_dummy_setop_vars_mutator((Node *) tle->expr,
                               1090                 :                :                                                              &first_child_relid);
                               1091                 :                :                     }
                               1092                 :                : 
 7172                          1093                 :         141864 :                     splan->plan.targetlist =
 2206                          1094                 :         141864 :                         fix_scan_list(root, splan->plan.targetlist,
                               1095                 :                :                                       rtoffset, NUM_EXEC_TLIST(plan));
 7172                          1096                 :         141864 :                     splan->plan.qual =
 2206                          1097                 :         141864 :                         fix_scan_list(root, splan->plan.qual,
                               1098                 :                :                                       rtoffset, NUM_EXEC_QUAL(plan));
                               1099                 :                :                 }
                               1100                 :                :                 /* resconstantqual can't contain any subplan variable refs */
 7172                          1101                 :         151617 :                 splan->resconstantqual =
 2206                          1102                 :         151617 :                     fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
                               1103                 :                :                 /* adjust the relids set */
  384 rhaas@postgresql.org     1104                 :         151617 :                 splan->relids = offset_relid_set(splan->relids, rtoffset);
                               1105                 :                :             }
 9913 tgl@sss.pgh.pa.us        1106                 :         151617 :             break;
 3554 andres@anarazel.de       1107                 :          10158 :         case T_ProjectSet:
                               1108                 :          10158 :             set_upper_references(root, plan, rtoffset);
                               1109                 :          10158 :             break;
 6211 tgl@sss.pgh.pa.us        1110                 :          60623 :         case T_ModifyTable:
                               1111                 :                :             {
                               1112                 :          60623 :                 ModifyTable *splan = (ModifyTable *) plan;
 1659 alvherre@alvh.no-ip.     1113                 :          60623 :                 Plan       *subplan = outerPlan(splan);
                               1114                 :                : 
 5283 tgl@sss.pgh.pa.us        1115         [ -  + ]:          60623 :                 Assert(splan->plan.targetlist == NIL);
 6211                          1116         [ -  + ]:          60623 :                 Assert(splan->plan.qual == NIL);
                               1117                 :                : 
 4403 sfrost@snowman.net       1118                 :          60623 :                 splan->withCheckOptionLists =
 2206 tgl@sss.pgh.pa.us        1119                 :          60623 :                     fix_scan_list(root, splan->withCheckOptionLists,
                               1120                 :                :                                   rtoffset, 1);
                               1121                 :                : 
 5283                          1122         [ +  + ]:          60623 :                 if (splan->returningLists)
                               1123                 :                :                 {
                               1124                 :           2603 :                     List       *newRL = NIL;
                               1125                 :                :                     ListCell   *lcrl,
                               1126                 :                :                                *lcrr;
                               1127                 :                : 
                               1128                 :                :                     /*
                               1129                 :                :                      * Pass each per-resultrel returningList through
                               1130                 :                :                      * set_returning_clause_references().
                               1131                 :                :                      */
                               1132         [ -  + ]:           2603 :                     Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
 2021                          1133   [ +  -  +  +  :           5510 :                     forboth(lcrl, splan->returningLists,
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               1134                 :                :                             lcrr, splan->resultRelations)
                               1135                 :                :                     {
 5237 bruce@momjian.us         1136                 :           2907 :                         List       *rlist = (List *) lfirst(lcrl);
                               1137                 :           2907 :                         Index       resultrel = lfirst_int(lcrr);
                               1138                 :                : 
 5283 tgl@sss.pgh.pa.us        1139                 :           2907 :                         rlist = set_returning_clause_references(root,
                               1140                 :                :                                                                 rlist,
                               1141                 :                :                                                                 subplan,
                               1142                 :                :                                                                 resultrel,
                               1143                 :                :                                                                 rtoffset);
                               1144                 :           2907 :                         newRL = lappend(newRL, rlist);
                               1145                 :                :                     }
                               1146                 :           2603 :                     splan->returningLists = newRL;
                               1147                 :                : 
                               1148                 :                :                     /*
                               1149                 :                :                      * Set up the visible plan targetlist as being the same as
                               1150                 :                :                      * the first RETURNING list.  This is mostly for the use
                               1151                 :                :                      * of EXPLAIN; the executor won't execute that targetlist,
                               1152                 :                :                      * although it does use it to prepare the node's result
                               1153                 :                :                      * tuple slot.  We postpone this step until here so that
                               1154                 :                :                      * we don't have to do set_returning_clause_references()
                               1155                 :                :                      * twice on identical targetlists.
                               1156                 :                :                      */
                               1157                 :           2603 :                     splan->plan.targetlist = copyObject(linitial(newRL));
                               1158                 :                :                 }
                               1159                 :                : 
                               1160                 :                :                 /*
                               1161                 :                :                  * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
                               1162                 :                :                  * join', where the inner side is the EXCLUDED tuple.
                               1163                 :                :                  * Therefore use fix_join_expr to setup the relevant variables
                               1164                 :                :                  * to INNER_VAR. We explicitly don't create any OUTER_VARs as
                               1165                 :                :                  * those are already used by RETURNING and it seems better to
                               1166                 :                :                  * be non-conflicting.
                               1167                 :                :                  */
  242 dean.a.rasheed@gmail     1168         [ +  + ]:          60623 :                 if (splan->onConflictAction == ONCONFLICT_UPDATE ||
                               1169         [ +  + ]:          59725 :                     splan->onConflictAction == ONCONFLICT_SELECT)
                               1170                 :                :                 {
                               1171                 :                :                     indexed_tlist *itlist;
                               1172                 :                : 
 4175 andres@anarazel.de       1173                 :           1211 :                     itlist = build_tlist_index(splan->exclRelTlist);
                               1174                 :                : 
                               1175                 :           1211 :                     splan->onConflictSet =
                               1176                 :           2422 :                         fix_join_expr(root, splan->onConflictSet,
                               1177                 :                :                                       NULL, itlist,
                               1178                 :           1211 :                                       linitial_int(splan->resultRelations),
 1351 tgl@sss.pgh.pa.us        1179                 :           1211 :                                       rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
                               1180                 :                : 
 4175 andres@anarazel.de       1181                 :           1211 :                     splan->onConflictWhere = (Node *)
                               1182                 :           2422 :                         fix_join_expr(root, (List *) splan->onConflictWhere,
                               1183                 :                :                                       NULL, itlist,
                               1184                 :           1211 :                                       linitial_int(splan->resultRelations),
 1351 tgl@sss.pgh.pa.us        1185                 :           1211 :                                       rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
                               1186                 :                : 
 4110 andres@anarazel.de       1187                 :           1211 :                     pfree(itlist);
                               1188                 :                : 
 4170                          1189                 :           1211 :                     splan->exclRelTlist =
 2206 tgl@sss.pgh.pa.us        1190                 :           1211 :                         fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
                               1191                 :                :                 }
                               1192                 :                : 
                               1193                 :                :                 /*
                               1194                 :                :                  * The MERGE statement produces the target rows by performing
                               1195                 :                :                  * a right join between the target relation and the source
                               1196                 :                :                  * relation (which could be a plain relation or a subquery).
                               1197                 :                :                  * The INSERT and UPDATE actions of the MERGE statement
                               1198                 :                :                  * require access to the columns from the source relation. We
                               1199                 :                :                  * arrange things so that the source relation attributes are
                               1200                 :                :                  * available as INNER_VAR and the target relation attributes
                               1201                 :                :                  * are available from the scan tuple.
                               1202                 :                :                  */
 1659 alvherre@alvh.no-ip.     1203         [ +  + ]:          60623 :                 if (splan->mergeActionLists != NIL)
                               1204                 :                :                 {
  926 dean.a.rasheed@gmail     1205                 :           1489 :                     List       *newMJC = NIL;
                               1206                 :                :                     ListCell   *lca,
                               1207                 :                :                                *lcj,
                               1208                 :                :                                *lcr;
                               1209                 :                : 
                               1210                 :                :                     /*
                               1211                 :                :                      * Fix the targetList of individual action nodes so that
                               1212                 :                :                      * the so-called "source relation" Vars are referenced as
                               1213                 :                :                      * INNER_VAR.  Note that for this to work correctly during
                               1214                 :                :                      * execution, the ecxt_innertuple must be set to the tuple
                               1215                 :                :                      * obtained by executing the subplan, which is what
                               1216                 :                :                      * constitutes the "source relation".
                               1217                 :                :                      *
                               1218                 :                :                      * We leave the Vars from the result relation (i.e. the
                               1219                 :                :                      * target relation) unchanged i.e. those Vars would be
                               1220                 :                :                      * picked from the scan slot. So during execution, we must
                               1221                 :                :                      * ensure that ecxt_scantuple is setup correctly to refer
                               1222                 :                :                      * to the tuple from the target relation.
                               1223                 :                :                      */
                               1224                 :                :                     indexed_tlist *itlist;
                               1225                 :                : 
 1659 alvherre@alvh.no-ip.     1226                 :           1489 :                     itlist = build_tlist_index(subplan->targetlist);
                               1227                 :                : 
  926 dean.a.rasheed@gmail     1228   [ +  -  +  +  :           3212 :                     forthree(lca, splan->mergeActionLists,
                                     +  -  +  +  +  
                                     -  +  +  +  +  
                                     +  -  +  -  +  
                                                 + ]
                               1229                 :                :                              lcj, splan->mergeJoinConditions,
                               1230                 :                :                              lcr, splan->resultRelations)
                               1231                 :                :                     {
 1659 alvherre@alvh.no-ip.     1232                 :           1723 :                         List       *mergeActionList = lfirst(lca);
  926 dean.a.rasheed@gmail     1233                 :           1723 :                         Node       *mergeJoinCondition = lfirst(lcj);
 1659 alvherre@alvh.no-ip.     1234                 :           1723 :                         Index       resultrel = lfirst_int(lcr);
                               1235                 :                : 
                               1236   [ +  -  +  +  :           4597 :                         foreach(l, mergeActionList)
                                              +  + ]
                               1237                 :                :                         {
                               1238                 :           2874 :                             MergeAction *action = (MergeAction *) lfirst(l);
                               1239                 :                : 
                               1240                 :                :                             /* Fix targetList of each action. */
                               1241                 :           2874 :                             action->targetList = fix_join_expr(root,
                               1242                 :                :                                                                action->targetList,
                               1243                 :                :                                                                NULL, itlist,
                               1244                 :                :                                                                resultrel,
                               1245                 :                :                                                                rtoffset,
                               1246                 :                :                                                                NRM_EQUAL,
                               1247                 :                :                                                                NUM_EXEC_TLIST(plan));
                               1248                 :                : 
                               1249                 :                :                             /* Fix quals too. */
                               1250                 :           2874 :                             action->qual = (Node *) fix_join_expr(root,
                               1251                 :           2874 :                                                                   (List *) action->qual,
                               1252                 :                :                                                                   NULL, itlist,
                               1253                 :                :                                                                   resultrel,
                               1254                 :                :                                                                   rtoffset,
                               1255                 :                :                                                                   NRM_EQUAL,
                               1256                 :           2874 :                                                                   NUM_EXEC_QUAL(plan));
                               1257                 :                :                         }
                               1258                 :                : 
                               1259                 :                :                         /* Fix join condition too. */
                               1260                 :                :                         mergeJoinCondition = (Node *)
  926 dean.a.rasheed@gmail     1261                 :           1723 :                             fix_join_expr(root,
                               1262                 :                :                                           (List *) mergeJoinCondition,
                               1263                 :                :                                           NULL, itlist,
                               1264                 :                :                                           resultrel,
                               1265                 :                :                                           rtoffset,
                               1266                 :                :                                           NRM_EQUAL,
                               1267                 :           1723 :                                           NUM_EXEC_QUAL(plan));
                               1268                 :           1723 :                         newMJC = lappend(newMJC, mergeJoinCondition);
                               1269                 :                :                     }
                               1270                 :           1489 :                     splan->mergeJoinConditions = newMJC;
                               1271                 :                :                 }
                               1272                 :                : 
 4255 tgl@sss.pgh.pa.us        1273                 :          60623 :                 splan->nominalRelation += rtoffset;
 2927                          1274         [ +  + ]:          60623 :                 if (splan->rootRelation)
                               1275                 :           2225 :                     splan->rootRelation += rtoffset;
 4175 andres@anarazel.de       1276                 :          60623 :                 splan->exclRelRTI += rtoffset;
                               1277                 :                : 
 6211 tgl@sss.pgh.pa.us        1278   [ +  -  +  +  :         123250 :                 foreach(l, splan->resultRelations)
                                              +  + ]
                               1279                 :                :                 {
                               1280                 :          62627 :                     lfirst_int(l) += rtoffset;
                               1281                 :                :                 }
 6195                          1282   [ +  +  +  +  :          63014 :                 foreach(l, splan->rowMarks)
                                              +  + ]
                               1283                 :                :                 {
                               1284                 :           2391 :                     PlanRowMark *rc = (PlanRowMark *) lfirst(l);
                               1285                 :                : 
                               1286                 :           2391 :                     rc->rti += rtoffset;
                               1287                 :           2391 :                     rc->prti += rtoffset;
                               1288                 :                :                 }
                               1289                 :                : 
                               1290                 :                :                 /*
                               1291                 :                :                  * Append this ModifyTable node's final result relation RT
                               1292                 :                :                  * index(es) to the global list for the plan.
                               1293                 :                :                  */
 5518                          1294                 :         121246 :                 root->glob->resultRelations =
                               1295                 :          60623 :                     list_concat(root->glob->resultRelations,
 2618                          1296                 :          60623 :                                 splan->resultRelations);
 2927                          1297         [ +  + ]:          60623 :                 if (splan->rootRelation)
                               1298                 :                :                 {
 2190 heikki.linnakangas@i     1299                 :           2225 :                     root->glob->resultRelations =
                               1300                 :           2225 :                         lappend_int(root->glob->resultRelations,
 2927 tgl@sss.pgh.pa.us        1301                 :           2225 :                                     splan->rootRelation);
                               1302                 :                :                 }
                               1303                 :                :             }
 6211                          1304                 :          60623 :             break;
 9913                          1305                 :          19012 :         case T_Append:
                               1306                 :                :             /* Needs special treatment, see comments below */
 2758                          1307                 :          19012 :             return set_append_references(root,
                               1308                 :                :                                          (Append *) plan,
                               1309                 :                :                                          rtoffset);
 5842                          1310                 :            481 :         case T_MergeAppend:
                               1311                 :                :             /* Needs special treatment, see comments below */
 2758                          1312                 :            481 :             return set_mergeappend_references(root,
                               1313                 :                :                                               (MergeAppend *) plan,
                               1314                 :                :                                               rtoffset);
 6582                          1315                 :            692 :         case T_RecursiveUnion:
                               1316                 :                :             /* This doesn't evaluate targetlist or check quals either */
                               1317                 :            692 :             set_dummy_tlist_references(plan, rtoffset);
                               1318         [ -  + ]:            692 :             Assert(plan->qual == NIL);
                               1319                 :            692 :             break;
 7846                          1320                 :            167 :         case T_BitmapAnd:
                               1321                 :                :             {
 6906 bruce@momjian.us         1322                 :            167 :                 BitmapAnd  *splan = (BitmapAnd *) plan;
                               1323                 :                : 
                               1324                 :                :                 /* BitmapAnd works like Append, but has no tlist */
 7172 tgl@sss.pgh.pa.us        1325         [ -  + ]:            167 :                 Assert(splan->plan.targetlist == NIL);
                               1326         [ -  + ]:            167 :                 Assert(splan->plan.qual == NIL);
                               1327   [ +  -  +  +  :            501 :                 foreach(l, splan->bitmapplans)
                                              +  + ]
                               1328                 :                :                 {
 5518                          1329                 :            334 :                     lfirst(l) = set_plan_refs(root,
 7172                          1330                 :            334 :                                               (Plan *) lfirst(l),
                               1331                 :                :                                               rtoffset);
                               1332                 :                :                 }
                               1333                 :                :             }
 7846                          1334                 :            167 :             break;
                               1335                 :            298 :         case T_BitmapOr:
                               1336                 :                :             {
 6906 bruce@momjian.us         1337                 :            298 :                 BitmapOr   *splan = (BitmapOr *) plan;
                               1338                 :                : 
                               1339                 :                :                 /* BitmapOr works like Append, but has no tlist */
 7172 tgl@sss.pgh.pa.us        1340         [ -  + ]:            298 :                 Assert(splan->plan.targetlist == NIL);
                               1341         [ -  + ]:            298 :                 Assert(splan->plan.qual == NIL);
                               1342   [ +  -  +  +  :            899 :                 foreach(l, splan->bitmapplans)
                                              +  + ]
                               1343                 :                :                 {
 5518                          1344                 :            601 :                     lfirst(l) = set_plan_refs(root,
 7172                          1345                 :            601 :                                               (Plan *) lfirst(l),
                               1346                 :                :                                               rtoffset);
                               1347                 :                :                 }
                               1348                 :                :             }
 7846                          1349                 :            298 :             break;
 9913 tgl@sss.pgh.pa.us        1350                 :UBC           0 :         default:
 8480                          1351         [ #  # ]:              0 :             elog(ERROR, "unrecognized node type: %d",
                               1352                 :                :                  (int) nodeTag(plan));
                               1353                 :                :             break;
                               1354                 :                :     }
                               1355                 :                : 
                               1356                 :                :     /*
                               1357                 :                :      * Now recurse into child plans, if any
                               1358                 :                :      *
                               1359                 :                :      * NOTE: it is essential that we recurse into child plans AFTER we set
                               1360                 :                :      * subplan references in this plan's tlist and quals.  If we did the
                               1361                 :                :      * reference-adjustments bottom-up, then we would fail to match this
                               1362                 :                :      * plan's var nodes against the already-modified nodes of the children.
                               1363                 :                :      */
 5518 tgl@sss.pgh.pa.us        1364                 :CBC      853501 :     plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
                               1365                 :         853501 :     plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
                               1366                 :                : 
 7813                          1367                 :         853501 :     return plan;
                               1368                 :                : }
                               1369                 :                : 
                               1370                 :                : /*
                               1371                 :                :  * set_indexonlyscan_references
                               1372                 :                :  *      Do set_plan_references processing on an IndexOnlyScan
                               1373                 :                :  *
                               1374                 :                :  * This is unlike the handling of a plain IndexScan because we have to
                               1375                 :                :  * convert Vars referencing the heap into Vars referencing the index.
                               1376                 :                :  * We can use the fix_upper_expr machinery for that, by working from a
                               1377                 :                :  * targetlist describing the index columns.
                               1378                 :                :  */
                               1379                 :                : static Plan *
 5480                          1380                 :          11423 : set_indexonlyscan_references(PlannerInfo *root,
                               1381                 :                :                              IndexOnlyScan *plan,
                               1382                 :                :                              int rtoffset)
                               1383                 :                : {
                               1384                 :                :     indexed_tlist *index_itlist;
                               1385                 :                :     List       *stripped_indextlist;
                               1386                 :                :     ListCell   *lc;
                               1387                 :                : 
                               1388                 :                :     /*
                               1389                 :                :      * Vars in the plan node's targetlist, qual, and recheckqual must only
                               1390                 :                :      * reference columns that the index AM can actually return.  To ensure
                               1391                 :                :      * this, remove non-returnable columns (which are marked as resjunk) from
                               1392                 :                :      * the indexed tlist.  We can just drop them because the indexed_tlist
                               1393                 :                :      * machinery pays attention to TLE resnos, not physical list position.
                               1394                 :                :      */
 1743                          1395                 :          11423 :     stripped_indextlist = NIL;
                               1396   [ +  -  +  +  :          27475 :     foreach(lc, plan->indextlist)
                                              +  + ]
                               1397                 :                :     {
                               1398                 :          16052 :         TargetEntry *indextle = (TargetEntry *) lfirst(lc);
                               1399                 :                : 
                               1400         [ +  + ]:          16052 :         if (!indextle->resjunk)
                               1401                 :          16010 :             stripped_indextlist = lappend(stripped_indextlist, indextle);
                               1402                 :                :     }
                               1403                 :                : 
                               1404                 :          11423 :     index_itlist = build_tlist_index(stripped_indextlist);
                               1405                 :                : 
 5480                          1406                 :          11423 :     plan->scan.scanrelid += rtoffset;
                               1407                 :          11423 :     plan->scan.plan.targetlist = (List *)
                               1408                 :          11423 :         fix_upper_expr(root,
                               1409                 :          11423 :                        (Node *) plan->scan.plan.targetlist,
                               1410                 :                :                        index_itlist,
                               1411                 :                :                        INDEX_VAR,
                               1412                 :                :                        rtoffset,
                               1413                 :                :                        NUM_EXEC_TLIST((Plan *) plan));
                               1414                 :          11423 :     plan->scan.plan.qual = (List *)
                               1415                 :          11423 :         fix_upper_expr(root,
                               1416                 :          11423 :                        (Node *) plan->scan.plan.qual,
                               1417                 :                :                        index_itlist,
                               1418                 :                :                        INDEX_VAR,
                               1419                 :                :                        rtoffset,
 2206                          1420                 :          11423 :                        NUM_EXEC_QUAL((Plan *) plan));
 1743                          1421                 :          11423 :     plan->recheckqual = (List *)
                               1422                 :          11423 :         fix_upper_expr(root,
                               1423                 :          11423 :                        (Node *) plan->recheckqual,
                               1424                 :                :                        index_itlist,
                               1425                 :                :                        INDEX_VAR,
                               1426                 :                :                        rtoffset,
                               1427                 :          11423 :                        NUM_EXEC_QUAL((Plan *) plan));
                               1428                 :                :     /* indexqual is already transformed to reference index columns */
 2206                          1429                 :          11423 :     plan->indexqual = fix_scan_list(root, plan->indexqual,
                               1430                 :                :                                     rtoffset, 1);
                               1431                 :                :     /* indexorderby is already transformed to reference index columns */
                               1432                 :          11423 :     plan->indexorderby = fix_scan_list(root, plan->indexorderby,
                               1433                 :                :                                        rtoffset, 1);
                               1434                 :                :     /* indextlist must NOT be transformed to reference index columns */
                               1435                 :          11423 :     plan->indextlist = fix_scan_list(root, plan->indextlist,
                               1436                 :                :                                      rtoffset, NUM_EXEC_TLIST((Plan *) plan));
                               1437                 :                : 
 5480                          1438                 :          11423 :     pfree(index_itlist);
                               1439                 :                : 
                               1440                 :          11423 :     return (Plan *) plan;
                               1441                 :                : }
                               1442                 :                : 
                               1443                 :                : /*
                               1444                 :                :  * set_subqueryscan_references
                               1445                 :                :  *      Do set_plan_references processing on a SubqueryScan
                               1446                 :                :  *
                               1447                 :                :  * We try to strip out the SubqueryScan entirely; if we can't, we have
                               1448                 :                :  * to do the normal processing on it.
                               1449                 :                :  */
                               1450                 :                : static Plan *
 5518                          1451                 :          29625 : set_subqueryscan_references(PlannerInfo *root,
                               1452                 :                :                             SubqueryScan *plan,
                               1453                 :                :                             int rtoffset)
                               1454                 :                : {
                               1455                 :                :     RelOptInfo *rel;
                               1456                 :                :     Plan       *result;
                               1457                 :                : 
                               1458                 :                :     /* Need to look up the subquery's RelOptInfo, since we need its subroot */
                               1459                 :          29625 :     rel = find_base_rel(root, plan->scan.scanrelid);
                               1460                 :                : 
                               1461                 :                :     /* Recursively process the subplan */
                               1462                 :          29625 :     plan->subplan = set_plan_references(rel->subroot, plan->subplan);
                               1463                 :                : 
 7813                          1464         [ +  + ]:          29625 :     if (trivial_subqueryscan(plan))
                               1465                 :                :     {
                               1466                 :                :         Index       scanrelid;
                               1467                 :                : 
                               1468                 :                :         /*
                               1469                 :                :          * We can omit the SubqueryScan node and just pull up the subplan.
                               1470                 :                :          */
 2758                          1471                 :          14610 :         result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
                               1472                 :                : 
                               1473                 :                :         /* Remember that we removed a SubqueryScan */
  244 rhaas@postgresql.org     1474                 :          14610 :         scanrelid = plan->scan.scanrelid + rtoffset;
                               1475                 :          14610 :         record_elided_node(root->glob, plan->subplan->plan_node_id,
                               1476                 :                :                            T_SubqueryScan, bms_make_singleton(scanrelid),
                               1477                 :                :                            NIL);
                               1478                 :                :     }
                               1479                 :                :     else
                               1480                 :                :     {
                               1481                 :                :         /*
                               1482                 :                :          * Keep the SubqueryScan node.  We have to do the processing that
                               1483                 :                :          * set_plan_references would otherwise have done on it.  Notice we do
                               1484                 :                :          * not do set_upper_references() here, because a SubqueryScan will
                               1485                 :                :          * always have been created with correct references to its subplan's
                               1486                 :                :          * outputs to begin with.
                               1487                 :                :          */
 7172 tgl@sss.pgh.pa.us        1488                 :          15015 :         plan->scan.scanrelid += rtoffset;
                               1489                 :          15015 :         plan->scan.plan.targetlist =
 2206                          1490                 :          15015 :             fix_scan_list(root, plan->scan.plan.targetlist,
                               1491                 :                :                           rtoffset, NUM_EXEC_TLIST((Plan *) plan));
 7172                          1492                 :          15015 :         plan->scan.plan.qual =
 2206                          1493                 :          15015 :             fix_scan_list(root, plan->scan.plan.qual,
                               1494                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) plan));
                               1495                 :                : 
 7172                          1496                 :          15015 :         result = (Plan *) plan;
                               1497                 :                :     }
                               1498                 :                : 
 7813                          1499                 :          29625 :     return result;
                               1500                 :                : }
                               1501                 :                : 
                               1502                 :                : /*
                               1503                 :                :  * trivial_subqueryscan
                               1504                 :                :  *      Detect whether a SubqueryScan can be deleted from the plan tree.
                               1505                 :                :  *
                               1506                 :                :  * We can delete it if it has no qual to check and the targetlist just
                               1507                 :                :  * regurgitates the output of the child plan.
                               1508                 :                :  *
                               1509                 :                :  * This can be called from mark_async_capable_plan(), a helper function for
                               1510                 :                :  * create_append_plan(), before set_subqueryscan_references(), to determine
                               1511                 :                :  * triviality of a SubqueryScan that is a child of an Append node.  So we
                               1512                 :                :  * cache the result in the SubqueryScan node to avoid repeated computation.
                               1513                 :                :  *
                               1514                 :                :  * Note: when called from mark_async_capable_plan(), we determine the result
                               1515                 :                :  * before running finalize_plan() on the SubqueryScan node (if needed) and
                               1516                 :                :  * set_plan_references() on the subplan tree, but this would be safe, because
                               1517                 :                :  * 1) finalize_plan() doesn't modify the tlist or quals for the SubqueryScan
                               1518                 :                :  *    node (or that for any plan node in the subplan tree), and
                               1519                 :                :  * 2) set_plan_references() modifies the tlist for every plan node in the
                               1520                 :                :  *    subplan tree, but keeps const/resjunk columns as const/resjunk ones and
                               1521                 :                :  *    preserves the length and order of the tlist, and
                               1522                 :                :  * 3) set_plan_references() might delete the topmost plan node like an Append
                               1523                 :                :  *    or MergeAppend from the subplan tree and pull up the child plan node,
                               1524                 :                :  *    but in that case, the tlist for the child plan node exactly matches the
                               1525                 :                :  *    parent.
                               1526                 :                :  */
                               1527                 :                : bool
                               1528                 :          38918 : trivial_subqueryscan(SubqueryScan *plan)
                               1529                 :                : {
                               1530                 :                :     int         attrno;
                               1531                 :                :     ListCell   *lp,
                               1532                 :                :                *lc;
                               1533                 :                : 
                               1534                 :                :     /* We might have detected this already; in which case reuse the result */
 1650 efujita@postgresql.o     1535         [ +  + ]:          38918 :     if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
                               1536                 :           3805 :         return true;
                               1537         [ +  + ]:          35113 :     if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
                               1538                 :           5488 :         return false;
                               1539         [ -  + ]:          29625 :     Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
                               1540                 :                :     /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
                               1541                 :          29625 :     plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
                               1542                 :                : 
 7813 tgl@sss.pgh.pa.us        1543         [ +  + ]:          29625 :     if (plan->scan.plan.qual != NIL)
                               1544                 :           1090 :         return false;
                               1545                 :                : 
 7707                          1546         [ +  + ]:          57070 :     if (list_length(plan->scan.plan.targetlist) !=
                               1547                 :          28535 :         list_length(plan->subplan->targetlist))
                               1548                 :           7538 :         return false;           /* tlists not same length */
                               1549                 :                : 
 7813                          1550                 :          20997 :     attrno = 1;
                               1551   [ +  +  +  +  :          64849 :     forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
                                     +  +  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               1552                 :                :     {
                               1553                 :          50239 :         TargetEntry *ptle = (TargetEntry *) lfirst(lp);
                               1554                 :          50239 :         TargetEntry *ctle = (TargetEntry *) lfirst(lc);
                               1555                 :                : 
                               1556         [ +  + ]:          50239 :         if (ptle->resjunk != ctle->resjunk)
                               1557                 :           6387 :             return false;       /* tlist doesn't match junk status */
                               1558                 :                : 
                               1559                 :                :         /*
                               1560                 :                :          * We accept either a Var referencing the corresponding element of the
                               1561                 :                :          * subplan tlist, or a Const equaling the subplan element. See
                               1562                 :                :          * generate_setop_tlist() for motivation.
                               1563                 :                :          */
 7350                          1564   [ +  -  +  + ]:          50219 :         if (ptle->expr && IsA(ptle->expr, Var))
                               1565                 :          42240 :         {
 7313 bruce@momjian.us         1566                 :          42400 :             Var        *var = (Var *) ptle->expr;
                               1567                 :                : 
 7350 tgl@sss.pgh.pa.us        1568         [ -  + ]:          42400 :             Assert(var->varno == plan->scan.scanrelid);
                               1569         [ -  + ]:          42400 :             Assert(var->varlevelsup == 0);
                               1570         [ +  + ]:          42400 :             if (var->varattno != attrno)
                               1571                 :            160 :                 return false;   /* out of order */
                               1572                 :                :         }
                               1573   [ +  -  +  + ]:           7819 :         else if (ptle->expr && IsA(ptle->expr, Const))
                               1574                 :                :         {
                               1575         [ +  + ]:           6921 :             if (!equal(ptle->expr, ctle->expr))
                               1576                 :           5309 :                 return false;
                               1577                 :                :         }
                               1578                 :                :         else
                               1579                 :            898 :             return false;
                               1580                 :                : 
 7813                          1581                 :          43852 :         attrno++;
                               1582                 :                :     }
                               1583                 :                : 
                               1584                 :                :     /* Re-mark the SubqueryScan as deletable from the plan tree */
 1650 efujita@postgresql.o     1585                 :          14610 :     plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
                               1586                 :                : 
 7813 tgl@sss.pgh.pa.us        1587                 :          14610 :     return true;
                               1588                 :                : }
                               1589                 :                : 
                               1590                 :                : /*
                               1591                 :                :  * clean_up_removed_plan_level
                               1592                 :                :  *      Do necessary cleanup when we strip out a SubqueryScan, Append, etc
                               1593                 :                :  *
                               1594                 :                :  * We are dropping the "parent" plan in favor of returning just its "child".
                               1595                 :                :  * A few small tweaks are needed.
                               1596                 :                :  */
                               1597                 :                : static Plan *
 2758                          1598                 :          19164 : clean_up_removed_plan_level(Plan *parent, Plan *child)
                               1599                 :                : {
                               1600                 :                :     /*
                               1601                 :                :      * We have to be sure we don't lose any initplans, so move any that were
                               1602                 :                :      * attached to the parent plan to the child.  If any are parallel-unsafe,
                               1603                 :                :      * the child is no longer parallel-safe.  As a cosmetic matter, also add
                               1604                 :                :      * the initplans' run costs to the child's costs.
                               1605                 :                :      */
 1279                          1606         [ +  + ]:          19164 :     if (parent->initPlan)
                               1607                 :                :     {
                               1608                 :                :         Cost        initplan_cost;
                               1609                 :                :         bool        unsafe_initplans;
                               1610                 :                : 
 1187                          1611                 :             35 :         SS_compute_initplan_cost(parent->initPlan,
                               1612                 :                :                                  &initplan_cost, &unsafe_initplans);
                               1613                 :             35 :         child->startup_cost += initplan_cost;
                               1614                 :             35 :         child->total_cost += initplan_cost;
                               1615         [ +  + ]:             35 :         if (unsafe_initplans)
                               1616                 :             15 :             child->parallel_safe = false;
                               1617                 :                : 
                               1618                 :                :         /*
                               1619                 :                :          * Attach plans this way so that parent's initplans are processed
                               1620                 :                :          * before any pre-existing initplans of the child.  Probably doesn't
                               1621                 :                :          * matter, but let's preserve the ordering just in case.
                               1622                 :                :          */
                               1623                 :             35 :         child->initPlan = list_concat(parent->initPlan,
                               1624                 :             35 :                                       child->initPlan);
                               1625                 :                :     }
                               1626                 :                : 
                               1627                 :                :     /*
                               1628                 :                :      * We also have to transfer the parent's column labeling info into the
                               1629                 :                :      * child, else columns sent to client will be improperly labeled if this
                               1630                 :                :      * is the topmost plan level.  resjunk and so on may be important too.
                               1631                 :                :      */
 2758                          1632                 :          19164 :     apply_tlist_labeling(child->targetlist, parent->targetlist);
                               1633                 :                : 
                               1634                 :          19164 :     return child;
                               1635                 :                : }
                               1636                 :                : 
                               1637                 :                : /*
                               1638                 :                :  * set_foreignscan_references
                               1639                 :                :  *     Do set_plan_references processing on a ForeignScan
                               1640                 :                :  */
                               1641                 :                : static void
 4173                          1642                 :           1115 : set_foreignscan_references(PlannerInfo *root,
                               1643                 :                :                            ForeignScan *fscan,
                               1644                 :                :                            int rtoffset)
                               1645                 :                : {
                               1646                 :                :     /* Adjust scanrelid if it's valid */
                               1647         [ +  + ]:           1115 :     if (fscan->scan.scanrelid > 0)
                               1648                 :            798 :         fscan->scan.scanrelid += rtoffset;
                               1649                 :                : 
                               1650   [ +  +  +  + ]:           1115 :     if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
                               1651                 :            317 :     {
                               1652                 :                :         /*
                               1653                 :                :          * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
                               1654                 :                :          * foreign scan tuple
                               1655                 :                :          */
                               1656                 :            317 :         indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
                               1657                 :                : 
                               1658                 :            317 :         fscan->scan.plan.targetlist = (List *)
                               1659                 :            317 :             fix_upper_expr(root,
                               1660                 :            317 :                            (Node *) fscan->scan.plan.targetlist,
                               1661                 :                :                            itlist,
                               1662                 :                :                            INDEX_VAR,
                               1663                 :                :                            rtoffset,
                               1664                 :                :                            NUM_EXEC_TLIST((Plan *) fscan));
                               1665                 :            317 :         fscan->scan.plan.qual = (List *)
                               1666                 :            317 :             fix_upper_expr(root,
                               1667                 :            317 :                            (Node *) fscan->scan.plan.qual,
                               1668                 :                :                            itlist,
                               1669                 :                :                            INDEX_VAR,
                               1670                 :                :                            rtoffset,
 2206                          1671                 :            317 :                            NUM_EXEC_QUAL((Plan *) fscan));
 4173                          1672                 :            317 :         fscan->fdw_exprs = (List *)
                               1673                 :            317 :             fix_upper_expr(root,
                               1674                 :            317 :                            (Node *) fscan->fdw_exprs,
                               1675                 :                :                            itlist,
                               1676                 :                :                            INDEX_VAR,
                               1677                 :                :                            rtoffset,
 2206                          1678                 :            317 :                            NUM_EXEC_QUAL((Plan *) fscan));
 3981 rhaas@postgresql.org     1679                 :            317 :         fscan->fdw_recheck_quals = (List *)
                               1680                 :            317 :             fix_upper_expr(root,
                               1681                 :            317 :                            (Node *) fscan->fdw_recheck_quals,
                               1682                 :                :                            itlist,
                               1683                 :                :                            INDEX_VAR,
                               1684                 :                :                            rtoffset,
 2206 tgl@sss.pgh.pa.us        1685                 :            317 :                            NUM_EXEC_QUAL((Plan *) fscan));
 4173                          1686                 :            317 :         pfree(itlist);
                               1687                 :                :         /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
                               1688                 :            317 :         fscan->fdw_scan_tlist =
 2206                          1689                 :            317 :             fix_scan_list(root, fscan->fdw_scan_tlist,
                               1690                 :                :                           rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
                               1691                 :                :     }
                               1692                 :                :     else
                               1693                 :                :     {
                               1694                 :                :         /*
                               1695                 :                :          * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
                               1696                 :                :          * way
                               1697                 :                :          */
 4173                          1698                 :            798 :         fscan->scan.plan.targetlist =
 2206                          1699                 :            798 :             fix_scan_list(root, fscan->scan.plan.targetlist,
                               1700                 :                :                           rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
 4173                          1701                 :            798 :         fscan->scan.plan.qual =
 2206                          1702                 :            798 :             fix_scan_list(root, fscan->scan.plan.qual,
                               1703                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
 4173                          1704                 :            798 :         fscan->fdw_exprs =
 2206                          1705                 :            798 :             fix_scan_list(root, fscan->fdw_exprs,
                               1706                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
 4015 rhaas@postgresql.org     1707                 :            798 :         fscan->fdw_recheck_quals =
 2206 tgl@sss.pgh.pa.us        1708                 :            798 :             fix_scan_list(root, fscan->fdw_recheck_quals,
                               1709                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
                               1710                 :                :     }
                               1711                 :                : 
 2497                          1712                 :           1115 :     fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
 1351                          1713                 :           1115 :     fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
                               1714                 :                : 
                               1715                 :                :     /* Adjust resultRelation if it's valid */
 2189 heikki.linnakangas@i     1716         [ +  + ]:           1115 :     if (fscan->resultRelation > 0)
                               1717                 :            107 :         fscan->resultRelation += rtoffset;
 4173 tgl@sss.pgh.pa.us        1718                 :           1115 : }
                               1719                 :                : 
                               1720                 :                : /*
                               1721                 :                :  * set_customscan_references
                               1722                 :                :  *     Do set_plan_references processing on a CustomScan
                               1723                 :                :  */
                               1724                 :                : static void
 4173 tgl@sss.pgh.pa.us        1725                 :GBC          10 : set_customscan_references(PlannerInfo *root,
                               1726                 :                :                           CustomScan *cscan,
                               1727                 :                :                           int rtoffset)
                               1728                 :                : {
                               1729                 :                :     ListCell   *lc;
                               1730                 :                : 
                               1731                 :                :     /* Adjust scanrelid if it's valid */
                               1732         [ +  - ]:             10 :     if (cscan->scan.scanrelid > 0)
                               1733                 :             10 :         cscan->scan.scanrelid += rtoffset;
                               1734                 :                : 
                               1735   [ +  -  -  + ]:             10 :     if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
 4173 tgl@sss.pgh.pa.us        1736                 :UBC           0 :     {
                               1737                 :                :         /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
                               1738                 :              0 :         indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
                               1739                 :                : 
                               1740                 :              0 :         cscan->scan.plan.targetlist = (List *)
                               1741                 :              0 :             fix_upper_expr(root,
                               1742                 :              0 :                            (Node *) cscan->scan.plan.targetlist,
                               1743                 :                :                            itlist,
                               1744                 :                :                            INDEX_VAR,
                               1745                 :                :                            rtoffset,
                               1746                 :                :                            NUM_EXEC_TLIST((Plan *) cscan));
                               1747                 :              0 :         cscan->scan.plan.qual = (List *)
                               1748                 :              0 :             fix_upper_expr(root,
                               1749                 :              0 :                            (Node *) cscan->scan.plan.qual,
                               1750                 :                :                            itlist,
                               1751                 :                :                            INDEX_VAR,
                               1752                 :                :                            rtoffset,
 2206                          1753                 :              0 :                            NUM_EXEC_QUAL((Plan *) cscan));
 4173                          1754                 :              0 :         cscan->custom_exprs = (List *)
                               1755                 :              0 :             fix_upper_expr(root,
                               1756                 :              0 :                            (Node *) cscan->custom_exprs,
                               1757                 :                :                            itlist,
                               1758                 :                :                            INDEX_VAR,
                               1759                 :                :                            rtoffset,
 2206                          1760                 :              0 :                            NUM_EXEC_QUAL((Plan *) cscan));
 4173                          1761                 :              0 :         pfree(itlist);
                               1762                 :                :         /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
                               1763                 :              0 :         cscan->custom_scan_tlist =
 2206                          1764                 :              0 :             fix_scan_list(root, cscan->custom_scan_tlist,
                               1765                 :                :                           rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
                               1766                 :                :     }
                               1767                 :                :     else
                               1768                 :                :     {
                               1769                 :                :         /* Adjust tlist, qual, custom_exprs in the standard way */
 4173 tgl@sss.pgh.pa.us        1770                 :GBC          10 :         cscan->scan.plan.targetlist =
 2206                          1771                 :             10 :             fix_scan_list(root, cscan->scan.plan.targetlist,
                               1772                 :                :                           rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
 4173                          1773                 :             10 :         cscan->scan.plan.qual =
 2206                          1774                 :             10 :             fix_scan_list(root, cscan->scan.plan.qual,
                               1775                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
 4173                          1776                 :             10 :         cscan->custom_exprs =
 2206                          1777                 :             10 :             fix_scan_list(root, cscan->custom_exprs,
                               1778                 :                :                           rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
                               1779                 :                :     }
                               1780                 :                : 
                               1781                 :                :     /* Adjust child plan-nodes recursively, if needed */
 4101                          1782   [ -  +  -  -  :             10 :     foreach(lc, cscan->custom_plans)
                                              -  + ]
                               1783                 :                :     {
 4126 rhaas@postgresql.org     1784                 :UBC           0 :         lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
                               1785                 :                :     }
                               1786                 :                : 
 2497 tgl@sss.pgh.pa.us        1787                 :GBC          10 :     cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
 4173                          1788                 :             10 : }
                               1789                 :                : 
                               1790                 :                : /*
                               1791                 :                :  * register_partpruneinfo
                               1792                 :                :  *      Subroutine for set_append_references and set_mergeappend_references
                               1793                 :                :  *
                               1794                 :                :  * Add the PartitionPruneInfo from root->partPruneInfos at the given index
                               1795                 :                :  * into PlannerGlobal->partPruneInfos and return its index there.
                               1796                 :                :  *
                               1797                 :                :  * Also update the RT indexes present in PartitionedRelPruneInfos to add the
                               1798                 :                :  * offset.
                               1799                 :                :  *
                               1800                 :                :  * Finally, if there are initial pruning steps, add the RT indexes of the
                               1801                 :                :  * leaf partitions to the set of relations that are prunable at execution
                               1802                 :                :  * startup time.
                               1803                 :                :  */
                               1804                 :                : static int
  620 amitlan@postgresql.o     1805                 :CBC         460 : register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
                               1806                 :                : {
                               1807                 :            460 :     PlannerGlobal *glob = root->glob;
                               1808                 :                :     PartitionPruneInfo *pinfo;
                               1809                 :                :     ListCell   *l;
                               1810                 :                : 
                               1811   [ +  -  -  + ]:            460 :     Assert(part_prune_index >= 0 &&
                               1812                 :                :            part_prune_index < list_length(root->partPruneInfos));
                               1813                 :            460 :     pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
                               1814                 :                :                           part_prune_index);
                               1815                 :                : 
                               1816                 :            460 :     pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
                               1817   [ +  -  +  +  :            930 :     foreach(l, pinfo->prune_infos)
                                              +  + ]
                               1818                 :                :     {
                               1819                 :            470 :         List       *prune_infos = lfirst(l);
                               1820                 :                :         ListCell   *l2;
                               1821                 :                : 
                               1822   [ +  -  +  +  :           1276 :         foreach(l2, prune_infos)
                                              +  + ]
                               1823                 :                :         {
                               1824                 :            806 :             PartitionedRelPruneInfo *prelinfo = lfirst(l2);
                               1825                 :                :             int         i;
                               1826                 :                : 
                               1827                 :            806 :             prelinfo->rtindex += rtoffset;
                               1828                 :            806 :             prelinfo->initial_pruning_steps =
                               1829                 :            806 :                 fix_scan_list(root, prelinfo->initial_pruning_steps,
                               1830                 :                :                               rtoffset, 1);
                               1831                 :            806 :             prelinfo->exec_pruning_steps =
                               1832                 :            806 :                 fix_scan_list(root, prelinfo->exec_pruning_steps,
                               1833                 :                :                               rtoffset, 1);
                               1834                 :                : 
  612                          1835         [ +  + ]:           3188 :             for (i = 0; i < prelinfo->nparts; i++)
                               1836                 :                :             {
                               1837                 :                :                 /*
                               1838                 :                :                  * Non-leaf partitions and partitions that do not have a
                               1839                 :                :                  * subplan are not included in this map as mentioned in
                               1840                 :                :                  * make_partitionedrel_pruneinfo().
                               1841                 :                :                  */
                               1842         [ +  + ]:           2382 :                 if (prelinfo->leafpart_rti_map[i])
                               1843                 :                :                 {
                               1844                 :           1931 :                     prelinfo->leafpart_rti_map[i] += rtoffset;
                               1845         [ +  + ]:           1931 :                     if (prelinfo->initial_pruning_steps)
                               1846                 :            598 :                         glob->prunableRelids = bms_add_member(glob->prunableRelids,
                               1847                 :            598 :                                                               prelinfo->leafpart_rti_map[i]);
                               1848                 :                :                 }
                               1849                 :                :             }
                               1850                 :                :         }
                               1851                 :                :     }
                               1852                 :                : 
  620                          1853                 :            460 :     glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
                               1854                 :                : 
                               1855                 :            460 :     return list_length(glob->partPruneInfos) - 1;
                               1856                 :                : }
                               1857                 :                : 
                               1858                 :                : /*
                               1859                 :                :  * set_append_references
                               1860                 :                :  *      Do set_plan_references processing on an Append
                               1861                 :                :  *
                               1862                 :                :  * We try to strip out the Append entirely; if we can't, we have
                               1863                 :                :  * to do the normal processing on it.
                               1864                 :                :  */
                               1865                 :                : static Plan *
 2758 tgl@sss.pgh.pa.us        1866                 :          19012 : set_append_references(PlannerInfo *root,
                               1867                 :                :                       Append *aplan,
                               1868                 :                :                       int rtoffset)
                               1869                 :                : {
                               1870                 :                :     ListCell   *l;
                               1871                 :                : 
                               1872                 :                :     /*
                               1873                 :                :      * Append, like Sort et al, doesn't actually evaluate its targetlist or
                               1874                 :                :      * check quals.  If it's got exactly one child plan, then it's not doing
                               1875                 :                :      * anything useful at all, and we can strip it out.
                               1876                 :                :      */
                               1877         [ -  + ]:          19012 :     Assert(aplan->plan.qual == NIL);
                               1878                 :                : 
                               1879                 :                :     /* First, we gotta recurse on the children */
                               1880   [ +  -  +  +  :          66516 :     foreach(l, aplan->appendplans)
                                              +  + ]
                               1881                 :                :     {
                               1882                 :          47504 :         lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
                               1883                 :                :     }
                               1884                 :                : 
                               1885                 :                :     /*
                               1886                 :                :      * See if it's safe to get rid of the Append entirely.  For this to be
                               1887                 :                :      * safe, there must be only one child plan and that child plan's parallel
                               1888                 :                :      * awareness must match the Append's.  The reason for the latter is that
                               1889                 :                :      * if the Append is parallel aware and the child is not, then the calling
                               1890                 :                :      * plan may execute the non-parallel aware child multiple times.  (If you
                               1891                 :                :      * change these rules, update create_append_path to match.)
                               1892                 :                :      */
 1546 alvherre@alvh.no-ip.     1893         [ +  + ]:          19012 :     if (list_length(aplan->appendplans) == 1)
                               1894                 :                :     {
                               1895                 :           4552 :         Plan       *p = (Plan *) linitial(aplan->appendplans);
                               1896                 :                : 
                               1897         [ +  - ]:           4552 :         if (p->parallel_aware == aplan->plan.parallel_aware)
                               1898                 :                :         {
                               1899                 :                :             Plan       *result;
                               1900                 :                : 
  244 rhaas@postgresql.org     1901                 :           4552 :             result = clean_up_removed_plan_level((Plan *) aplan, p);
                               1902                 :                : 
                               1903                 :                :             /* Remember that we removed an Append */
                               1904                 :           4552 :             record_elided_node(root->glob, p->plan_node_id, T_Append,
                               1905                 :                :                                offset_relid_set(aplan->apprelids, rtoffset),
                               1906                 :                :                                offset_relid_set_list(aplan->child_append_relid_sets,
                               1907                 :                :                                                      rtoffset));
                               1908                 :                : 
                               1909                 :           4552 :             return result;
                               1910                 :                :         }
                               1911                 :                :     }
                               1912                 :                : 
                               1913                 :                :     /*
                               1914                 :                :      * Otherwise, clean up the Append as needed.  It's okay to do this after
                               1915                 :                :      * recursing to the children, because set_dummy_tlist_references doesn't
                               1916                 :                :      * look at those.
                               1917                 :                :      */
 2758 tgl@sss.pgh.pa.us        1918                 :          14460 :     set_dummy_tlist_references((Plan *) aplan, rtoffset);
                               1919                 :                : 
 2497                          1920                 :          14460 :     aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
    4 rhaas@postgresql.org     1921                 :          14460 :     aplan->child_append_relid_sets =
                               1922                 :          14460 :         offset_relid_set_list(aplan->child_append_relid_sets, rtoffset);
                               1923                 :                : 
                               1924                 :                :     /*
                               1925                 :                :      * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
                               1926                 :                :      * Also update the RT indexes present in it to add the offset.
                               1927                 :                :      */
  620 amitlan@postgresql.o     1928         [ +  + ]:          14460 :     if (aplan->part_prune_index >= 0)
                               1929                 :            430 :         aplan->part_prune_index =
                               1930                 :            430 :             register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
                               1931                 :                : 
                               1932                 :                :     /* We don't need to recurse to lefttree or righttree ... */
 2758 tgl@sss.pgh.pa.us        1933         [ -  + ]:          14460 :     Assert(aplan->plan.lefttree == NULL);
                               1934         [ -  + ]:          14460 :     Assert(aplan->plan.righttree == NULL);
                               1935                 :                : 
                               1936                 :          14460 :     return (Plan *) aplan;
                               1937                 :                : }
                               1938                 :                : 
                               1939                 :                : /*
                               1940                 :                :  * set_mergeappend_references
                               1941                 :                :  *      Do set_plan_references processing on a MergeAppend
                               1942                 :                :  *
                               1943                 :                :  * We try to strip out the MergeAppend entirely; if we can't, we have
                               1944                 :                :  * to do the normal processing on it.
                               1945                 :                :  */
                               1946                 :                : static Plan *
                               1947                 :            481 : set_mergeappend_references(PlannerInfo *root,
                               1948                 :                :                            MergeAppend *mplan,
                               1949                 :                :                            int rtoffset)
                               1950                 :                : {
                               1951                 :                :     ListCell   *l;
                               1952                 :                : 
                               1953                 :                :     /*
                               1954                 :                :      * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
                               1955                 :                :      * or check quals.  If it's got exactly one child plan, then it's not
                               1956                 :                :      * doing anything useful at all, and we can strip it out.
                               1957                 :                :      */
                               1958         [ -  + ]:            481 :     Assert(mplan->plan.qual == NIL);
                               1959                 :                : 
                               1960                 :                :     /* First, we gotta recurse on the children */
                               1961   [ +  -  +  +  :           1888 :     foreach(l, mplan->mergeplans)
                                              +  + ]
                               1962                 :                :     {
                               1963                 :           1407 :         lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
                               1964                 :                :     }
                               1965                 :                : 
                               1966                 :                :     /*
                               1967                 :                :      * See if it's safe to get rid of the MergeAppend entirely.  For this to
                               1968                 :                :      * be safe, there must be only one child plan and that child plan's
                               1969                 :                :      * parallel awareness must match the MergeAppend's.  The reason for the
                               1970                 :                :      * latter is that if the MergeAppend is parallel aware and the child is
                               1971                 :                :      * not, then the calling plan may execute the non-parallel aware child
                               1972                 :                :      * multiple times.  (If you change these rules, update
                               1973                 :                :      * create_merge_append_path to match.)
                               1974                 :                :      */
 1546 alvherre@alvh.no-ip.     1975         [ +  + ]:            481 :     if (list_length(mplan->mergeplans) == 1)
                               1976                 :                :     {
                               1977                 :              2 :         Plan       *p = (Plan *) linitial(mplan->mergeplans);
                               1978                 :                : 
                               1979         [ +  - ]:              2 :         if (p->parallel_aware == mplan->plan.parallel_aware)
                               1980                 :                :         {
                               1981                 :                :             Plan       *result;
                               1982                 :                : 
  244 rhaas@postgresql.org     1983                 :              2 :             result = clean_up_removed_plan_level((Plan *) mplan, p);
                               1984                 :                : 
                               1985                 :                :             /* Remember that we removed a MergeAppend */
                               1986                 :              2 :             record_elided_node(root->glob, p->plan_node_id, T_MergeAppend,
                               1987                 :                :                                offset_relid_set(mplan->apprelids, rtoffset),
                               1988                 :                :                                offset_relid_set_list(mplan->child_append_relid_sets,
                               1989                 :                :                                                      rtoffset));
                               1990                 :                : 
                               1991                 :              2 :             return result;
                               1992                 :                :         }
                               1993                 :                :     }
                               1994                 :                : 
                               1995                 :                :     /*
                               1996                 :                :      * Otherwise, clean up the MergeAppend as needed.  It's okay to do this
                               1997                 :                :      * after recursing to the children, because set_dummy_tlist_references
                               1998                 :                :      * doesn't look at those.
                               1999                 :                :      */
 2758 tgl@sss.pgh.pa.us        2000                 :            479 :     set_dummy_tlist_references((Plan *) mplan, rtoffset);
                               2001                 :                : 
 2497                          2002                 :            479 :     mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
    4 rhaas@postgresql.org     2003                 :            479 :     mplan->child_append_relid_sets =
                               2004                 :            479 :         offset_relid_set_list(mplan->child_append_relid_sets, rtoffset);
                               2005                 :                : 
                               2006                 :                :     /*
                               2007                 :                :      * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
                               2008                 :                :      * Also update the RT indexes present in it to add the offset.
                               2009                 :                :      */
  620 amitlan@postgresql.o     2010         [ +  + ]:            479 :     if (mplan->part_prune_index >= 0)
                               2011                 :             30 :         mplan->part_prune_index =
                               2012                 :             30 :             register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
                               2013                 :                : 
                               2014                 :                :     /* We don't need to recurse to lefttree or righttree ... */
 2758 tgl@sss.pgh.pa.us        2015         [ -  + ]:            479 :     Assert(mplan->plan.lefttree == NULL);
                               2016         [ -  + ]:            479 :     Assert(mplan->plan.righttree == NULL);
                               2017                 :                : 
                               2018                 :            479 :     return (Plan *) mplan;
                               2019                 :                : }
                               2020                 :                : 
                               2021                 :                : /*
                               2022                 :                :  * set_hash_references
                               2023                 :                :  *     Do set_plan_references processing on a Hash node
                               2024                 :                :  */
                               2025                 :                : static void
 2628 andres@anarazel.de       2026                 :          32061 : set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
                               2027                 :                : {
                               2028                 :          32061 :     Hash       *hplan = (Hash *) plan;
                               2029                 :          32061 :     Plan       *outer_plan = plan->lefttree;
                               2030                 :                :     indexed_tlist *outer_itlist;
                               2031                 :                : 
                               2032                 :                :     /*
                               2033                 :                :      * Hash's hashkeys are used when feeding tuples into the hashtable,
                               2034                 :                :      * therefore have them reference Hash's outer plan (which itself is the
                               2035                 :                :      * inner plan of the HashJoin).
                               2036                 :                :      */
                               2037                 :          32061 :     outer_itlist = build_tlist_index(outer_plan->targetlist);
                               2038                 :          32061 :     hplan->hashkeys = (List *)
                               2039                 :          32061 :         fix_upper_expr(root,
                               2040                 :          32061 :                        (Node *) hplan->hashkeys,
                               2041                 :                :                        outer_itlist,
                               2042                 :                :                        OUTER_VAR,
                               2043                 :                :                        rtoffset,
 2206 tgl@sss.pgh.pa.us        2044                 :          32061 :                        NUM_EXEC_QUAL(plan));
                               2045                 :                : 
                               2046                 :                :     /* Hash doesn't project */
 2628 andres@anarazel.de       2047                 :          32061 :     set_dummy_tlist_references(plan, rtoffset);
                               2048                 :                : 
                               2049                 :                :     /* Hash nodes don't have their own quals */
                               2050         [ -  + ]:          32061 :     Assert(plan->qual == NIL);
                               2051                 :          32061 : }
                               2052                 :                : 
                               2053                 :                : /*
                               2054                 :                :  * offset_relid_set
                               2055                 :                :  *      Apply rtoffset to the members of a Relids set.
                               2056                 :                :  */
                               2057                 :                : static Relids
 2497 tgl@sss.pgh.pa.us        2058                 :         173822 : offset_relid_set(Relids relids, int rtoffset)
                               2059                 :                : {
                               2060                 :                :     /* If there's no offset to apply, we needn't make another set */
                               2061         [ +  + ]:         173822 :     if (rtoffset == 0)
                               2062                 :         156910 :         return relids;
   95 drowley@postgresql.o     2063                 :GNC       16912 :     return bms_offset_members(relids, rtoffset);
                               2064                 :                : }
                               2065                 :                : 
                               2066                 :                : /*
                               2067                 :                :  * offset_relid_set_list
                               2068                 :                :  *      Apply rtoffset to the members of each Relid set in a List.
                               2069                 :                :  */
                               2070                 :                : static List *
    4 rhaas@postgresql.org     2071                 :CBC       19493 : offset_relid_set_list(List *relid_sets, int rtoffset)
                               2072                 :                : {
                               2073                 :          19493 :     List       *result = NIL;
                               2074                 :                : 
                               2075         [ +  + ]:          19493 :     if (rtoffset == 0)
                               2076                 :          18110 :         return relid_sets;
                               2077                 :                : 
                               2078   [ +  +  +  +  :           2778 :     foreach_ptr(Bitmapset, relids, relid_sets)
                                              +  + ]
                               2079                 :             12 :         result = lappend(result, offset_relid_set(relids, rtoffset));
                               2080                 :                : 
                               2081                 :           1383 :     return result;
                               2082                 :                : }
                               2083                 :                : 
                               2084                 :                : /*
                               2085                 :                :  * copyVar
                               2086                 :                :  *      Copy a Var node.
                               2087                 :                :  *
                               2088                 :                :  * fix_scan_expr and friends do this enough times that it's worth having
                               2089                 :                :  * a bespoke routine instead of using the generic copyObject() function.
                               2090                 :                :  */
                               2091                 :                : static inline Var *
 7105 tgl@sss.pgh.pa.us        2092                 :        1807699 : copyVar(Var *var)
                               2093                 :                : {
  306 michael@paquier.xyz      2094                 :        1807699 :     Var        *newvar = palloc_object(Var);
                               2095                 :                : 
 7105 tgl@sss.pgh.pa.us        2096                 :        1807699 :     *newvar = *var;
                               2097                 :        1807699 :     return newvar;
                               2098                 :                : }
                               2099                 :                : 
                               2100                 :                : /*
                               2101                 :                :  * fix_expr_common
                               2102                 :                :  *      Do generic set_plan_references processing on an expression node
                               2103                 :                :  *
                               2104                 :                :  * This is code that is common to all variants of expression-fixing.
                               2105                 :                :  * We must look up operator opcode info for OpExpr and related nodes,
                               2106                 :                :  * add OIDs from regclass Const nodes into root->glob->relationOids, and
                               2107                 :                :  * add PlanInvalItems for user-defined functions into root->glob->invalItems.
                               2108                 :                :  * We also fill in column index lists for GROUPING() expressions.
                               2109                 :                :  *
                               2110                 :                :  * We assume it's okay to update opcode info in-place.  So this could possibly
                               2111                 :                :  * scribble on the planner's input data structures, but it's OK.
                               2112                 :                :  */
                               2113                 :                : static void
 5518                          2114                 :       10489960 : fix_expr_common(PlannerInfo *root, Node *node)
                               2115                 :                : {
                               2116                 :                :     /* We assume callers won't call us on a NULL pointer */
 6607                          2117         [ +  + ]:       10489960 :     if (IsA(node, Aggref))
                               2118                 :                :     {
 5518                          2119                 :          47421 :         record_plan_function_dependency(root,
                               2120                 :                :                                         ((Aggref *) node)->aggfnoid);
                               2121                 :                :     }
 6497                          2122         [ +  + ]:       10442539 :     else if (IsA(node, WindowFunc))
                               2123                 :                :     {
 5518                          2124                 :           3450 :         record_plan_function_dependency(root,
                               2125                 :                :                                         ((WindowFunc *) node)->winfnoid);
                               2126                 :                :     }
 6607                          2127         [ +  + ]:       10439089 :     else if (IsA(node, FuncExpr))
                               2128                 :                :     {
 5518                          2129                 :         218798 :         record_plan_function_dependency(root,
                               2130                 :                :                                         ((FuncExpr *) node)->funcid);
                               2131                 :                :     }
 6607                          2132         [ +  + ]:       10220291 :     else if (IsA(node, OpExpr))
                               2133                 :                :     {
                               2134                 :         658771 :         set_opfuncid((OpExpr *) node);
 5518                          2135                 :         658771 :         record_plan_function_dependency(root,
                               2136                 :                :                                         ((OpExpr *) node)->opfuncid);
                               2137                 :                :     }
 6607                          2138         [ +  + ]:        9561520 :     else if (IsA(node, DistinctExpr))
                               2139                 :                :     {
                               2140                 :            645 :         set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
 5518                          2141                 :            645 :         record_plan_function_dependency(root,
                               2142                 :                :                                         ((DistinctExpr *) node)->opfuncid);
                               2143                 :                :     }
 6607                          2144         [ +  + ]:        9560875 :     else if (IsA(node, NullIfExpr))
                               2145                 :                :     {
                               2146                 :            295 :         set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
 5518                          2147                 :            295 :         record_plan_function_dependency(root,
                               2148                 :                :                                         ((NullIfExpr *) node)->opfuncid);
                               2149                 :                :     }
 6607                          2150         [ +  + ]:        9560580 :     else if (IsA(node, ScalarArrayOpExpr))
                               2151                 :                :     {
 2013 drowley@postgresql.o     2152                 :          28806 :         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
                               2153                 :                : 
                               2154                 :          28806 :         set_sa_opfuncid(saop);
                               2155                 :          28806 :         record_plan_function_dependency(root, saop->opfuncid);
                               2156                 :                : 
 1124                          2157         [ +  + ]:          28806 :         if (OidIsValid(saop->hashfuncid))
 2013                          2158                 :            574 :             record_plan_function_dependency(root, saop->hashfuncid);
                               2159                 :                : 
 1124                          2160         [ +  + ]:          28806 :         if (OidIsValid(saop->negfuncid))
 1923                          2161                 :             82 :             record_plan_function_dependency(root, saop->negfuncid);
                               2162                 :                :     }
 6607 tgl@sss.pgh.pa.us        2163         [ +  + ]:        9531774 :     else if (IsA(node, Const))
                               2164                 :                :     {
                               2165                 :        1059872 :         Const      *con = (Const *) node;
                               2166                 :                : 
                               2167                 :                :         /* Check for regclass reference */
                               2168   [ +  +  +  +  :        1059872 :         if (ISREGCLASSCONST(con))
                                              +  + ]
 5518                          2169                 :         181891 :             root->glob->relationOids =
                               2170                 :         181891 :                 lappend_oid(root->glob->relationOids,
                               2171                 :                :                             DatumGetObjectId(con->constvalue));
                               2172                 :                :     }
 4167 andres@anarazel.de       2173         [ +  + ]:        8471902 :     else if (IsA(node, GroupingFunc))
                               2174                 :                :     {
                               2175                 :            303 :         GroupingFunc *g = (GroupingFunc *) node;
                               2176                 :            303 :         AttrNumber *grouping_map = root->grouping_map;
                               2177                 :                : 
                               2178                 :                :         /* If there are no grouping sets, we don't need this. */
                               2179                 :                : 
                               2180   [ +  +  -  + ]:            303 :         Assert(grouping_map || g->cols == NIL);
                               2181                 :                : 
                               2182         [ +  + ]:            303 :         if (grouping_map)
                               2183                 :                :         {
                               2184                 :                :             ListCell   *lc;
                               2185                 :            226 :             List       *cols = NIL;
                               2186                 :                : 
                               2187   [ +  -  +  +  :            598 :             foreach(lc, g->refs)
                                              +  + ]
                               2188                 :                :             {
                               2189                 :            372 :                 cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
                               2190                 :                :             }
                               2191                 :                : 
                               2192   [ -  +  -  - ]:            226 :             Assert(!g->cols || equal(cols, g->cols));
                               2193                 :                : 
                               2194         [ +  - ]:            226 :             if (!g->cols)
                               2195                 :            226 :                 g->cols = cols;
                               2196                 :                :         }
                               2197                 :                :     }
 6607 tgl@sss.pgh.pa.us        2198                 :       10489960 : }
                               2199                 :                : 
                               2200                 :                : /*
                               2201                 :                :  * fix_param_node
                               2202                 :                :  *      Do set_plan_references processing on a Param
                               2203                 :                :  *
                               2204                 :                :  * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
                               2205                 :                :  * root->multiexpr_params; otherwise no change is needed.
                               2206                 :                :  * Just for paranoia's sake, we make a copy of the node in either case.
                               2207                 :                :  */
                               2208                 :                : static Node *
 4499                          2209                 :          87764 : fix_param_node(PlannerInfo *root, Param *p)
                               2210                 :                : {
                               2211         [ +  + ]:          87764 :     if (p->paramkind == PARAM_MULTIEXPR)
                               2212                 :                :     {
                               2213                 :            235 :         int         subqueryid = p->paramid >> 16;
                               2214                 :            235 :         int         colno = p->paramid & 0xFFFF;
                               2215                 :                :         List       *params;
                               2216                 :                : 
                               2217   [ +  -  -  + ]:            470 :         if (subqueryid <= 0 ||
                               2218                 :            235 :             subqueryid > list_length(root->multiexpr_params))
 4499 tgl@sss.pgh.pa.us        2219         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
 4499 tgl@sss.pgh.pa.us        2220                 :CBC         235 :         params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
                               2221   [ +  -  -  + ]:            235 :         if (colno <= 0 || colno > list_length(params))
 4499 tgl@sss.pgh.pa.us        2222         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
 4499 tgl@sss.pgh.pa.us        2223                 :CBC         235 :         return copyObject(list_nth(params, colno - 1));
                               2224                 :                :     }
 3504 peter_e@gmx.net          2225                 :          87529 :     return (Node *) copyObject(p);
                               2226                 :                : }
                               2227                 :                : 
                               2228                 :                : /*
                               2229                 :                :  * fix_alternative_subplan
                               2230                 :                :  *      Do set_plan_references processing on an AlternativeSubPlan
                               2231                 :                :  *
                               2232                 :                :  * Choose one of the alternative implementations and return just that one,
                               2233                 :                :  * discarding the rest of the AlternativeSubPlan structure.
                               2234                 :                :  * Note: caller must still recurse into the result!
                               2235                 :                :  *
                               2236                 :                :  * We don't make any attempt to fix up cost estimates in the parent plan
                               2237                 :                :  * node or higher-level nodes.
                               2238                 :                :  */
                               2239                 :                : static Node *
 2206 tgl@sss.pgh.pa.us        2240                 :           1378 : fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan,
                               2241                 :                :                         double num_exec)
                               2242                 :                : {
                               2243                 :           1378 :     SubPlan    *bestplan = NULL;
                               2244                 :           1378 :     Cost        bestcost = 0;
                               2245                 :                :     ListCell   *lc;
                               2246                 :                : 
                               2247                 :                :     /*
                               2248                 :                :      * Compute the estimated cost of each subplan assuming num_exec
                               2249                 :                :      * executions, and keep the cheapest one.  If one subplan has more
                               2250                 :                :      * disabled nodes than another, choose the one with fewer disabled nodes
                               2251                 :                :      * regardless of cost; this parallels compare_path_costs.  In event of
                               2252                 :                :      * exact equality of estimates, we prefer the later plan; this is a bit
                               2253                 :                :      * arbitrary, but in current usage it biases us to break ties against
                               2254                 :                :      * fast-start subplans.
                               2255                 :                :      */
                               2256         [ -  + ]:           1378 :     Assert(asplan->subplans != NIL);
                               2257                 :                : 
                               2258   [ +  -  +  +  :           4134 :     foreach(lc, asplan->subplans)
                                              +  + ]
                               2259                 :                :     {
                               2260                 :           2756 :         SubPlan    *curplan = (SubPlan *) lfirst(lc);
                               2261                 :                :         Cost        curcost;
                               2262                 :                : 
                               2263                 :           2756 :         curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
  206 rhaas@postgresql.org     2264         [ +  + ]:           2756 :         if (bestplan == NULL ||
                               2265         [ +  + ]:           1378 :             curplan->disabled_nodes < bestplan->disabled_nodes ||
                               2266   [ +  +  +  + ]:           1345 :             (curplan->disabled_nodes == bestplan->disabled_nodes &&
                               2267                 :                :              curcost <= bestcost))
                               2268                 :                :         {
 2206 tgl@sss.pgh.pa.us        2269                 :           1858 :             bestplan = curplan;
                               2270                 :           1858 :             bestcost = curcost;
                               2271                 :                :         }
                               2272                 :                : 
                               2273                 :                :         /* Also mark all subplans that are in AlternativeSubPlans */
 1854                          2274                 :           2756 :         root->isAltSubplan[curplan->plan_id - 1] = true;
                               2275                 :                :     }
                               2276                 :                : 
                               2277                 :                :     /* Mark the subplan we selected */
                               2278                 :           1378 :     root->isUsedSubplan[bestplan->plan_id - 1] = true;
                               2279                 :                : 
 2206                          2280                 :           1378 :     return (Node *) bestplan;
                               2281                 :                : }
                               2282                 :                : 
                               2283                 :                : /*
                               2284                 :                :  * fix_dummy_setop_vars_mutator
                               2285                 :                :  *      Change the varno 0 Vars made by prepunion.c to varno *first_child_relid.
                               2286                 :                :  */
                               2287                 :                : static Node *
    7                          2288                 :         373921 : fix_dummy_setop_vars_mutator(Node *node, int *first_child_relid)
                               2289                 :                : {
                               2290         [ +  + ]:         373921 :     if (node == NULL)
                               2291                 :          12504 :         return NULL;
                               2292         [ +  + ]:         361417 :     if (IsA(node, Var))
                               2293                 :                :     {
                               2294                 :           1565 :         Var        *var = (Var *) node;
                               2295                 :                : 
                               2296         [ +  + ]:           1565 :         if (var->varno == 0)
                               2297                 :             30 :             return (Node *) makeVar(*first_child_relid,
                               2298                 :             30 :                                     var->varattno,
                               2299                 :                :                                     var->vartype,
                               2300                 :                :                                     var->vartypmod,
                               2301                 :                :                                     var->varcollid,
                               2302                 :                :                                     var->varlevelsup);
                               2303                 :           1535 :         return node;
                               2304                 :                :     }
                               2305                 :         359852 :     return expression_tree_mutator(node, fix_dummy_setop_vars_mutator,
                               2306                 :                :                                    first_child_relid);
                               2307                 :                : }
                               2308                 :                : 
                               2309                 :                : /*
                               2310                 :                :  * fix_scan_expr
                               2311                 :                :  *      Do set_plan_references processing on a scan-level expression
                               2312                 :                :  *
                               2313                 :                :  * This consists of incrementing all Vars' varnos by rtoffset,
                               2314                 :                :  * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
                               2315                 :                :  * replacing Aggref nodes that should be replaced by initplan output Params,
                               2316                 :                :  * choosing the best implementation for AlternativeSubPlans,
                               2317                 :                :  * looking up operator opcode info for OpExpr and related nodes,
                               2318                 :                :  * and adding OIDs from regclass Const nodes into root->glob->relationOids.
                               2319                 :                :  *
                               2320                 :                :  * 'node': the expression to be modified
                               2321                 :                :  * 'rtoffset': how much to increment varnos by
                               2322                 :                :  * 'num_exec': estimated number of executions of expression
                               2323                 :                :  *
                               2324                 :                :  * The expression tree is either copied-and-modified, or modified in-place
                               2325                 :                :  * if that seems safe.
                               2326                 :                :  */
                               2327                 :                : static Node *
 2206                          2328                 :        1779064 : fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
                               2329                 :                : {
                               2330                 :                :     fix_scan_expr_context context;
                               2331                 :                : 
 5518                          2332                 :        1779064 :     context.root = root;
 7172                          2333                 :        1779064 :     context.rtoffset = rtoffset;
 2206                          2334                 :        1779064 :     context.num_exec = num_exec;
                               2335                 :                : 
 4499                          2336         [ +  + ]:        1779064 :     if (rtoffset != 0 ||
                               2337         [ +  + ]:        1437455 :         root->multiexpr_params != NIL ||
 3871                          2338         [ +  + ]:        1436980 :         root->glob->lastPHId != 0 ||
 2206                          2339         [ +  + ]:        1425931 :         root->minmax_aggs != NIL ||
                               2340         [ +  + ]:        1425262 :         root->hasAlternativeSubPlans)
                               2341                 :                :     {
 6897                          2342                 :         363901 :         return fix_scan_expr_mutator(node, &context);
                               2343                 :                :     }
                               2344                 :                :     else
                               2345                 :                :     {
                               2346                 :                :         /*
                               2347                 :                :          * If rtoffset == 0, we don't need to change any Vars, and if there
                               2348                 :                :          * are no MULTIEXPR subqueries then we don't need to replace
                               2349                 :                :          * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
                               2350                 :                :          * we won't need to remove them, and if there are no minmax Aggrefs we
                               2351                 :                :          * won't need to replace them, and if there are no AlternativeSubPlans
                               2352                 :                :          * we won't need to remove them.  Then it's OK to just scribble on the
                               2353                 :                :          * input node tree instead of copying (since the only change, filling
                               2354                 :                :          * in any unset opfuncid fields, is harmless).  This saves just enough
                               2355                 :                :          * cycles to be noticeable on trivial queries.
                               2356                 :                :          */
                               2357                 :        1415163 :         (void) fix_scan_expr_walker(node, &context);
                               2358                 :        1415163 :         return node;
                               2359                 :                :     }
                               2360                 :                : }
                               2361                 :                : 
                               2362                 :                : static Node *
 6906 bruce@momjian.us         2363                 :        2459688 : fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
                               2364                 :                : {
 7813 tgl@sss.pgh.pa.us        2365         [ +  + ]:        2459688 :     if (node == NULL)
 7172                          2366                 :         143230 :         return NULL;
 7813                          2367         [ +  + ]:        2316458 :     if (IsA(node, Var))
                               2368                 :                :     {
 7105                          2369                 :         834585 :         Var        *var = copyVar((Var *) node);
                               2370                 :                : 
 7813                          2371         [ -  + ]:         834585 :         Assert(var->varlevelsup == 0);
                               2372                 :                : 
                               2373                 :                :         /*
                               2374                 :                :          * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
                               2375                 :                :          * But an indexqual expression could contain INDEX_VAR Vars.
                               2376                 :                :          */
 5480                          2377         [ -  + ]:         834585 :         Assert(var->varno != INNER_VAR);
                               2378         [ -  + ]:         834585 :         Assert(var->varno != OUTER_VAR);
 2021                          2379         [ -  + ]:         834585 :         Assert(var->varno != ROWID_VAR);
 5480                          2380         [ +  + ]:         834585 :         if (!IS_SPECIAL_VARNO(var->varno))
                               2381                 :         794049 :             var->varno += context->rtoffset;
 2468                          2382         [ +  + ]:         834585 :         if (var->varnosyn > 0)
                               2383                 :         833786 :             var->varnosyn += context->rtoffset;
 7172                          2384                 :         834585 :         return (Node *) var;
                               2385                 :                :     }
 4499                          2386         [ +  + ]:        1481873 :     if (IsA(node, Param))
                               2387                 :          74315 :         return fix_param_node(context->root, (Param *) node);
 3871                          2388         [ +  + ]:        1407558 :     if (IsA(node, Aggref))
                               2389                 :                :     {
                               2390                 :            355 :         Aggref     *aggref = (Aggref *) node;
                               2391                 :                :         Param      *aggparam;
                               2392                 :                : 
                               2393                 :                :         /* See if the Aggref should be replaced by a Param */
 1187                          2394                 :            355 :         aggparam = find_minmax_agg_replacement_param(context->root, aggref);
                               2395         [ +  + ]:            355 :         if (aggparam != NULL)
                               2396                 :                :         {
                               2397                 :                :             /* Make a copy of the Param for paranoia's sake */
                               2398                 :            340 :             return (Node *) copyObject(aggparam);
                               2399                 :                :         }
                               2400                 :                :         /* If no match, just fall through to process it normally */
                               2401                 :                :     }
 7063                          2402         [ -  + ]:        1407218 :     if (IsA(node, CurrentOfExpr))
                               2403                 :                :     {
 7063 tgl@sss.pgh.pa.us        2404                 :UBC           0 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
                               2405                 :                : 
 1853                          2406         [ #  # ]:              0 :         Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
                               2407                 :              0 :         cexpr->cvarno += context->rtoffset;
 7063                          2408                 :              0 :         return (Node *) cexpr;
                               2409                 :                :     }
 6565 tgl@sss.pgh.pa.us        2410         [ +  + ]:CBC     1407218 :     if (IsA(node, PlaceHolderVar))
                               2411                 :                :     {
                               2412                 :                :         /* At scan level, we should always just evaluate the contained expr */
                               2413                 :           2597 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               2414                 :                : 
                               2415                 :                :         /* XXX can we assert something about phnullingrels? */
                               2416                 :           2597 :         return fix_scan_expr_mutator((Node *) phv->phexpr, context);
                               2417                 :                :     }
 2206                          2418         [ +  + ]:        1404621 :     if (IsA(node, AlternativeSubPlan))
                               2419                 :            248 :         return fix_scan_expr_mutator(fix_alternative_subplan(context->root,
                               2420                 :                :                                                              (AlternativeSubPlan *) node,
                               2421                 :                :                                                              context->num_exec),
                               2422                 :                :                                      context);
 5518                          2423                 :        1404373 :     fix_expr_common(context->root, node);
  683 peter@eisentraut.org     2424                 :        1404373 :     return expression_tree_mutator(node, fix_scan_expr_mutator, context);
                               2425                 :                : }
                               2426                 :                : 
                               2427                 :                : static bool
 6897 tgl@sss.pgh.pa.us        2428                 :        7490115 : fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
                               2429                 :                : {
                               2430         [ +  + ]:        7490115 :     if (node == NULL)
                               2431                 :         719287 :         return false;
 2021                          2432   [ +  +  -  + ]:        6770828 :     Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
 6565                          2433         [ -  + ]:        6770828 :     Assert(!IsA(node, PlaceHolderVar));
 2206                          2434         [ -  + ]:        6770828 :     Assert(!IsA(node, AlternativeSubPlan));
 5518                          2435                 :        6770828 :     fix_expr_common(context->root, node);
  683 peter@eisentraut.org     2436                 :        6770828 :     return expression_tree_walker(node, fix_scan_expr_walker, context);
                               2437                 :                : }
                               2438                 :                : 
                               2439                 :                : /*
                               2440                 :                :  * set_join_references
                               2441                 :                :  *    Modify the target list and quals of a join node to reference its
                               2442                 :                :  *    subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
                               2443                 :                :  *    attno values to the result domain number of either the corresponding
                               2444                 :                :  *    outer or inner join tuple item.  Also perform opcode lookup for these
                               2445                 :                :  *    expressions, and add regclass OIDs to root->glob->relationOids.
                               2446                 :                :  */
                               2447                 :                : static void
 5518 tgl@sss.pgh.pa.us        2448                 :         110978 : set_join_references(PlannerInfo *root, Join *join, int rtoffset)
                               2449                 :                : {
 8671                          2450                 :         110978 :     Plan       *outer_plan = join->plan.lefttree;
                               2451                 :         110978 :     Plan       *inner_plan = join->plan.righttree;
                               2452                 :                :     indexed_tlist *outer_itlist;
                               2453                 :                :     indexed_tlist *inner_itlist;
                               2454                 :                : 
 7794                          2455                 :         110978 :     outer_itlist = build_tlist_index(outer_plan->targetlist);
                               2456                 :         110978 :     inner_itlist = build_tlist_index(inner_plan->targetlist);
                               2457                 :                : 
                               2458                 :                :     /*
                               2459                 :                :      * First process the joinquals (including merge or hash clauses).  These
                               2460                 :                :      * are logically below the join so they can always use all values
                               2461                 :                :      * available from the input tlists.  It's okay to also handle
                               2462                 :                :      * NestLoopParams now, because those couldn't refer to nullable
                               2463                 :                :      * subexpressions.
                               2464                 :                :      */
 5518                          2465                 :         221956 :     join->joinqual = fix_join_expr(root,
                               2466                 :                :                                    join->joinqual,
                               2467                 :                :                                    outer_itlist,
                               2468                 :                :                                    inner_itlist,
                               2469                 :                :                                    (Index) 0,
                               2470                 :                :                                    rtoffset,
                               2471                 :                :                                    NRM_EQUAL,
 2206                          2472                 :         110978 :                                    NUM_EXEC_QUAL((Plan *) join));
                               2473                 :                : 
                               2474                 :                :     /* Now do join-type-specific stuff */
 8671                          2475         [ +  + ]:         110978 :     if (IsA(join, NestLoop))
                               2476                 :                :     {
 5936                          2477                 :          73310 :         NestLoop   *nl = (NestLoop *) join;
                               2478                 :                :         ListCell   *lc;
                               2479                 :                : 
                               2480   [ +  +  +  +  :         114820 :         foreach(lc, nl->nestParams)
                                              +  + ]
                               2481                 :                :         {
                               2482                 :          41510 :             NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
                               2483                 :                : 
                               2484                 :                :             /*
                               2485                 :                :              * identify_current_nestloop_params has already ensured that any
                               2486                 :                :              * Vars or PHVs seen in the NestLoopParam expression have
                               2487                 :                :              * nullingrels that include exactly the outer-join relids that
                               2488                 :                :              * appear in the outer side's output and can null the respective
                               2489                 :                :              * Var or PHV.  Therefore, fix_upper_expr will not complain when
                               2490                 :                :              * performing the nullingrels matches here.
                               2491                 :                :              */
 5518                          2492                 :          83020 :             nlp->paramval = (Var *) fix_upper_expr(root,
 5936                          2493                 :          41510 :                                                    (Node *) nlp->paramval,
                               2494                 :                :                                                    outer_itlist,
                               2495                 :                :                                                    OUTER_VAR,
                               2496                 :                :                                                    rtoffset,
                               2497                 :                :                                                    NUM_EXEC_TLIST(outer_plan));
                               2498                 :                :             /* Check we replaced any PlaceHolderVar with simple Var */
 5457                          2499         [ +  - ]:          41510 :             if (!(IsA(nlp->paramval, Var) &&
                               2500         [ -  + ]:          41510 :                   nlp->paramval->varno == OUTER_VAR))
 5457 tgl@sss.pgh.pa.us        2501         [ #  # ]:UBC           0 :                 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
                               2502                 :                :         }
                               2503                 :                :     }
 8671 tgl@sss.pgh.pa.us        2504         [ +  + ]:CBC       37668 :     else if (IsA(join, MergeJoin))
                               2505                 :                :     {
                               2506                 :           5607 :         MergeJoin  *mj = (MergeJoin *) join;
                               2507                 :                : 
 5518                          2508                 :           5607 :         mj->mergeclauses = fix_join_expr(root,
                               2509                 :                :                                          mj->mergeclauses,
                               2510                 :                :                                          outer_itlist,
                               2511                 :                :                                          inner_itlist,
                               2512                 :                :                                          (Index) 0,
                               2513                 :                :                                          rtoffset,
                               2514                 :                :                                          NRM_EQUAL,
 2206                          2515                 :           5607 :                                          NUM_EXEC_QUAL((Plan *) join));
                               2516                 :                :     }
 8671                          2517         [ +  - ]:          32061 :     else if (IsA(join, HashJoin))
                               2518                 :                :     {
                               2519                 :          32061 :         HashJoin   *hj = (HashJoin *) join;
                               2520                 :                : 
 5518                          2521                 :          64122 :         hj->hashclauses = fix_join_expr(root,
                               2522                 :                :                                         hj->hashclauses,
                               2523                 :                :                                         outer_itlist,
                               2524                 :                :                                         inner_itlist,
                               2525                 :                :                                         (Index) 0,
                               2526                 :                :                                         rtoffset,
                               2527                 :                :                                         NRM_EQUAL,
 2206                          2528                 :          32061 :                                         NUM_EXEC_QUAL((Plan *) join));
                               2529                 :                : 
                               2530                 :                :         /*
                               2531                 :                :          * HashJoin's hashkeys are used to look for matching tuples from its
                               2532                 :                :          * outer plan (not the Hash node!) in the hashtable.
                               2533                 :                :          */
 2628 andres@anarazel.de       2534                 :          32061 :         hj->hashkeys = (List *) fix_upper_expr(root,
                               2535                 :          32061 :                                                (Node *) hj->hashkeys,
                               2536                 :                :                                                outer_itlist,
                               2537                 :                :                                                OUTER_VAR,
                               2538                 :                :                                                rtoffset,
 2206 tgl@sss.pgh.pa.us        2539                 :          32061 :                                                NUM_EXEC_QUAL((Plan *) join));
                               2540                 :                :     }
                               2541                 :                : 
                               2542                 :                :     /*
                               2543                 :                :      * Now we need to fix up the targetlist and qpqual, which are logically
                               2544                 :                :      * above the join.  This means that, if it's an outer join with non-empty
                               2545                 :                :      * ojrelids, any Vars and PHVs appearing here should have nullingrels that
                               2546                 :                :      * include the effects of the outer join, ie they will have nullingrels
                               2547                 :                :      * equal to the input Vars' nullingrels plus the bit added by the outer
                               2548                 :                :      * join.  We don't currently have enough info available here to identify
                               2549                 :                :      * what that should be, so we just tell fix_join_expr to accept superset
                               2550                 :                :      * nullingrels matches instead of exact ones.
                               2551                 :                :      */
 4209                          2552                 :         221956 :     join->plan.targetlist = fix_join_expr(root,
                               2553                 :                :                                           join->plan.targetlist,
                               2554                 :                :                                           outer_itlist,
                               2555                 :                :                                           inner_itlist,
                               2556                 :                :                                           (Index) 0,
                               2557                 :                :                                           rtoffset,
   96 rguo@postgresql.org      2558                 :GNC      110978 :                                           (bms_is_empty(join->ojrelids) ? NRM_EQUAL : NRM_SUPERSET),
                               2559                 :                :                                           NUM_EXEC_TLIST((Plan *) join));
 4209 tgl@sss.pgh.pa.us        2560                 :CBC      221956 :     join->plan.qual = fix_join_expr(root,
                               2561                 :                :                                     join->plan.qual,
                               2562                 :                :                                     outer_itlist,
                               2563                 :                :                                     inner_itlist,
                               2564                 :                :                                     (Index) 0,
                               2565                 :                :                                     rtoffset,
   96 rguo@postgresql.org      2566                 :GNC      110978 :                                     (bms_is_empty(join->ojrelids) ? NRM_EQUAL : NRM_SUPERSET),
 2206 tgl@sss.pgh.pa.us        2567         [ +  + ]:CBC      110978 :                                     NUM_EXEC_QUAL((Plan *) join));
                               2568                 :                : 
 7794                          2569                 :         110978 :     pfree(outer_itlist);
                               2570                 :         110978 :     pfree(inner_itlist);
11052 scrappy@hub.org          2571                 :         110978 : }
                               2572                 :                : 
                               2573                 :                : /*
                               2574                 :                :  * set_upper_references
                               2575                 :                :  *    Update the targetlist and quals of an upper-level plan node
                               2576                 :                :  *    to refer to the tuples returned by its lefttree subplan.
                               2577                 :                :  *    Also perform opcode lookup for these expressions, and
                               2578                 :                :  *    add regclass OIDs to root->glob->relationOids.
                               2579                 :                :  *
                               2580                 :                :  * This is used for single-input plan types like Agg, Group, Result.
                               2581                 :                :  *
                               2582                 :                :  * In most cases, we have to match up individual Vars in the tlist and
                               2583                 :                :  * qual expressions with elements of the subplan's tlist (which was
                               2584                 :                :  * generated by flattening these selfsame expressions, so it should have all
                               2585                 :                :  * the required variables).  There is an important exception, however:
                               2586                 :                :  * depending on where we are in the plan tree, sort/group columns may have
                               2587                 :                :  * been pushed into the subplan tlist unflattened.  If these values are also
                               2588                 :                :  * needed in the output then we want to reference the subplan tlist element
                               2589                 :                :  * rather than recomputing the expression.
                               2590                 :                :  */
                               2591                 :                : static void
 5518 tgl@sss.pgh.pa.us        2592                 :          61732 : set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
                               2593                 :                : {
 9913                          2594                 :          61732 :     Plan       *subplan = plan->lefttree;
                               2595                 :                :     indexed_tlist *subplan_itlist;
                               2596                 :                :     List       *output_targetlist;
                               2597                 :                :     ListCell   *l;
                               2598                 :                : 
 7171                          2599                 :          61732 :     subplan_itlist = build_tlist_index(subplan->targetlist);
                               2600                 :                : 
                               2601                 :                :     /*
                               2602                 :                :      * If it's a grouping node with grouping sets, any Vars and PHVs appearing
                               2603                 :                :      * in the targetlist and quals should have nullingrels that include the
                               2604                 :                :      * effects of the grouping step, ie they will have nullingrels equal to
                               2605                 :                :      * the input Vars/PHVs' nullingrels plus the RT index of the grouping
                               2606                 :                :      * step.  In order to perform exact nullingrels matches, we remove the RT
                               2607                 :                :      * index of the grouping step first.
                               2608                 :                :      */
  762 rguo@postgresql.org      2609         [ +  + ]:          61732 :     if (IsA(plan, Agg) &&
                               2610         [ +  + ]:          37830 :         root->group_rtindex > 0 &&
                               2611         [ +  + ]:           6104 :         ((Agg *) plan)->groupingSets)
                               2612                 :                :     {
                               2613                 :            832 :         plan->targetlist = (List *)
                               2614                 :            832 :             remove_nulling_relids((Node *) plan->targetlist,
                               2615                 :            832 :                                   bms_make_singleton(root->group_rtindex),
                               2616                 :                :                                   NULL);
                               2617                 :            832 :         plan->qual = (List *)
                               2618                 :            832 :             remove_nulling_relids((Node *) plan->qual,
                               2619                 :            832 :                                   bms_make_singleton(root->group_rtindex),
                               2620                 :                :                                   NULL);
                               2621                 :                :     }
                               2622                 :                : 
 9113 tgl@sss.pgh.pa.us        2623                 :          61732 :     output_targetlist = NIL;
                               2624   [ +  +  +  +  :         168590 :     foreach(l, plan->targetlist)
                                              +  + ]
                               2625                 :                :     {
                               2626                 :         106858 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               2627                 :                :         Node       *newexpr;
                               2628                 :                : 
                               2629                 :                :         /* If it's a sort/group item, first try to match by sortref */
 3273                          2630         [ +  + ]:         106858 :         if (tle->ressortgroupref != 0)
                               2631                 :                :         {
                               2632                 :                :             newexpr = (Node *)
 3504 peter_e@gmx.net          2633                 :          33497 :                 search_indexed_tlist_for_sortgroupref(tle->expr,
                               2634                 :                :                                                       tle->ressortgroupref,
                               2635                 :                :                                                       subplan_itlist,
                               2636                 :                :                                                       OUTER_VAR);
 6174 tgl@sss.pgh.pa.us        2637         [ +  + ]:          33497 :             if (!newexpr)
 5518                          2638                 :          18445 :                 newexpr = fix_upper_expr(root,
 6174                          2639                 :          18445 :                                          (Node *) tle->expr,
                               2640                 :                :                                          subplan_itlist,
                               2641                 :                :                                          OUTER_VAR,
                               2642                 :                :                                          rtoffset,
                               2643                 :                :                                          NUM_EXEC_TLIST(plan));
                               2644                 :                :         }
                               2645                 :                :         else
 5518                          2646                 :          73361 :             newexpr = fix_upper_expr(root,
 6174                          2647                 :          73361 :                                      (Node *) tle->expr,
                               2648                 :                :                                      subplan_itlist,
                               2649                 :                :                                      OUTER_VAR,
                               2650                 :                :                                      rtoffset,
                               2651                 :                :                                      NUM_EXEC_TLIST(plan));
 7859                          2652                 :         106858 :         tle = flatCopyTargetEntry(tle);
                               2653                 :         106858 :         tle->expr = (Expr *) newexpr;
                               2654                 :         106858 :         output_targetlist = lappend(output_targetlist, tle);
                               2655                 :                :     }
 9113                          2656                 :          61732 :     plan->targetlist = output_targetlist;
                               2657                 :                : 
 9913                          2658                 :          61732 :     plan->qual = (List *)
 5518                          2659                 :          61732 :         fix_upper_expr(root,
 6941                          2660                 :          61732 :                        (Node *) plan->qual,
                               2661                 :                :                        subplan_itlist,
                               2662                 :                :                        OUTER_VAR,
                               2663                 :                :                        rtoffset,
 2206                          2664                 :          61732 :                        NUM_EXEC_QUAL(plan));
                               2665                 :                : 
 7794                          2666                 :          61732 :     pfree(subplan_itlist);
11052 scrappy@hub.org          2667                 :          61732 : }
                               2668                 :                : 
                               2669                 :                : /*
                               2670                 :                :  * set_param_references
                               2671                 :                :  *    Initialize the initParam list in Gather or Gather merge node such that
                               2672                 :                :  *    it contains reference of all the params that needs to be evaluated
                               2673                 :                :  *    before execution of the node.  It contains the initplan params that are
                               2674                 :                :  *    being passed to the plan nodes below it.
                               2675                 :                :  */
                               2676                 :                : static void
 3252 rhaas@postgresql.org     2677                 :           1267 : set_param_references(PlannerInfo *root, Plan *plan)
                               2678                 :                : {
 2340 tgl@sss.pgh.pa.us        2679   [ +  +  -  + ]:           1267 :     Assert(IsA(plan, Gather) || IsA(plan, GatherMerge));
                               2680                 :                : 
 3252 rhaas@postgresql.org     2681         [ +  + ]:           1267 :     if (plan->lefttree->extParam)
                               2682                 :                :     {
                               2683                 :                :         PlannerInfo *proot;
                               2684                 :           1160 :         Bitmapset  *initSetParam = NULL;
                               2685                 :                :         ListCell   *l;
                               2686                 :                : 
                               2687         [ +  + ]:           2470 :         for (proot = root; proot != NULL; proot = proot->parent_root)
                               2688                 :                :         {
                               2689   [ +  +  +  +  :           1375 :             foreach(l, proot->init_plans)
                                              +  + ]
                               2690                 :                :             {
                               2691                 :             65 :                 SubPlan    *initsubplan = (SubPlan *) lfirst(l);
                               2692                 :                :                 ListCell   *l2;
                               2693                 :                : 
                               2694   [ +  -  +  +  :            130 :                 foreach(l2, initsubplan->setParam)
                                              +  + ]
                               2695                 :                :                 {
                               2696                 :             65 :                     initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
                               2697                 :                :                 }
                               2698                 :                :             }
                               2699                 :                :         }
                               2700                 :                : 
                               2701                 :                :         /*
                               2702                 :                :          * Remember the list of all external initplan params that are used by
                               2703                 :                :          * the children of Gather or Gather merge node.
                               2704                 :                :          */
                               2705         [ +  + ]:           1160 :         if (IsA(plan, Gather))
                               2706                 :            852 :             ((Gather *) plan)->initParam =
                               2707                 :            852 :                 bms_intersect(plan->lefttree->extParam, initSetParam);
                               2708                 :                :         else
                               2709                 :            308 :             ((GatherMerge *) plan)->initParam =
                               2710                 :            308 :                 bms_intersect(plan->lefttree->extParam, initSetParam);
                               2711                 :                :     }
                               2712                 :           1267 : }
                               2713                 :                : 
                               2714                 :                : /*
                               2715                 :                :  * Recursively scan an expression tree and convert Aggrefs to the proper
                               2716                 :                :  * intermediate form for combining aggregates.  This means (1) replacing each
                               2717                 :                :  * one's argument list with a single argument that is the original Aggref
                               2718                 :                :  * modified to show partial aggregation and (2) changing the upper Aggref to
                               2719                 :                :  * show combining aggregation.
                               2720                 :                :  *
                               2721                 :                :  * After this step, set_upper_references will replace the partial Aggrefs
                               2722                 :                :  * with Vars referencing the lower Agg plan node's outputs, so that the final
                               2723                 :                :  * form seen by the executor is a combining Aggref with a Var as input.
                               2724                 :                :  *
                               2725                 :                :  * It's rather messy to postpone this step until setrefs.c; ideally it'd be
                               2726                 :                :  * done in createplan.c.  The difficulty is that once we modify the Aggref
                               2727                 :                :  * expressions, they will no longer be equal() to their original form and
                               2728                 :                :  * so cross-plan-node-level matches will fail.  So this has to happen after
                               2729                 :                :  * the plan node above the Agg has resolved its subplan references.
                               2730                 :                :  */
                               2731                 :                : static Node *
 3760 tgl@sss.pgh.pa.us        2732                 :           8851 : convert_combining_aggrefs(Node *node, void *context)
                               2733                 :                : {
                               2734         [ +  + ]:           8851 :     if (node == NULL)
                               2735                 :           1082 :         return NULL;
                               2736         [ +  + ]:           7769 :     if (IsA(node, Aggref))
                               2737                 :                :     {
                               2738                 :           1986 :         Aggref     *orig_agg = (Aggref *) node;
                               2739                 :                :         Aggref     *child_agg;
                               2740                 :                :         Aggref     *parent_agg;
                               2741                 :                : 
                               2742                 :                :         /* Assert we've not chosen to partial-ize any unsupported cases */
 3733                          2743         [ -  + ]:           1986 :         Assert(orig_agg->aggorder == NIL);
                               2744         [ -  + ]:           1986 :         Assert(orig_agg->aggdistinct == NIL);
                               2745                 :                : 
                               2746                 :                :         /*
                               2747                 :                :          * Since aggregate calls can't be nested, we needn't recurse into the
                               2748                 :                :          * arguments.  But for safety, flat-copy the Aggref node itself rather
                               2749                 :                :          * than modifying it in-place.
                               2750                 :                :          */
 3760                          2751                 :           1986 :         child_agg = makeNode(Aggref);
                               2752                 :           1986 :         memcpy(child_agg, orig_agg, sizeof(Aggref));
                               2753                 :                : 
                               2754                 :                :         /*
                               2755                 :                :          * For the parent Aggref, we want to copy all the fields of the
                               2756                 :                :          * original aggregate *except* the args list, which we'll replace
                               2757                 :                :          * below, and the aggfilter expression, which should be applied only
                               2758                 :                :          * by the child not the parent.  Rather than explicitly knowing about
                               2759                 :                :          * all the other fields here, we can momentarily modify child_agg to
                               2760                 :                :          * provide a suitable source for copyObject.
                               2761                 :                :          */
                               2762                 :           1986 :         child_agg->args = NIL;
 3733                          2763                 :           1986 :         child_agg->aggfilter = NULL;
 3504 peter_e@gmx.net          2764                 :           1986 :         parent_agg = copyObject(child_agg);
 3760 tgl@sss.pgh.pa.us        2765                 :           1986 :         child_agg->args = orig_agg->args;
 3733                          2766                 :           1986 :         child_agg->aggfilter = orig_agg->aggfilter;
                               2767                 :                : 
                               2768                 :                :         /*
                               2769                 :                :          * Now, set up child_agg to represent the first phase of partial
                               2770                 :                :          * aggregation.  For now, assume serialization is required.
                               2771                 :                :          */
 3760                          2772                 :           1986 :         mark_partial_aggref(child_agg, AGGSPLIT_INITIAL_SERIAL);
                               2773                 :                : 
                               2774                 :                :         /*
                               2775                 :                :          * And set up parent_agg to represent the second phase.
                               2776                 :                :          */
                               2777                 :           1986 :         parent_agg->args = list_make1(makeTargetEntry((Expr *) child_agg,
                               2778                 :                :                                                       1, NULL, false));
                               2779                 :           1986 :         mark_partial_aggref(parent_agg, AGGSPLIT_FINAL_DESERIAL);
                               2780                 :                : 
                               2781                 :           1986 :         return (Node *) parent_agg;
                               2782                 :                :     }
  683 peter@eisentraut.org     2783                 :           5783 :     return expression_tree_mutator(node, convert_combining_aggrefs, context);
                               2784                 :                : }
                               2785                 :                : 
                               2786                 :                : /*
                               2787                 :                :  * set_dummy_tlist_references
                               2788                 :                :  *    Replace the targetlist of an upper-level plan node with a simple
                               2789                 :                :  *    list of OUTER_VAR references to its child.
                               2790                 :                :  *
                               2791                 :                :  * This is used for plan types like Sort and Append that don't evaluate
                               2792                 :                :  * their targetlists.  Although the executor doesn't care at all what's in
                               2793                 :                :  * the tlist, EXPLAIN needs it to be realistic.
                               2794                 :                :  *
                               2795                 :                :  * Note: we could almost use set_upper_references() here, but it fails for
                               2796                 :                :  * Append for lack of a lefttree subplan.  Single-purpose code is faster
                               2797                 :                :  * anyway.
                               2798                 :                :  */
                               2799                 :                : static void
 7171 tgl@sss.pgh.pa.us        2800                 :         131029 : set_dummy_tlist_references(Plan *plan, int rtoffset)
                               2801                 :                : {
                               2802                 :                :     List       *output_targetlist;
                               2803                 :                :     ListCell   *l;
                               2804                 :                : 
                               2805                 :         131029 :     output_targetlist = NIL;
                               2806   [ +  +  +  +  :         553219 :     foreach(l, plan->targetlist)
                                              +  + ]
                               2807                 :                :     {
                               2808                 :         422190 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               2809                 :         422190 :         Var        *oldvar = (Var *) tle->expr;
                               2810                 :                :         Var        *newvar;
                               2811                 :                : 
                               2812                 :                :         /*
                               2813                 :                :          * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
                               2814                 :                :          * as Consts, not Vars referencing Consts.  Here, there's no speed
                               2815                 :                :          * advantage to be had, but it makes EXPLAIN output look cleaner, and
                               2816                 :                :          * again it avoids confusing the executor.
                               2817                 :                :          */
 3631                          2818         [ +  + ]:         422190 :         if (IsA(oldvar, Const))
                               2819                 :                :         {
                               2820                 :                :             /* just reuse the existing TLE node */
                               2821                 :          11976 :             output_targetlist = lappend(output_targetlist, tle);
                               2822                 :          11976 :             continue;
                               2823                 :                :         }
                               2824                 :                : 
 5480                          2825                 :         410214 :         newvar = makeVar(OUTER_VAR,
 7171                          2826                 :         410214 :                          tle->resno,
                               2827                 :                :                          exprType((Node *) oldvar),
                               2828                 :                :                          exprTypmod((Node *) oldvar),
                               2829                 :                :                          exprCollation((Node *) oldvar),
                               2830                 :                :                          0);
 2468                          2831         [ +  + ]:         410214 :         if (IsA(oldvar, Var) &&
                               2832         [ +  + ]:         326714 :             oldvar->varnosyn > 0)
                               2833                 :                :         {
                               2834                 :         294063 :             newvar->varnosyn = oldvar->varnosyn + rtoffset;
                               2835                 :         294063 :             newvar->varattnosyn = oldvar->varattnosyn;
                               2836                 :                :         }
                               2837                 :                :         else
                               2838                 :                :         {
                               2839                 :         116151 :             newvar->varnosyn = 0;    /* wasn't ever a plain Var */
                               2840                 :         116151 :             newvar->varattnosyn = 0;
                               2841                 :                :         }
                               2842                 :                : 
 7171                          2843                 :         410214 :         tle = flatCopyTargetEntry(tle);
                               2844                 :         410214 :         tle->expr = (Expr *) newvar;
                               2845                 :         410214 :         output_targetlist = lappend(output_targetlist, tle);
                               2846                 :                :     }
                               2847                 :         131029 :     plan->targetlist = output_targetlist;
                               2848                 :                : 
                               2849                 :                :     /* We don't touch plan->qual here */
                               2850                 :         131029 : }
                               2851                 :                : 
                               2852                 :                : 
                               2853                 :                : /*
                               2854                 :                :  * build_tlist_index --- build an index data structure for a child tlist
                               2855                 :                :  *
                               2856                 :                :  * In most cases, subplan tlists will be "flat" tlists with only Vars,
                               2857                 :                :  * so we try to optimize that case by extracting information about Vars
                               2858                 :                :  * in advance.  Matching a parent tlist to a child is still an O(N^2)
                               2859                 :                :  * operation, but at least with a much smaller constant factor than plain
                               2860                 :                :  * tlist_member() searches.
                               2861                 :                :  *
                               2862                 :                :  * The result of this function is an indexed_tlist struct to pass to
                               2863                 :                :  * search_indexed_tlist_for_var() and siblings.
                               2864                 :                :  * When done, the indexed_tlist may be freed with a single pfree().
                               2865                 :                :  */
                               2866                 :                : static indexed_tlist *
 7794                          2867                 :         332687 : build_tlist_index(List *tlist)
                               2868                 :                : {
                               2869                 :                :     indexed_tlist *itlist;
                               2870                 :                :     tlist_vinfo *vinfo;
                               2871                 :                :     ListCell   *l;
                               2872                 :                : 
                               2873                 :                :     /* Create data structure with enough slots for all tlist entries */
                               2874                 :                :     itlist = (indexed_tlist *)
                               2875                 :         332687 :         palloc(offsetof(indexed_tlist, vars) +
                               2876                 :         332687 :                list_length(tlist) * sizeof(tlist_vinfo));
                               2877                 :                : 
                               2878                 :         332687 :     itlist->tlist = tlist;
 6565                          2879                 :         332687 :     itlist->has_ph_vars = false;
 7794                          2880                 :         332687 :     itlist->has_non_vars = false;
                               2881                 :                : 
                               2882                 :                :     /* Find the Vars and fill in the index array */
                               2883                 :         332687 :     vinfo = itlist->vars;
 8666                          2884   [ +  +  +  +  :        2948787 :     foreach(l, tlist)
                                              +  + ]
                               2885                 :                :     {
                               2886                 :        2616100 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               2887                 :                : 
 7794                          2888   [ +  -  +  + ]:        2616100 :         if (tle->expr && IsA(tle->expr, Var))
                               2889                 :        2598595 :         {
 7667 bruce@momjian.us         2890                 :        2598595 :             Var        *var = (Var *) tle->expr;
                               2891                 :                : 
 7794 tgl@sss.pgh.pa.us        2892                 :        2598595 :             vinfo->varno = var->varno;
                               2893                 :        2598595 :             vinfo->varattno = var->varattno;
                               2894                 :        2598595 :             vinfo->resno = tle->resno;
 1351                          2895                 :        2598595 :             vinfo->varnullingrels = var->varnullingrels;
 7794                          2896                 :        2598595 :             vinfo++;
                               2897                 :                :         }
 6565                          2898   [ +  -  +  + ]:          17505 :         else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
                               2899                 :           3574 :             itlist->has_ph_vars = true;
                               2900                 :                :         else
 7794                          2901                 :          13931 :             itlist->has_non_vars = true;
                               2902                 :                :     }
                               2903                 :                : 
                               2904                 :         332687 :     itlist->num_vars = (vinfo - itlist->vars);
                               2905                 :                : 
                               2906                 :         332687 :     return itlist;
                               2907                 :                : }
                               2908                 :                : 
                               2909                 :                : /*
                               2910                 :                :  * build_tlist_index_other_vars --- build a restricted tlist index
                               2911                 :                :  *
                               2912                 :                :  * This is like build_tlist_index, but we only index tlist entries that
                               2913                 :                :  * are Vars belonging to some rel other than the one specified.  We will set
                               2914                 :                :  * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
                               2915                 :                :  * (so nothing other than Vars and PlaceHolderVars can be matched).
                               2916                 :                :  */
                               2917                 :                : static indexed_tlist *
 1853                          2918                 :           2907 : build_tlist_index_other_vars(List *tlist, int ignore_rel)
                               2919                 :                : {
                               2920                 :                :     indexed_tlist *itlist;
                               2921                 :                :     tlist_vinfo *vinfo;
                               2922                 :                :     ListCell   *l;
                               2923                 :                : 
                               2924                 :                :     /* Create data structure with enough slots for all tlist entries */
                               2925                 :                :     itlist = (indexed_tlist *)
 7366                          2926                 :           2907 :         palloc(offsetof(indexed_tlist, vars) +
                               2927                 :           2907 :                list_length(tlist) * sizeof(tlist_vinfo));
                               2928                 :                : 
                               2929                 :           2907 :     itlist->tlist = tlist;
 6565                          2930                 :           2907 :     itlist->has_ph_vars = false;
 7366                          2931                 :           2907 :     itlist->has_non_vars = false;
                               2932                 :                : 
                               2933                 :                :     /* Find the desired Vars and fill in the index array */
                               2934                 :           2907 :     vinfo = itlist->vars;
                               2935   [ +  +  +  +  :          11221 :     foreach(l, tlist)
                                              +  + ]
                               2936                 :                :     {
                               2937                 :           8314 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
                               2938                 :                : 
                               2939   [ +  -  +  + ]:           8314 :         if (tle->expr && IsA(tle->expr, Var))
                               2940                 :           4378 :         {
                               2941                 :           4378 :             Var        *var = (Var *) tle->expr;
                               2942                 :                : 
                               2943         [ +  + ]:           4378 :             if (var->varno != ignore_rel)
                               2944                 :                :             {
                               2945                 :           3438 :                 vinfo->varno = var->varno;
                               2946                 :           3438 :                 vinfo->varattno = var->varattno;
                               2947                 :           3438 :                 vinfo->resno = tle->resno;
 1351                          2948                 :           3438 :                 vinfo->varnullingrels = var->varnullingrels;
 7366                          2949                 :           3438 :                 vinfo++;
                               2950                 :                :             }
                               2951                 :                :         }
 6565                          2952   [ +  -  +  + ]:           3936 :         else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
                               2953                 :             93 :             itlist->has_ph_vars = true;
                               2954                 :                :     }
                               2955                 :                : 
 7366                          2956                 :           2907 :     itlist->num_vars = (vinfo - itlist->vars);
                               2957                 :                : 
                               2958                 :           2907 :     return itlist;
                               2959                 :                : }
                               2960                 :                : 
                               2961                 :                : /*
                               2962                 :                :  * search_indexed_tlist_for_var --- find a Var in an indexed tlist
                               2963                 :                :  *
                               2964                 :                :  * If a match is found, return a copy of the given Var with suitably
                               2965                 :                :  * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
                               2966                 :                :  * Also ensure that varnosyn is incremented by rtoffset.
                               2967                 :                :  * If no match, return NULL.
                               2968                 :                :  *
                               2969                 :                :  * We cross-check the varnullingrels of the subplan output Var based on
                               2970                 :                :  * nrm_match.  Most call sites should pass NRM_EQUAL indicating we expect
                               2971                 :                :  * an exact match.  However, there are places where we haven't cleaned
                               2972                 :                :  * things up completely, and we have to settle for allowing superset matches.
                               2973                 :                :  */
                               2974                 :                : static Var *
 7172                          2975                 :        1263994 : search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
                               2976                 :                :                              int newvarno, int rtoffset,
                               2977                 :                :                              NullingRelsMatch nrm_match)
                               2978                 :                : {
 1853                          2979                 :        1263994 :     int         varno = var->varno;
 7794                          2980                 :        1263994 :     AttrNumber  varattno = var->varattno;
                               2981                 :                :     tlist_vinfo *vinfo;
                               2982                 :                :     int         i;
                               2983                 :                : 
                               2984                 :        1263994 :     vinfo = itlist->vars;
                               2985                 :        1263994 :     i = itlist->num_vars;
                               2986         [ +  + ]:        8379356 :     while (i-- > 0)
                               2987                 :                :     {
                               2988   [ +  +  +  + ]:        8076341 :         if (vinfo->varno == varno && vinfo->varattno == varattno)
                               2989                 :                :         {
                               2990                 :                :             /* Found a match */
 7105                          2991                 :         960979 :             Var        *newvar = copyVar(var);
                               2992                 :                : 
                               2993                 :                :             /*
                               2994                 :                :              * Verify that we kept all the nullingrels machinations straight.
                               2995                 :                :              *
                               2996                 :                :              * XXX we skip the check for system columns and whole-row Vars.
                               2997                 :                :              * That's because such Vars might be row identity Vars, which are
                               2998                 :                :              * generated without any varnullingrels.  It'd be hard to do
                               2999                 :                :              * otherwise, since they're normally made very early in planning,
                               3000                 :                :              * when we haven't looked at the jointree yet and don't know which
                               3001                 :                :              * joins might null such Vars.  Doesn't seem worth the expense to
                               3002                 :                :              * make them fully valid.  (While it's slightly annoying that we
                               3003                 :                :              * thereby lose checking for user-written references to such
                               3004                 :                :              * columns, it seems unlikely that a bug in nullingrels logic
                               3005                 :                :              * would affect only system columns.)
                               3006                 :                :              */
 1244                          3007   [ +  +  +  +  :        1897618 :             if (!(varattno <= 0 ||
                                        -  +  -  + ]
                               3008                 :                :                   (nrm_match == NRM_SUPERSET ?
                               3009                 :         233697 :                    bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
                               3010                 :         702942 :                    bms_equal(vinfo->varnullingrels, var->varnullingrels))))
 1244 tgl@sss.pgh.pa.us        3011         [ #  # ]:UBC           0 :                 elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
                               3012                 :                :                      bmsToString(var->varnullingrels),
                               3013                 :                :                      bmsToString(vinfo->varnullingrels),
                               3014                 :                :                      varno, varattno);
                               3015                 :                : 
 7794 tgl@sss.pgh.pa.us        3016                 :CBC      960979 :             newvar->varno = newvarno;
                               3017                 :         960979 :             newvar->varattno = vinfo->resno;
 2468                          3018         [ +  + ]:         960979 :             if (newvar->varnosyn > 0)
                               3019                 :         960544 :                 newvar->varnosyn += rtoffset;
 7794                          3020                 :         960979 :             return newvar;
                               3021                 :                :         }
                               3022                 :        7115362 :         vinfo++;
                               3023                 :                :     }
                               3024                 :         303015 :     return NULL;                /* no match */
                               3025                 :                : }
                               3026                 :                : 
                               3027                 :                : /*
                               3028                 :                :  * search_indexed_tlist_for_phv --- find a PlaceHolderVar in an indexed tlist
                               3029                 :                :  *
                               3030                 :                :  * If a match is found, return a Var constructed to reference the tlist item.
                               3031                 :                :  * If no match, return NULL.
                               3032                 :                :  *
                               3033                 :                :  * Cross-check phnullingrels as in search_indexed_tlist_for_var.
                               3034                 :                :  *
                               3035                 :                :  * NOTE: it is a waste of time to call this unless itlist->has_ph_vars.
                               3036                 :                :  */
                               3037                 :                : static Var *
 1351                          3038                 :           3729 : search_indexed_tlist_for_phv(PlaceHolderVar *phv,
                               3039                 :                :                              indexed_tlist *itlist, int newvarno,
                               3040                 :                :                              NullingRelsMatch nrm_match)
                               3041                 :                : {
                               3042                 :                :     ListCell   *lc;
                               3043                 :                : 
                               3044   [ +  -  +  +  :           8734 :     foreach(lc, itlist->tlist)
                                              +  + ]
                               3045                 :                :     {
                               3046                 :           8389 :         TargetEntry *tle = (TargetEntry *) lfirst(lc);
                               3047                 :                : 
                               3048   [ +  -  +  + ]:           8389 :         if (tle->expr && IsA(tle->expr, PlaceHolderVar))
                               3049                 :                :         {
                               3050                 :           4787 :             PlaceHolderVar *subphv = (PlaceHolderVar *) tle->expr;
                               3051                 :                :             Var        *newvar;
                               3052                 :                : 
                               3053                 :                :             /*
                               3054                 :                :              * Analogously to search_indexed_tlist_for_var, we match on phid
                               3055                 :                :              * only.  We don't use equal(), partially for speed but mostly
                               3056                 :                :              * because phnullingrels might not be exactly equal.
                               3057                 :                :              */
                               3058         [ +  + ]:           4787 :             if (phv->phid != subphv->phid)
                               3059                 :           1403 :                 continue;
                               3060                 :                : 
                               3061                 :                :             /* Verify that we kept all the nullingrels machinations straight */
   96 rguo@postgresql.org      3062   [ +  +  -  + ]:GNC        6768 :             if (!(nrm_match == NRM_SUPERSET ?
 1244 tgl@sss.pgh.pa.us        3063                 :CBC        1618 :                   bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
                               3064                 :           1766 :                   bms_equal(subphv->phnullingrels, phv->phnullingrels)))
 1244 tgl@sss.pgh.pa.us        3065         [ #  # ]:UBC           0 :                 elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
                               3066                 :                :                      bmsToString(phv->phnullingrels),
                               3067                 :                :                      bmsToString(subphv->phnullingrels),
                               3068                 :                :                      phv->phid);
                               3069                 :                : 
                               3070                 :                :             /* Found a matching subplan output expression */
 1351 tgl@sss.pgh.pa.us        3071                 :CBC        3384 :             newvar = makeVarFromTargetEntry(newvarno, tle);
                               3072                 :           3384 :             newvar->varnosyn = 0;    /* wasn't ever a plain Var */
                               3073                 :           3384 :             newvar->varattnosyn = 0;
                               3074                 :           3384 :             return newvar;
                               3075                 :                :         }
                               3076                 :                :     }
                               3077                 :            345 :     return NULL;                /* no match */
                               3078                 :                : }
                               3079                 :                : 
                               3080                 :                : /*
                               3081                 :                :  * search_indexed_tlist_for_non_var --- find a non-Var/PHV in an indexed tlist
                               3082                 :                :  *
                               3083                 :                :  * If a match is found, return a Var constructed to reference the tlist item.
                               3084                 :                :  * If no match, return NULL.
                               3085                 :                :  *
                               3086                 :                :  * NOTE: it is a waste of time to call this unless itlist->has_non_vars.
                               3087                 :                :  */
                               3088                 :                : static Var *
 3504 peter_e@gmx.net          3089                 :          31140 : search_indexed_tlist_for_non_var(Expr *node,
                               3090                 :                :                                  indexed_tlist *itlist, int newvarno)
                               3091                 :                : {
                               3092                 :                :     TargetEntry *tle;
                               3093                 :                : 
                               3094                 :                :     /*
                               3095                 :                :      * If it's a simple Const, replacing it with a Var is silly, even if there
                               3096                 :                :      * happens to be an identical Const below; a Var is more expensive to
                               3097                 :                :      * execute than a Const.  What's more, replacing it could confuse some
                               3098                 :                :      * places in the executor that expect to see simple Consts for, eg,
                               3099                 :                :      * dropped columns.
                               3100                 :                :      */
 3631 tgl@sss.pgh.pa.us        3101         [ +  + ]:          31140 :     if (IsA(node, Const))
                               3102                 :           1493 :         return NULL;
                               3103                 :                : 
 7794                          3104                 :          29647 :     tle = tlist_member(node, itlist->tlist);
                               3105         [ +  + ]:          29647 :     if (tle)
                               3106                 :                :     {
                               3107                 :                :         /* Found a matching subplan output expression */
                               3108                 :                :         Var        *newvar;
                               3109                 :                : 
 5890 peter_e@gmx.net          3110                 :           7392 :         newvar = makeVarFromTargetEntry(newvarno, tle);
 2468 tgl@sss.pgh.pa.us        3111                 :           7392 :         newvar->varnosyn = 0;    /* wasn't ever a plain Var */
                               3112                 :           7392 :         newvar->varattnosyn = 0;
 7794                          3113                 :           7392 :         return newvar;
                               3114                 :                :     }
                               3115                 :          22255 :     return NULL;                /* no match */
                               3116                 :                : }
                               3117                 :                : 
                               3118                 :                : /*
                               3119                 :                :  * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
                               3120                 :                :  *
                               3121                 :                :  * If a match is found, return a Var constructed to reference the tlist item.
                               3122                 :                :  * If no match, return NULL.
                               3123                 :                :  *
                               3124                 :                :  * This is needed to ensure that we select the right subplan TLE in cases
                               3125                 :                :  * where there are multiple textually-equal()-but-volatile sort expressions.
                               3126                 :                :  * And it's also faster than search_indexed_tlist_for_non_var.
                               3127                 :                :  */
                               3128                 :                : static Var *
 3504 peter_e@gmx.net          3129                 :          33497 : search_indexed_tlist_for_sortgroupref(Expr *node,
                               3130                 :                :                                       Index sortgroupref,
                               3131                 :                :                                       indexed_tlist *itlist,
                               3132                 :                :                                       int newvarno)
                               3133                 :                : {
                               3134                 :                :     ListCell   *lc;
                               3135                 :                : 
 6174 tgl@sss.pgh.pa.us        3136   [ +  +  +  +  :          72069 :     foreach(lc, itlist->tlist)
                                              +  + ]
                               3137                 :                :     {
                               3138                 :          53624 :         TargetEntry *tle = (TargetEntry *) lfirst(lc);
                               3139                 :                : 
                               3140                 :                :         /*
                               3141                 :                :          * Usually the equal() check is redundant, but in setop plans it may
                               3142                 :                :          * not be, since prepunion.c assigns ressortgroupref equal to the
                               3143                 :                :          * column resno without regard to whether that matches the topmost
                               3144                 :                :          * level's sortgrouprefs and without regard to whether any implicit
                               3145                 :                :          * coercions are added in the setop tree.  We might have to clean that
                               3146                 :                :          * up someday; but for now, just ignore any false matches.
                               3147                 :                :          */
                               3148   [ +  +  +  + ]:          68791 :         if (tle->ressortgroupref == sortgroupref &&
                               3149                 :          15167 :             equal(node, tle->expr))
                               3150                 :                :         {
                               3151                 :                :             /* Found a matching subplan output expression */
                               3152                 :                :             Var        *newvar;
                               3153                 :                : 
 5890 peter_e@gmx.net          3154                 :          15052 :             newvar = makeVarFromTargetEntry(newvarno, tle);
 2468 tgl@sss.pgh.pa.us        3155                 :          15052 :             newvar->varnosyn = 0;    /* wasn't ever a plain Var */
                               3156                 :          15052 :             newvar->varattnosyn = 0;
 6174                          3157                 :          15052 :             return newvar;
                               3158                 :                :         }
                               3159                 :                :     }
                               3160                 :          18445 :     return NULL;                /* no match */
                               3161                 :                : }
                               3162                 :                : 
                               3163                 :                : /*
                               3164                 :                :  * fix_join_expr
                               3165                 :                :  *     Create a new set of targetlist entries or join qual clauses by
                               3166                 :                :  *     changing the varno/varattno values of variables in the clauses
                               3167                 :                :  *     to reference target list values from the outer and inner join
                               3168                 :                :  *     relation target lists.  Also perform opcode lookup and add
                               3169                 :                :  *     regclass OIDs to root->glob->relationOids.
                               3170                 :                :  *
                               3171                 :                :  * This is used in four different scenarios:
                               3172                 :                :  * 1) a normal join clause, where all the Vars in the clause *must* be
                               3173                 :                :  *    replaced by OUTER_VAR or INNER_VAR references.  In this case
                               3174                 :                :  *    acceptable_rel should be zero so that any failure to match a Var will be
                               3175                 :                :  *    reported as an error.
                               3176                 :                :  * 2) RETURNING clauses, which may contain both Vars of the target relation
                               3177                 :                :  *    and Vars of other relations. In this case we want to replace the
                               3178                 :                :  *    other-relation Vars by OUTER_VAR references, while leaving target Vars
                               3179                 :                :  *    alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
                               3180                 :                :  *    target relation should be passed.
                               3181                 :                :  * 3) ON CONFLICT SET and WHERE clauses.  Here references to EXCLUDED are
                               3182                 :                :  *    to be replaced with INNER_VAR references, while leaving target Vars (the
                               3183                 :                :  *    to-be-updated relation) alone. Correspondingly inner_itlist is to be
                               3184                 :                :  *    EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
                               3185                 :                :  *    relation.
                               3186                 :                :  * 4) MERGE.  In this case, references to the source relation are to be
                               3187                 :                :  *    replaced with INNER_VAR references, leaving Vars of the target
                               3188                 :                :  *    relation (the to-be-modified relation) alone.  So inner_itlist is to be
                               3189                 :                :  *    the source relation elements, outer_itlist = NULL and acceptable_rel
                               3190                 :                :  *    the target relation.
                               3191                 :                :  *
                               3192                 :                :  * 'clauses' is the targetlist or list of join clauses
                               3193                 :                :  * 'outer_itlist' is the indexed target list of the outer join relation,
                               3194                 :                :  *      or NULL
                               3195                 :                :  * 'inner_itlist' is the indexed target list of the inner join relation,
                               3196                 :                :  *      or NULL
                               3197                 :                :  * 'acceptable_rel' is either zero or the rangetable index of a relation
                               3198                 :                :  *      whose Vars may appear in the clause without provoking an error
                               3199                 :                :  * 'rtoffset': how much to increment varnos by
                               3200                 :                :  * 'nrm_match': as for search_indexed_tlist_for_var()
                               3201                 :                :  * 'num_exec': estimated number of executions of expression
                               3202                 :                :  *
                               3203                 :                :  * Returns the new expression tree.  The original clause structure is
                               3204                 :                :  * not modified.
                               3205                 :                :  */
                               3206                 :                : static List *
 5518                          3207                 :         383402 : fix_join_expr(PlannerInfo *root,
                               3208                 :                :               List *clauses,
                               3209                 :                :               indexed_tlist *outer_itlist,
                               3210                 :                :               indexed_tlist *inner_itlist,
                               3211                 :                :               Index acceptable_rel,
                               3212                 :                :               int rtoffset,
                               3213                 :                :               NullingRelsMatch nrm_match,
                               3214                 :                :               double num_exec)
                               3215                 :                : {
                               3216                 :                :     fix_join_expr_context context;
                               3217                 :                : 
                               3218                 :         383402 :     context.root = root;
 7794                          3219                 :         383402 :     context.outer_itlist = outer_itlist;
                               3220                 :         383402 :     context.inner_itlist = inner_itlist;
 9913                          3221                 :         383402 :     context.acceptable_rel = acceptable_rel;
 7172                          3222                 :         383402 :     context.rtoffset = rtoffset;
 1351                          3223                 :         383402 :     context.nrm_match = nrm_match;
 2206                          3224                 :         383402 :     context.num_exec = num_exec;
 7172                          3225                 :         383402 :     return (List *) fix_join_expr_mutator((Node *) clauses, &context);
                               3226                 :                : }
                               3227                 :                : 
                               3228                 :                : static Node *
 6906 bruce@momjian.us         3229                 :        2445802 : fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
                               3230                 :                : {
                               3231                 :                :     Var        *newvar;
                               3232                 :                : 
 9926 tgl@sss.pgh.pa.us        3233         [ +  + ]:        2445802 :     if (node == NULL)
                               3234                 :         240687 :         return NULL;
                               3235         [ +  + ]:        2205115 :     if (IsA(node, Var))
                               3236                 :                :     {
                               3237                 :         784231 :         Var        *var = (Var *) node;
                               3238                 :                : 
                               3239                 :                :         /*
                               3240                 :                :          * Verify that Vars with non-default varreturningtype only appear in
                               3241                 :                :          * the RETURNING list, and refer to the target relation.
                               3242                 :                :          */
  634 dean.a.rasheed@gmail     3243         [ +  + ]:         784231 :         if (var->varreturningtype != VAR_RETURNING_DEFAULT)
                               3244                 :                :         {
                               3245         [ +  - ]:           2581 :             if (context->inner_itlist != NULL ||
                               3246         [ +  - ]:           2581 :                 context->outer_itlist == NULL ||
                               3247         [ -  + ]:           2581 :                 context->acceptable_rel == 0)
  634 dean.a.rasheed@gmail     3248         [ #  # ]:UBC           0 :                 elog(ERROR, "variable returning old/new found outside RETURNING list");
  634 dean.a.rasheed@gmail     3249         [ -  + ]:CBC        2581 :             if (var->varno != context->acceptable_rel)
  634 dean.a.rasheed@gmail     3250         [ #  # ]:UBC           0 :                 elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
                               3251                 :                :                      var->varno, context->acceptable_rel);
                               3252                 :                :         }
                               3253                 :                : 
                               3254                 :                :         /* Look for the var in the input tlists, first in the outer */
 4175 andres@anarazel.de       3255         [ +  + ]:CBC      784231 :         if (context->outer_itlist)
                               3256                 :                :         {
                               3257                 :         778152 :             newvar = search_indexed_tlist_for_var(var,
                               3258                 :                :                                                   context->outer_itlist,
                               3259                 :                :                                                   OUTER_VAR,
                               3260                 :                :                                                   context->rtoffset,
                               3261                 :                :                                                   context->nrm_match);
                               3262         [ +  + ]:         778152 :             if (newvar)
                               3263                 :         477885 :                 return (Node *) newvar;
                               3264                 :                :         }
                               3265                 :                : 
                               3266                 :                :         /* then in the inner. */
 7794 tgl@sss.pgh.pa.us        3267         [ +  + ]:         306346 :         if (context->inner_itlist)
                               3268                 :                :         {
                               3269                 :         296959 :             newvar = search_indexed_tlist_for_var(var,
                               3270                 :                :                                                   context->inner_itlist,
                               3271                 :                :                                                   INNER_VAR,
                               3272                 :                :                                                   context->rtoffset,
                               3273                 :                :                                                   context->nrm_match);
                               3274         [ +  + ]:         296959 :             if (newvar)
                               3275                 :         294211 :                 return (Node *) newvar;
                               3276                 :                :         }
                               3277                 :                : 
                               3278                 :                :         /* If it's for acceptable_rel, adjust and return it */
 8728                          3279         [ +  - ]:          12135 :         if (var->varno == context->acceptable_rel)
                               3280                 :                :         {
 7105                          3281                 :          12135 :             var = copyVar(var);
 5283                          3282                 :          12135 :             var->varno += context->rtoffset;
 2468                          3283         [ +  + ]:          12135 :             if (var->varnosyn > 0)
                               3284                 :          11568 :                 var->varnosyn += context->rtoffset;
 7172                          3285                 :          12135 :             return (Node *) var;
                               3286                 :                :         }
                               3287                 :                : 
                               3288                 :                :         /* No referent found for Var */
 8480 tgl@sss.pgh.pa.us        3289         [ #  # ]:UBC           0 :         elog(ERROR, "variable not found in subplan target lists");
                               3290                 :                :     }
 6565 tgl@sss.pgh.pa.us        3291         [ +  + ]:CBC     1420884 :     if (IsA(node, PlaceHolderVar))
                               3292                 :                :     {
                               3293                 :           2734 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               3294                 :                : 
                               3295                 :                :         /* See if the PlaceHolderVar has bubbled up from a lower plan node */
 4175 andres@anarazel.de       3296   [ +  +  +  + ]:           2734 :         if (context->outer_itlist && context->outer_itlist->has_ph_vars)
                               3297                 :                :         {
 1351 tgl@sss.pgh.pa.us        3298                 :           1110 :             newvar = search_indexed_tlist_for_phv(phv,
                               3299                 :                :                                                   context->outer_itlist,
                               3300                 :                :                                                   OUTER_VAR,
                               3301                 :                :                                                   context->nrm_match);
 6565                          3302         [ +  + ]:           1110 :             if (newvar)
                               3303                 :            810 :                 return (Node *) newvar;
                               3304                 :                :         }
                               3305   [ +  -  +  + ]:           1924 :         if (context->inner_itlist && context->inner_itlist->has_ph_vars)
                               3306                 :                :         {
 1351                          3307                 :           1546 :             newvar = search_indexed_tlist_for_phv(phv,
                               3308                 :                :                                                   context->inner_itlist,
                               3309                 :                :                                                   INNER_VAR,
                               3310                 :                :                                                   context->nrm_match);
 6565                          3311         [ +  + ]:           1546 :             if (newvar)
                               3312                 :           1501 :                 return (Node *) newvar;
                               3313                 :                :         }
                               3314                 :                : 
                               3315                 :                :         /* If not supplied by input plans, evaluate the contained expr */
                               3316                 :                :         /* XXX can we assert something about phnullingrels? */
                               3317                 :            423 :         return fix_join_expr_mutator((Node *) phv->phexpr, context);
                               3318                 :                :     }
                               3319                 :                :     /* Try matching more complex expressions too, if tlists have any */
 2964 efujita@postgresql.o     3320   [ +  +  +  + ]:        1418150 :     if (context->outer_itlist && context->outer_itlist->has_non_vars)
                               3321                 :                :     {
 3504 peter_e@gmx.net          3322                 :           1827 :         newvar = search_indexed_tlist_for_non_var((Expr *) node,
                               3323                 :                :                                                   context->outer_itlist,
                               3324                 :                :                                                   OUTER_VAR);
 7794 tgl@sss.pgh.pa.us        3325         [ +  + ]:           1827 :         if (newvar)
 8666                          3326                 :            164 :             return (Node *) newvar;
                               3327                 :                :     }
 2964 efujita@postgresql.o     3328   [ +  +  +  + ]:        1417986 :     if (context->inner_itlist && context->inner_itlist->has_non_vars)
                               3329                 :                :     {
 3504 peter_e@gmx.net          3330                 :           5550 :         newvar = search_indexed_tlist_for_non_var((Expr *) node,
                               3331                 :                :                                                   context->inner_itlist,
                               3332                 :                :                                                   INNER_VAR);
 7794 tgl@sss.pgh.pa.us        3333         [ +  + ]:           5550 :         if (newvar)
 8666                          3334                 :            993 :             return (Node *) newvar;
                               3335                 :                :     }
                               3336                 :                :     /* Special cases (apply only AFTER failing to match to lower tlist) */
 2861                          3337         [ +  + ]:        1416993 :     if (IsA(node, Param))
                               3338                 :           4506 :         return fix_param_node(context->root, (Param *) node);
 2206                          3339         [ +  + ]:        1412487 :     if (IsA(node, AlternativeSubPlan))
                               3340                 :           1100 :         return fix_join_expr_mutator(fix_alternative_subplan(context->root,
                               3341                 :                :                                                              (AlternativeSubPlan *) node,
                               3342                 :                :                                                              context->num_exec),
                               3343                 :                :                                      context);
 5518                          3344                 :        1411387 :     fix_expr_common(context->root, node);
  683 peter@eisentraut.org     3345                 :        1411387 :     return expression_tree_mutator(node, fix_join_expr_mutator, context);
                               3346                 :                : }
                               3347                 :                : 
                               3348                 :                : /*
                               3349                 :                :  * fix_upper_expr
                               3350                 :                :  *      Modifies an expression tree so that all Var nodes reference outputs
                               3351                 :                :  *      of a subplan.  Also looks for Aggref nodes that should be replaced
                               3352                 :                :  *      by initplan output Params.  Also performs opcode lookup, and adds
                               3353                 :                :  *      regclass OIDs to root->glob->relationOids.
                               3354                 :                :  *
                               3355                 :                :  * This is used to fix up target and qual expressions of non-join upper-level
                               3356                 :                :  * plan nodes, as well as index-only scan nodes.
                               3357                 :                :  *
                               3358                 :                :  * An error is raised if no matching var can be found in the subplan tlist
                               3359                 :                :  * --- so this routine should only be applied to nodes whose subplans'
                               3360                 :                :  * targetlists were generated by flattening the expressions used in the
                               3361                 :                :  * parent node.
                               3362                 :                :  *
                               3363                 :                :  * If itlist->has_non_vars is true, then we try to match whole subexpressions
                               3364                 :                :  * against elements of the subplan tlist, so that we can avoid recomputing
                               3365                 :                :  * expressions that were already computed by the subplan.  (This is relatively
                               3366                 :                :  * expensive, so we don't want to try it in the common case where the
                               3367                 :                :  * subplan tlist is just a flattened list of Vars.)
                               3368                 :                :  *
                               3369                 :                :  * When cross-checking the nullingrels of the subplan output Vars/PHVs, we
                               3370                 :                :  * always expect exact matches.
                               3371                 :                :  *
                               3372                 :                :  * 'node': the tree to be fixed (a target item or qual)
                               3373                 :                :  * 'subplan_itlist': indexed target list for subplan (or index)
                               3374                 :                :  * 'newvarno': varno to use for Vars referencing tlist elements
                               3375                 :                :  * 'rtoffset': how much to increment varnos by
                               3376                 :                :  * 'num_exec': estimated number of executions of expression
                               3377                 :                :  *
                               3378                 :                :  * The resulting tree is a copy of the original in which all Var nodes have
                               3379                 :                :  * varno = newvarno, varattno = resno of corresponding targetlist element.
                               3380                 :                :  * The original tree is not modified.
                               3381                 :                :  */
                               3382                 :                : static Node *
 5518 tgl@sss.pgh.pa.us        3383                 :         294707 : fix_upper_expr(PlannerInfo *root,
                               3384                 :                :                Node *node,
                               3385                 :                :                indexed_tlist *subplan_itlist,
                               3386                 :                :                int newvarno,
                               3387                 :                :                int rtoffset,
                               3388                 :                :                double num_exec)
                               3389                 :                : {
                               3390                 :                :     fix_upper_expr_context context;
                               3391                 :                : 
                               3392                 :         294707 :     context.root = root;
 7794                          3393                 :         294707 :     context.subplan_itlist = subplan_itlist;
 5480                          3394                 :         294707 :     context.newvarno = newvarno;
 7172                          3395                 :         294707 :     context.rtoffset = rtoffset;
 2206                          3396                 :         294707 :     context.num_exec = num_exec;
 7172                          3397                 :         294707 :     return fix_upper_expr_mutator(node, &context);
                               3398                 :                : }
                               3399                 :                : 
                               3400                 :                : static Node *
 6906 bruce@momjian.us         3401                 :         844424 : fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
                               3402                 :                : {
                               3403                 :                :     Var        *newvar;
                               3404                 :                : 
 9926 tgl@sss.pgh.pa.us        3405         [ +  + ]:         844424 :     if (node == NULL)
 9913                          3406                 :         267529 :         return NULL;
 9926                          3407         [ +  + ]:         576895 :     if (IsA(node, Var))
                               3408                 :                :     {
                               3409                 :         188883 :         Var        *var = (Var *) node;
                               3410                 :                : 
 7794                          3411                 :         188883 :         newvar = search_indexed_tlist_for_var(var,
                               3412                 :                :                                               context->subplan_itlist,
                               3413                 :                :                                               context->newvarno,
                               3414                 :                :                                               context->rtoffset,
                               3415                 :                :                                               NRM_EQUAL);
                               3416         [ -  + ]:         188883 :         if (!newvar)
 8480 tgl@sss.pgh.pa.us        3417         [ #  # ]:UBC           0 :             elog(ERROR, "variable not found in subplan target list");
 9913 tgl@sss.pgh.pa.us        3418                 :CBC      188883 :         return (Node *) newvar;
                               3419                 :                :     }
 6565                          3420         [ +  + ]:         388012 :     if (IsA(node, PlaceHolderVar))
                               3421                 :                :     {
                               3422                 :           1191 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               3423                 :                : 
                               3424                 :                :         /* See if the PlaceHolderVar has bubbled up from a lower plan node */
                               3425         [ +  + ]:           1191 :         if (context->subplan_itlist->has_ph_vars)
                               3426                 :                :         {
 1351                          3427                 :           1073 :             newvar = search_indexed_tlist_for_phv(phv,
                               3428                 :                :                                                   context->subplan_itlist,
                               3429                 :                :                                                   context->newvarno,
                               3430                 :                :                                                   NRM_EQUAL);
 6565                          3431         [ +  - ]:           1073 :             if (newvar)
                               3432                 :           1073 :                 return (Node *) newvar;
                               3433                 :                :         }
                               3434                 :                :         /* If not supplied by input plan, evaluate the contained expr */
                               3435                 :                :         /* XXX can we assert something about phnullingrels? */
                               3436                 :            118 :         return fix_upper_expr_mutator((Node *) phv->phexpr, context);
                               3437                 :                :     }
                               3438                 :                :     /* Try matching more complex expressions too, if tlist has any */
 2861                          3439         [ +  + ]:         386821 :     if (context->subplan_itlist->has_non_vars)
                               3440                 :                :     {
                               3441                 :          23588 :         newvar = search_indexed_tlist_for_non_var((Expr *) node,
                               3442                 :                :                                                   context->subplan_itlist,
                               3443                 :                :                                                   context->newvarno);
                               3444         [ +  + ]:          23588 :         if (newvar)
                               3445                 :           6060 :             return (Node *) newvar;
                               3446                 :                :     }
                               3447                 :                :     /* Special cases (apply only AFTER failing to match to lower tlist) */
 4499                          3448         [ +  + ]:         380761 :     if (IsA(node, Param))
                               3449                 :           8943 :         return fix_param_node(context->root, (Param *) node);
 3871                          3450         [ +  + ]:         371818 :     if (IsA(node, Aggref))
                               3451                 :                :     {
                               3452                 :          42042 :         Aggref     *aggref = (Aggref *) node;
                               3453                 :                :         Param      *aggparam;
                               3454                 :                : 
                               3455                 :                :         /* See if the Aggref should be replaced by a Param */
 1187                          3456                 :          42042 :         aggparam = find_minmax_agg_replacement_param(context->root, aggref);
                               3457         [ -  + ]:          42042 :         if (aggparam != NULL)
                               3458                 :                :         {
                               3459                 :                :             /* Make a copy of the Param for paranoia's sake */
 1187 tgl@sss.pgh.pa.us        3460                 :UBC           0 :             return (Node *) copyObject(aggparam);
                               3461                 :                :         }
                               3462                 :                :         /* If no match, just fall through to process it normally */
                               3463                 :                :     }
 2206 tgl@sss.pgh.pa.us        3464         [ +  + ]:CBC      371818 :     if (IsA(node, AlternativeSubPlan))
                               3465                 :             30 :         return fix_upper_expr_mutator(fix_alternative_subplan(context->root,
                               3466                 :                :                                                               (AlternativeSubPlan *) node,
                               3467                 :                :                                                               context->num_exec),
                               3468                 :                :                                       context);
 5518                          3469                 :         371788 :     fix_expr_common(context->root, node);
  683 peter@eisentraut.org     3470                 :         371788 :     return expression_tree_mutator(node, fix_upper_expr_mutator, context);
                               3471                 :                : }
                               3472                 :                : 
                               3473                 :                : /*
                               3474                 :                :  * set_returning_clause_references
                               3475                 :                :  *      Perform setrefs.c's work on a RETURNING targetlist
                               3476                 :                :  *
                               3477                 :                :  * If the query involves more than just the result table, we have to
                               3478                 :                :  * adjust any Vars that refer to other tables to reference junk tlist
                               3479                 :                :  * entries in the top subplan's targetlist.  Vars referencing the result
                               3480                 :                :  * table should be left alone, however (the executor will evaluate them
                               3481                 :                :  * using the actual heap tuple, after firing triggers if any).  In the
                               3482                 :                :  * adjusted RETURNING list, result-table Vars will have their original
                               3483                 :                :  * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
                               3484                 :                :  *
                               3485                 :                :  * We also must perform opcode lookup and add regclass OIDs to
                               3486                 :                :  * root->glob->relationOids.
                               3487                 :                :  *
                               3488                 :                :  * 'rlist': the RETURNING targetlist to be fixed
                               3489                 :                :  * 'topplan': the top subplan node that will be just below the ModifyTable
                               3490                 :                :  *      node (note it's not yet passed through set_plan_refs)
                               3491                 :                :  * 'resultRelation': RT index of the associated result relation
                               3492                 :                :  * 'rtoffset': how much to increment varnos by
                               3493                 :                :  *
                               3494                 :                :  * Note: the given 'root' is for the parent query level, not the 'topplan'.
                               3495                 :                :  * This does not matter currently since we only access the dependency-item
                               3496                 :                :  * lists in root->glob, but it would need some hacking if we wanted a root
                               3497                 :                :  * that actually matches the subplan.
                               3498                 :                :  *
                               3499                 :                :  * Note: resultRelation is not yet adjusted by rtoffset.
                               3500                 :                :  */
                               3501                 :                : static List *
 5518 tgl@sss.pgh.pa.us        3502                 :           2907 : set_returning_clause_references(PlannerInfo *root,
                               3503                 :                :                                 List *rlist,
                               3504                 :                :                                 Plan *topplan,
                               3505                 :                :                                 Index resultRelation,
                               3506                 :                :                                 int rtoffset)
                               3507                 :                : {
                               3508                 :                :     indexed_tlist *itlist;
                               3509                 :                : 
                               3510                 :                :     /*
                               3511                 :                :      * We can perform the desired Var fixup by abusing the fix_join_expr
                               3512                 :                :      * machinery that formerly handled inner indexscan fixup.  We search the
                               3513                 :                :      * top plan's targetlist for Vars of non-result relations, and use
                               3514                 :                :      * fix_join_expr to convert RETURNING Vars into references to those tlist
                               3515                 :                :      * entries, while leaving result-rel Vars as-is.
                               3516                 :                :      *
                               3517                 :                :      * PlaceHolderVars will also be sought in the targetlist, but no
                               3518                 :                :      * more-complex expressions will be.  Note that it is not possible for a
                               3519                 :                :      * PlaceHolderVar to refer to the result relation, since the result is
                               3520                 :                :      * never below an outer join.  If that case could happen, we'd have to be
                               3521                 :                :      * prepared to pick apart the PlaceHolderVar and evaluate its contained
                               3522                 :                :      * expression instead.
                               3523                 :                :      */
 7366                          3524                 :           2907 :     itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
                               3525                 :                : 
 5518                          3526                 :           2907 :     rlist = fix_join_expr(root,
                               3527                 :                :                           rlist,
                               3528                 :                :                           itlist,
                               3529                 :                :                           NULL,
                               3530                 :                :                           resultRelation,
                               3531                 :                :                           rtoffset,
                               3532                 :                :                           NRM_EQUAL,
                               3533                 :                :                           NUM_EXEC_TLIST(topplan));
                               3534                 :                : 
 7366                          3535                 :           2907 :     pfree(itlist);
                               3536                 :                : 
                               3537                 :           2907 :     return rlist;
                               3538                 :                : }
                               3539                 :                : 
                               3540                 :                : /*
                               3541                 :                :  * fix_windowagg_condition_expr_mutator
                               3542                 :                :  *      Mutator function for replacing WindowFuncs with the corresponding Var
                               3543                 :                :  *      in the targetlist which references that WindowFunc.
                               3544                 :                :  */
                               3545                 :                : static Node *
 1648 drowley@postgresql.o     3546                 :           3198 : fix_windowagg_condition_expr_mutator(Node *node,
                               3547                 :                :                                      fix_windowagg_cond_context *context)
                               3548                 :                : {
                               3549         [ +  + ]:           3198 :     if (node == NULL)
                               3550                 :           2333 :         return NULL;
                               3551                 :                : 
                               3552         [ +  + ]:            865 :     if (IsA(node, WindowFunc))
                               3553                 :                :     {
                               3554                 :                :         Var        *newvar;
                               3555                 :                : 
                               3556                 :            175 :         newvar = search_indexed_tlist_for_non_var((Expr *) node,
                               3557                 :                :                                                   context->subplan_itlist,
                               3558                 :                :                                                   context->newvarno);
                               3559         [ +  - ]:            175 :         if (newvar)
                               3560                 :            175 :             return (Node *) newvar;
 1648 drowley@postgresql.o     3561         [ #  # ]:UBC           0 :         elog(ERROR, "WindowFunc not found in subplan target lists");
                               3562                 :                :     }
                               3563                 :                : 
 1648 drowley@postgresql.o     3564                 :CBC         690 :     return expression_tree_mutator(node,
                               3565                 :                :                                    fix_windowagg_condition_expr_mutator,
                               3566                 :                :                                    context);
                               3567                 :                : }
                               3568                 :                : 
                               3569                 :                : /*
                               3570                 :                :  * fix_windowagg_condition_expr
                               3571                 :                :  *      Converts references in 'runcondition' so that any WindowFunc
                               3572                 :                :  *      references are swapped out for a Var which references the matching
                               3573                 :                :  *      WindowFunc in 'subplan_itlist'.
                               3574                 :                :  */
                               3575                 :                : static List *
                               3576                 :           2498 : fix_windowagg_condition_expr(PlannerInfo *root,
                               3577                 :                :                              List *runcondition,
                               3578                 :                :                              indexed_tlist *subplan_itlist)
                               3579                 :                : {
                               3580                 :                :     fix_windowagg_cond_context context;
                               3581                 :                : 
                               3582                 :           2498 :     context.root = root;
                               3583                 :           2498 :     context.subplan_itlist = subplan_itlist;
                               3584                 :           2498 :     context.newvarno = 0;
                               3585                 :                : 
                               3586                 :           2498 :     return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
                               3587                 :                :                                                          &context);
                               3588                 :                : }
                               3589                 :                : 
                               3590                 :                : /*
                               3591                 :                :  * set_windowagg_runcondition_references
                               3592                 :                :  *      Converts references in 'runcondition' so that any WindowFunc
                               3593                 :                :  *      references are swapped out for a Var which references the matching
                               3594                 :                :  *      WindowFunc in 'plan' targetlist.
                               3595                 :                :  */
                               3596                 :                : static List *
                               3597                 :           2498 : set_windowagg_runcondition_references(PlannerInfo *root,
                               3598                 :                :                                       List *runcondition,
                               3599                 :                :                                       Plan *plan)
                               3600                 :                : {
                               3601                 :                :     List       *newlist;
                               3602                 :                :     indexed_tlist *itlist;
                               3603                 :                : 
                               3604                 :           2498 :     itlist = build_tlist_index(plan->targetlist);
                               3605                 :                : 
                               3606                 :           2498 :     newlist = fix_windowagg_condition_expr(root, runcondition, itlist);
                               3607                 :                : 
                               3608                 :           2498 :     pfree(itlist);
                               3609                 :                : 
                               3610                 :           2498 :     return newlist;
                               3611                 :                : }
                               3612                 :                : 
                               3613                 :                : /*
                               3614                 :                :  * find_minmax_agg_replacement_param
                               3615                 :                :  *      If the given Aggref is one that we are optimizing into a subquery
                               3616                 :                :  *      (cf. planagg.c), then return the Param that should replace it.
                               3617                 :                :  *      Else return NULL.
                               3618                 :                :  *
                               3619                 :                :  * This is exported so that SS_finalize_plan can use it before setrefs.c runs.
                               3620                 :                :  * Note that it will not find anything until we have built a Plan from a
                               3621                 :                :  * MinMaxAggPath, as root->minmax_aggs will never be filled otherwise.
                               3622                 :                :  */
                               3623                 :                : Param *
 1187 tgl@sss.pgh.pa.us        3624                 :          58139 : find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
                               3625                 :                : {
                               3626   [ +  +  +  - ]:          58939 :     if (root->minmax_aggs != NIL &&
                               3627                 :            800 :         list_length(aggref->args) == 1)
                               3628                 :                :     {
                               3629                 :            800 :         TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
                               3630                 :                :         ListCell   *lc;
                               3631                 :                : 
                               3632   [ +  -  +  -  :            884 :         foreach(lc, root->minmax_aggs)
                                              +  - ]
                               3633                 :                :         {
                               3634                 :            884 :             MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
                               3635                 :                : 
                               3636   [ +  +  +  - ]:           1684 :             if (mminfo->aggfnoid == aggref->aggfnoid &&
                               3637                 :            800 :                 equal(mminfo->target, curTarget->expr))
                               3638                 :            800 :                 return mminfo->param;
                               3639                 :                :         }
                               3640                 :                :     }
                               3641                 :          57339 :     return NULL;
                               3642                 :                : }
                               3643                 :                : 
                               3644                 :                : 
                               3645                 :                : /*****************************************************************************
                               3646                 :                :  *                  QUERY DEPENDENCY MANAGEMENT
                               3647                 :                :  *****************************************************************************/
                               3648                 :                : 
                               3649                 :                : /*
                               3650                 :                :  * record_plan_function_dependency
                               3651                 :                :  *      Mark the current plan as depending on a particular function.
                               3652                 :                :  *
                               3653                 :                :  * This is exported so that the function-inlining code can record a
                               3654                 :                :  * dependency on a function that it's removed from the plan tree.
                               3655                 :                :  */
                               3656                 :                : void
 5518                          3657                 :         961497 : record_plan_function_dependency(PlannerInfo *root, Oid funcid)
                               3658                 :                : {
                               3659                 :                :     /*
                               3660                 :                :      * For performance reasons, we don't bother to track built-in functions;
                               3661                 :                :      * we just assume they'll never change (or at least not in ways that'd
                               3662                 :                :      * invalidate plans using them).  For this purpose we can consider a
                               3663                 :                :      * built-in function to be one with OID less than FirstUnpinnedObjectId.
                               3664                 :                :      * Note that the OID generator guarantees never to generate such an OID
                               3665                 :                :      * after startup, even at OID wraparound.
                               3666                 :                :      */
 1915                          3667         [ +  + ]:         961497 :     if (funcid >= (Oid) FirstUnpinnedObjectId)
                               3668                 :                :     {
 5536                          3669                 :          28501 :         PlanInvalItem *inval_item = makeNode(PlanInvalItem);
                               3670                 :                : 
                               3671                 :                :         /*
                               3672                 :                :          * It would work to use any syscache on pg_proc, but the easiest is
                               3673                 :                :          * PROCOID since we already have the function's OID at hand.  Note
                               3674                 :                :          * that plancache.c knows we use PROCOID.
                               3675                 :                :          */
 6607                          3676                 :          28501 :         inval_item->cacheId = PROCOID;
 5332                          3677                 :          28501 :         inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
                               3678                 :                :                                                       ObjectIdGetDatum(funcid));
                               3679                 :                : 
 5518                          3680                 :          28501 :         root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
                               3681                 :                :     }
 6607                          3682                 :         961497 : }
                               3683                 :                : 
                               3684                 :                : /*
                               3685                 :                :  * record_plan_type_dependency
                               3686                 :                :  *      Mark the current plan as depending on a particular type.
                               3687                 :                :  *
                               3688                 :                :  * This is exported so that eval_const_expressions can record a
                               3689                 :                :  * dependency on a domain that it's removed a CoerceToDomain node for.
                               3690                 :                :  *
                               3691                 :                :  * We don't currently need to record dependencies on domains that the
                               3692                 :                :  * plan contains CoerceToDomain nodes for, though that might change in
                               3693                 :                :  * future.  Hence, this isn't actually called in this module, though
                               3694                 :                :  * someday fix_expr_common might call it.
                               3695                 :                :  */
                               3696                 :                : void
 2832                          3697                 :          12030 : record_plan_type_dependency(PlannerInfo *root, Oid typid)
                               3698                 :                : {
                               3699                 :                :     /*
                               3700                 :                :      * As in record_plan_function_dependency, ignore the possibility that
                               3701                 :                :      * someone would change a built-in domain.
                               3702                 :                :      */
 1915                          3703         [ +  - ]:          12030 :     if (typid >= (Oid) FirstUnpinnedObjectId)
                               3704                 :                :     {
 2860                          3705                 :          12030 :         PlanInvalItem *inval_item = makeNode(PlanInvalItem);
                               3706                 :                : 
                               3707                 :                :         /*
                               3708                 :                :          * It would work to use any syscache on pg_type, but the easiest is
                               3709                 :                :          * TYPEOID since we already have the type's OID at hand.  Note that
                               3710                 :                :          * plancache.c knows we use TYPEOID.
                               3711                 :                :          */
                               3712                 :          12030 :         inval_item->cacheId = TYPEOID;
                               3713                 :          12030 :         inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
                               3714                 :                :                                                       ObjectIdGetDatum(typid));
                               3715                 :                : 
                               3716                 :          12030 :         root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
                               3717                 :                :     }
                               3718                 :          12030 : }
                               3719                 :                : 
                               3720                 :                : /*
                               3721                 :                :  * extract_query_dependencies
                               3722                 :                :  *      Given a rewritten, but not yet planned, query or queries
                               3723                 :                :  *      (i.e. a Query node or list of Query nodes), extract dependencies
                               3724                 :                :  *      just as set_plan_references would do.  Also detect whether any
                               3725                 :                :  *      rewrite steps were affected by RLS.
                               3726                 :                :  *
                               3727                 :                :  * This is needed by plancache.c to handle invalidation of cached unplanned
                               3728                 :                :  * queries.
                               3729                 :                :  *
                               3730                 :                :  * Note: this does not go through eval_const_expressions, and hence doesn't
                               3731                 :                :  * reflect its additions of inlined functions and elided CoerceToDomain nodes
                               3732                 :                :  * to the invalItems list.  This is obviously OK for functions, since we'll
                               3733                 :                :  * see them in the original query tree anyway.  For domains, it's OK because
                               3734                 :                :  * we don't care about domains unless they get elided.  That is, a plan might
                               3735                 :                :  * have domain dependencies that the query tree doesn't.
                               3736                 :                :  */
                               3737                 :                : void
 6114                          3738                 :          36506 : extract_query_dependencies(Node *query,
                               3739                 :                :                            List **relationOids,
                               3740                 :                :                            List **invalItems,
                               3741                 :                :                            bool *hasRowSecurity)
                               3742                 :                : {
                               3743                 :                :     PlannerGlobal glob;
                               3744                 :                :     PlannerInfo root;
                               3745                 :                : 
                               3746                 :                :     /* Make up dummy planner state so we can use this module's machinery */
 6607                          3747   [ +  -  +  -  :        1058674 :     MemSet(&glob, 0, sizeof(glob));
                                     +  -  +  -  +  
                                                 + ]
                               3748                 :          36506 :     glob.type = T_PlannerGlobal;
                               3749                 :          36506 :     glob.relationOids = NIL;
                               3750                 :          36506 :     glob.invalItems = NIL;
                               3751                 :                :     /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
 3741                          3752                 :          36506 :     glob.dependsOnRole = false;
                               3753                 :                : 
 5518                          3754   [ +  -  +  -  :        3431564 :     MemSet(&root, 0, sizeof(root));
                                     +  -  +  -  +  
                                                 + ]
                               3755                 :          36506 :     root.type = T_PlannerInfo;
                               3756                 :          36506 :     root.glob = &glob;
                               3757                 :                : 
                               3758                 :          36506 :     (void) extract_query_dependencies_walker(query, &root);
                               3759                 :                : 
 6607                          3760                 :          36506 :     *relationOids = glob.relationOids;
                               3761                 :          36506 :     *invalItems = glob.invalItems;
 3741                          3762                 :          36506 :     *hasRowSecurity = glob.dependsOnRole;
 6607                          3763                 :          36506 : }
                               3764                 :                : 
                               3765                 :                : /*
                               3766                 :                :  * Tree walker for extract_query_dependencies.
                               3767                 :                :  *
                               3768                 :                :  * This is exported so that expression_planner_with_deps can call it on
                               3769                 :                :  * simple expressions (post-planning, not before planning, in that case).
                               3770                 :                :  * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
                               3771                 :                :  * and invalItems lists are added to as needed.
                               3772                 :                :  */
                               3773                 :                : bool
 5518                          3774                 :        1046751 : extract_query_dependencies_walker(Node *node, PlannerInfo *context)
                               3775                 :                : {
 6607                          3776         [ +  + ]:        1046751 :     if (node == NULL)
                               3777                 :         475557 :         return false;
 6565                          3778         [ -  + ]:         571194 :     Assert(!IsA(node, PlaceHolderVar));
 6607                          3779         [ +  + ]:         571194 :     if (IsA(node, Query))
                               3780                 :                :     {
                               3781                 :          39610 :         Query      *query = (Query *) node;
                               3782                 :                :         ListCell   *lc;
                               3783                 :                : 
 5220                          3784         [ +  + ]:          39610 :         if (query->commandType == CMD_UTILITY)
                               3785                 :                :         {
                               3786                 :                :             /*
                               3787                 :                :              * This logic must handle any utility command for which parse
                               3788                 :                :              * analysis was nontrivial (cf. stmt_requires_parse_analysis).
                               3789                 :                :              *
                               3790                 :                :              * Notably, CALL requires its own processing.
                               3791                 :                :              */
 1113                          3792         [ +  + ]:           6451 :             if (IsA(query->utilityStmt, CallStmt))
                               3793                 :                :             {
                               3794                 :             61 :                 CallStmt   *callstmt = (CallStmt *) query->utilityStmt;
                               3795                 :                : 
                               3796                 :                :                 /* We need not examine funccall, just the transformed exprs */
                               3797                 :             61 :                 (void) extract_query_dependencies_walker((Node *) callstmt->funcexpr,
                               3798                 :                :                                                          context);
                               3799                 :             61 :                 (void) extract_query_dependencies_walker((Node *) callstmt->outargs,
                               3800                 :                :                                                          context);
                               3801                 :             61 :                 return false;
                               3802                 :                :             }
                               3803                 :                : 
                               3804                 :                :             /*
                               3805                 :                :              * Ignore other utility statements, except those (such as EXPLAIN)
                               3806                 :                :              * that contain a parsed-but-not-planned query.  For those, we
                               3807                 :                :              * just need to transfer our attention to the contained query.
                               3808                 :                :              */
 5320                          3809                 :           6390 :             query = UtilityContainsQuery(query->utilityStmt);
                               3810         [ +  + ]:           6390 :             if (query == NULL)
 6114                          3811                 :             24 :                 return false;
                               3812                 :                :         }
                               3813                 :                : 
                               3814                 :                :         /* Remember if any Query has RLS quals applied by rewriter */
 3741                          3815         [ +  + ]:          39525 :         if (query->hasRowSecurity)
                               3816                 :            145 :             context->glob->dependsOnRole = true;
                               3817                 :                : 
                               3818                 :                :         /* Collect relation OIDs in this Query's rtable */
 6607                          3819   [ +  +  +  +  :          63847 :         foreach(lc, query->rtable)
                                              +  + ]
                               3820                 :                :         {
                               3821                 :          24322 :             RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
                               3822                 :                : 
 1363                          3823         [ +  + ]:          24322 :             if (rte->rtekind == RTE_RELATION ||
                               3824   [ +  +  +  + ]:           5321 :                 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
                               3825   [ +  +  +  - ]:           5049 :                 (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
 5518                          3826                 :          19594 :                 context->glob->relationOids =
                               3827                 :          19594 :                     lappend_oid(context->glob->relationOids, rte->relid);
                               3828                 :                :         }
                               3829                 :                : 
                               3830                 :                :         /* And recurse into the query's subexpressions */
 6607                          3831                 :          39525 :         return query_tree_walker(query, extract_query_dependencies_walker,
                               3832                 :                :                                  context, 0);
                               3833                 :                :     }
                               3834                 :                :     /* Extract function dependencies and check for regclass Consts */
 2860                          3835                 :         531584 :     fix_expr_common(context, node);
 6607                          3836                 :         531584 :     return expression_tree_walker(node, extract_query_dependencies_walker,
                               3837                 :                :                                   context);
                               3838                 :                : }
                               3839                 :                : 
                               3840                 :                : /*
                               3841                 :                :  * Record some details about a node removed from the plan during setrefs
                               3842                 :                :  * processing, for the benefit of code trying to reconstruct planner decisions
                               3843                 :                :  * from examination of the final plan tree.
                               3844                 :                :  */
                               3845                 :                : static void
  244 rhaas@postgresql.org     3846                 :          19164 : record_elided_node(PlannerGlobal *glob, int plan_node_id,
                               3847                 :                :                    NodeTag elided_type, Bitmapset *relids,
                               3848                 :                :                    List *child_append_relid_sets)
                               3849                 :                : {
                               3850                 :          19164 :     ElidedNode *n = makeNode(ElidedNode);
                               3851                 :                : 
                               3852                 :          19164 :     n->plan_node_id = plan_node_id;
                               3853                 :          19164 :     n->elided_type = elided_type;
                               3854                 :          19164 :     n->relids = relids;
    4                          3855                 :          19164 :     n->child_append_relid_sets = child_append_relid_sets;
                               3856                 :                : 
  244                          3857                 :          19164 :     glob->elidedNodes = lappend(glob->elidedNodes, n);
                               3858                 :          19164 : }
        

Generated by: LCOV version 2.0-1