LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - setrefs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 1072 1122 95.5 %
Date: 2025-01-18 04:15:08 Functions: 46 47 97.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14