LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/plan - setrefs.c (source / functions) Coverage Total Hit UBC CBC
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 95.6 % 1172 1121 51 1121
Current Date: 2025-09-06 07:49:51 +0900 Functions: 97.9 % 48 47 1 47
Baseline: lcov-20250906-005545-baseline Branches: 80.7 % 836 675 161 675
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 95.3 % 43 41 2 41
(360..) days: 95.7 % 1128 1079 49 1079
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 97.9 % 47 46 1 46
Branch coverage date bins:
(7,30] days: 50.0 % 4 2 2 2
(30,360] days: 70.0 % 40 28 12 28
(360..) days: 81.4 % 792 645 147 645

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

Generated by: LCOV version 2.4-beta