LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - setrefs.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 97.1 % 1159 1125
Test Date: 2026-10-06 00:16:20 Functions: 100.0 % 50 50
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 85.4 % 748 639

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

Generated by: LCOV version 2.0-1