LCOV - code coverage report
Current view: top level - src/backend/rewrite - rewriteManip.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18beta1 Lines: 576 638 90.3 %
Date: 2025-05-17 05:15:19 Functions: 41 41 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * rewriteManip.c
       4             :  *
       5             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       6             :  * Portions Copyright (c) 1994, Regents of the University of California
       7             :  *
       8             :  *
       9             :  * IDENTIFICATION
      10             :  *    src/backend/rewrite/rewriteManip.c
      11             :  *
      12             :  *-------------------------------------------------------------------------
      13             :  */
      14             : #include "postgres.h"
      15             : 
      16             : #include "catalog/pg_type.h"
      17             : #include "nodes/makefuncs.h"
      18             : #include "nodes/nodeFuncs.h"
      19             : #include "nodes/pathnodes.h"
      20             : #include "nodes/plannodes.h"
      21             : #include "parser/parse_coerce.h"
      22             : #include "parser/parse_relation.h"
      23             : #include "parser/parsetree.h"
      24             : #include "rewrite/rewriteManip.h"
      25             : #include "utils/lsyscache.h"
      26             : 
      27             : 
      28             : typedef struct
      29             : {
      30             :     int         sublevels_up;
      31             : } contain_aggs_of_level_context;
      32             : 
      33             : typedef struct
      34             : {
      35             :     int         agg_location;
      36             :     int         sublevels_up;
      37             : } locate_agg_of_level_context;
      38             : 
      39             : typedef struct
      40             : {
      41             :     int         win_location;
      42             : } locate_windowfunc_context;
      43             : 
      44             : typedef struct
      45             : {
      46             :     const Bitmapset *target_relids;
      47             :     const Bitmapset *added_relids;
      48             :     int         sublevels_up;
      49             : } add_nulling_relids_context;
      50             : 
      51             : typedef struct
      52             : {
      53             :     const Bitmapset *removable_relids;
      54             :     const Bitmapset *except_relids;
      55             :     int         sublevels_up;
      56             : } remove_nulling_relids_context;
      57             : 
      58             : static bool contain_aggs_of_level_walker(Node *node,
      59             :                                          contain_aggs_of_level_context *context);
      60             : static bool locate_agg_of_level_walker(Node *node,
      61             :                                        locate_agg_of_level_context *context);
      62             : static bool contain_windowfuncs_walker(Node *node, void *context);
      63             : static bool locate_windowfunc_walker(Node *node,
      64             :                                      locate_windowfunc_context *context);
      65             : static bool checkExprHasSubLink_walker(Node *node, void *context);
      66             : static Relids offset_relid_set(Relids relids, int offset);
      67             : static Node *add_nulling_relids_mutator(Node *node,
      68             :                                         add_nulling_relids_context *context);
      69             : static Node *remove_nulling_relids_mutator(Node *node,
      70             :                                            remove_nulling_relids_context *context);
      71             : 
      72             : 
      73             : /*
      74             :  * contain_aggs_of_level -
      75             :  *  Check if an expression contains an aggregate function call of a
      76             :  *  specified query level.
      77             :  *
      78             :  * The objective of this routine is to detect whether there are aggregates
      79             :  * belonging to the given query level.  Aggregates belonging to subqueries
      80             :  * or outer queries do NOT cause a true result.  We must recurse into
      81             :  * subqueries to detect outer-reference aggregates that logically belong to
      82             :  * the specified query level.
      83             :  */
      84             : bool
      85         744 : contain_aggs_of_level(Node *node, int levelsup)
      86             : {
      87             :     contain_aggs_of_level_context context;
      88             : 
      89         744 :     context.sublevels_up = levelsup;
      90             : 
      91             :     /*
      92             :      * Must be prepared to start with a Query or a bare expression tree; if
      93             :      * it's a Query, we don't want to increment sublevels_up.
      94             :      */
      95         744 :     return query_or_expression_tree_walker(node,
      96             :                                            contain_aggs_of_level_walker,
      97             :                                            &context,
      98             :                                            0);
      99             : }
     100             : 
     101             : static bool
     102        1748 : contain_aggs_of_level_walker(Node *node,
     103             :                              contain_aggs_of_level_context *context)
     104             : {
     105        1748 :     if (node == NULL)
     106         450 :         return false;
     107        1298 :     if (IsA(node, Aggref))
     108             :     {
     109           0 :         if (((Aggref *) node)->agglevelsup == context->sublevels_up)
     110           0 :             return true;        /* abort the tree traversal and return true */
     111             :         /* else fall through to examine argument */
     112             :     }
     113        1298 :     if (IsA(node, GroupingFunc))
     114             :     {
     115           0 :         if (((GroupingFunc *) node)->agglevelsup == context->sublevels_up)
     116           0 :             return true;
     117             :         /* else fall through to examine argument */
     118             :     }
     119        1298 :     if (IsA(node, Query))
     120             :     {
     121             :         /* Recurse into subselects */
     122             :         bool        result;
     123             : 
     124          28 :         context->sublevels_up++;
     125          28 :         result = query_tree_walker((Query *) node,
     126             :                                    contain_aggs_of_level_walker,
     127             :                                    context, 0);
     128          28 :         context->sublevels_up--;
     129          28 :         return result;
     130             :     }
     131        1270 :     return expression_tree_walker(node, contain_aggs_of_level_walker,
     132             :                                   context);
     133             : }
     134             : 
     135             : /*
     136             :  * locate_agg_of_level -
     137             :  *    Find the parse location of any aggregate of the specified query level.
     138             :  *
     139             :  * Returns -1 if no such agg is in the querytree, or if they all have
     140             :  * unknown parse location.  (The former case is probably caller error,
     141             :  * but we don't bother to distinguish it from the latter case.)
     142             :  *
     143             :  * Note: it might seem appropriate to merge this functionality into
     144             :  * contain_aggs_of_level, but that would complicate that function's API.
     145             :  * Currently, the only uses of this function are for error reporting,
     146             :  * and so shaving cycles probably isn't very important.
     147             :  */
     148             : int
     149          60 : locate_agg_of_level(Node *node, int levelsup)
     150             : {
     151             :     locate_agg_of_level_context context;
     152             : 
     153          60 :     context.agg_location = -1;  /* in case we find nothing */
     154          60 :     context.sublevels_up = levelsup;
     155             : 
     156             :     /*
     157             :      * Must be prepared to start with a Query or a bare expression tree; if
     158             :      * it's a Query, we don't want to increment sublevels_up.
     159             :      */
     160          60 :     (void) query_or_expression_tree_walker(node,
     161             :                                            locate_agg_of_level_walker,
     162             :                                            &context,
     163             :                                            0);
     164             : 
     165          60 :     return context.agg_location;
     166             : }
     167             : 
     168             : static bool
     169         240 : locate_agg_of_level_walker(Node *node,
     170             :                            locate_agg_of_level_context *context)
     171             : {
     172         240 :     if (node == NULL)
     173          12 :         return false;
     174         228 :     if (IsA(node, Aggref))
     175             :     {
     176          54 :         if (((Aggref *) node)->agglevelsup == context->sublevels_up &&
     177          48 :             ((Aggref *) node)->location >= 0)
     178             :         {
     179          48 :             context->agg_location = ((Aggref *) node)->location;
     180          48 :             return true;        /* abort the tree traversal and return true */
     181             :         }
     182             :         /* else fall through to examine argument */
     183             :     }
     184         180 :     if (IsA(node, GroupingFunc))
     185             :     {
     186           0 :         if (((GroupingFunc *) node)->agglevelsup == context->sublevels_up &&
     187           0 :             ((GroupingFunc *) node)->location >= 0)
     188             :         {
     189           0 :             context->agg_location = ((GroupingFunc *) node)->location;
     190           0 :             return true;        /* abort the tree traversal and return true */
     191             :         }
     192             :     }
     193         180 :     if (IsA(node, Query))
     194             :     {
     195             :         /* Recurse into subselects */
     196             :         bool        result;
     197             : 
     198          12 :         context->sublevels_up++;
     199          12 :         result = query_tree_walker((Query *) node,
     200             :                                    locate_agg_of_level_walker,
     201             :                                    context, 0);
     202          12 :         context->sublevels_up--;
     203          12 :         return result;
     204             :     }
     205         168 :     return expression_tree_walker(node, locate_agg_of_level_walker, context);
     206             : }
     207             : 
     208             : /*
     209             :  * contain_windowfuncs -
     210             :  *  Check if an expression contains a window function call of the
     211             :  *  current query level.
     212             :  */
     213             : bool
     214        9590 : contain_windowfuncs(Node *node)
     215             : {
     216             :     /*
     217             :      * Must be prepared to start with a Query or a bare expression tree; if
     218             :      * it's a Query, we don't want to increment sublevels_up.
     219             :      */
     220        9590 :     return query_or_expression_tree_walker(node,
     221             :                                            contain_windowfuncs_walker,
     222             :                                            NULL,
     223             :                                            0);
     224             : }
     225             : 
     226             : static bool
     227       10514 : contain_windowfuncs_walker(Node *node, void *context)
     228             : {
     229       10514 :     if (node == NULL)
     230         168 :         return false;
     231       10346 :     if (IsA(node, WindowFunc))
     232          12 :         return true;            /* abort the tree traversal and return true */
     233             :     /* Mustn't recurse into subselects */
     234       10334 :     return expression_tree_walker(node, contain_windowfuncs_walker, context);
     235             : }
     236             : 
     237             : /*
     238             :  * locate_windowfunc -
     239             :  *    Find the parse location of any windowfunc of the current query level.
     240             :  *
     241             :  * Returns -1 if no such windowfunc is in the querytree, or if they all have
     242             :  * unknown parse location.  (The former case is probably caller error,
     243             :  * but we don't bother to distinguish it from the latter case.)
     244             :  *
     245             :  * Note: it might seem appropriate to merge this functionality into
     246             :  * contain_windowfuncs, but that would complicate that function's API.
     247             :  * Currently, the only uses of this function are for error reporting,
     248             :  * and so shaving cycles probably isn't very important.
     249             :  */
     250             : int
     251           6 : locate_windowfunc(Node *node)
     252             : {
     253             :     locate_windowfunc_context context;
     254             : 
     255           6 :     context.win_location = -1;  /* in case we find nothing */
     256             : 
     257             :     /*
     258             :      * Must be prepared to start with a Query or a bare expression tree; if
     259             :      * it's a Query, we don't want to increment sublevels_up.
     260             :      */
     261           6 :     (void) query_or_expression_tree_walker(node,
     262             :                                            locate_windowfunc_walker,
     263             :                                            &context,
     264             :                                            0);
     265             : 
     266           6 :     return context.win_location;
     267             : }
     268             : 
     269             : static bool
     270           6 : locate_windowfunc_walker(Node *node, locate_windowfunc_context *context)
     271             : {
     272           6 :     if (node == NULL)
     273           0 :         return false;
     274           6 :     if (IsA(node, WindowFunc))
     275             :     {
     276           6 :         if (((WindowFunc *) node)->location >= 0)
     277             :         {
     278           6 :             context->win_location = ((WindowFunc *) node)->location;
     279           6 :             return true;        /* abort the tree traversal and return true */
     280             :         }
     281             :         /* else fall through to examine argument */
     282             :     }
     283             :     /* Mustn't recurse into subselects */
     284           0 :     return expression_tree_walker(node, locate_windowfunc_walker, context);
     285             : }
     286             : 
     287             : /*
     288             :  * checkExprHasSubLink -
     289             :  *  Check if an expression contains a SubLink.
     290             :  */
     291             : bool
     292      119412 : checkExprHasSubLink(Node *node)
     293             : {
     294             :     /*
     295             :      * If a Query is passed, examine it --- but we should not recurse into
     296             :      * sub-Queries that are in its rangetable or CTE list.
     297             :      */
     298      119412 :     return query_or_expression_tree_walker(node,
     299             :                                            checkExprHasSubLink_walker,
     300             :                                            NULL,
     301             :                                            QTW_IGNORE_RC_SUBQUERIES);
     302             : }
     303             : 
     304             : static bool
     305      200782 : checkExprHasSubLink_walker(Node *node, void *context)
     306             : {
     307      200782 :     if (node == NULL)
     308        3854 :         return false;
     309      196928 :     if (IsA(node, SubLink))
     310        1816 :         return true;            /* abort the tree traversal and return true */
     311      195112 :     return expression_tree_walker(node, checkExprHasSubLink_walker, context);
     312             : }
     313             : 
     314             : /*
     315             :  * Check for MULTIEXPR Param within expression tree
     316             :  *
     317             :  * We intentionally don't descend into SubLinks: only Params at the current
     318             :  * query level are of interest.
     319             :  */
     320             : static bool
     321      188128 : contains_multiexpr_param(Node *node, void *context)
     322             : {
     323      188128 :     if (node == NULL)
     324        3360 :         return false;
     325      184768 :     if (IsA(node, Param))
     326             :     {
     327         486 :         if (((Param *) node)->paramkind == PARAM_MULTIEXPR)
     328           0 :             return true;        /* abort the tree traversal and return true */
     329         486 :         return false;
     330             :     }
     331      184282 :     return expression_tree_walker(node, contains_multiexpr_param, context);
     332             : }
     333             : 
     334             : /*
     335             :  * CombineRangeTables
     336             :  *      Adds the RTEs of 'src_rtable' into 'dst_rtable'
     337             :  *
     338             :  * This also adds the RTEPermissionInfos of 'src_perminfos' (belonging to the
     339             :  * RTEs in 'src_rtable') into *dst_perminfos and also updates perminfoindex of
     340             :  * the RTEs in 'src_rtable' to now point to the perminfos' indexes in
     341             :  * *dst_perminfos.
     342             :  *
     343             :  * Note that this changes both 'dst_rtable' and 'dst_perminfos' destructively,
     344             :  * so the caller should have better passed safe-to-modify copies.
     345             :  */
     346             : void
     347       45524 : CombineRangeTables(List **dst_rtable, List **dst_perminfos,
     348             :                    List *src_rtable, List *src_perminfos)
     349             : {
     350             :     ListCell   *l;
     351       45524 :     int         offset = list_length(*dst_perminfos);
     352             : 
     353       45524 :     if (offset > 0)
     354             :     {
     355      112010 :         foreach(l, src_rtable)
     356             :         {
     357       74304 :             RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
     358             : 
     359       74304 :             if (rte->perminfoindex > 0)
     360       34492 :                 rte->perminfoindex += offset;
     361             :         }
     362             :     }
     363             : 
     364       45524 :     *dst_perminfos = list_concat(*dst_perminfos, src_perminfos);
     365       45524 :     *dst_rtable = list_concat(*dst_rtable, src_rtable);
     366       45524 : }
     367             : 
     368             : /*
     369             :  * OffsetVarNodes - adjust Vars when appending one query's RT to another
     370             :  *
     371             :  * Find all Var nodes in the given tree with varlevelsup == sublevels_up,
     372             :  * and increment their varno fields (rangetable indexes) by 'offset'.
     373             :  * The varnosyn fields are adjusted similarly.  Also, adjust other nodes
     374             :  * that contain rangetable indexes, such as RangeTblRef and JoinExpr.
     375             :  *
     376             :  * NOTE: although this has the form of a walker, we cheat and modify the
     377             :  * nodes in-place.  The given expression tree should have been copied
     378             :  * earlier to ensure that no unwanted side-effects occur!
     379             :  */
     380             : 
     381             : typedef struct
     382             : {
     383             :     int         offset;
     384             :     int         sublevels_up;
     385             : } OffsetVarNodes_context;
     386             : 
     387             : static bool
     388     2165604 : OffsetVarNodes_walker(Node *node, OffsetVarNodes_context *context)
     389             : {
     390     2165604 :     if (node == NULL)
     391      670982 :         return false;
     392     1494622 :     if (IsA(node, Var))
     393             :     {
     394      777342 :         Var        *var = (Var *) node;
     395             : 
     396      777342 :         if (var->varlevelsup == context->sublevels_up)
     397             :         {
     398      752514 :             var->varno += context->offset;
     399      752514 :             var->varnullingrels = offset_relid_set(var->varnullingrels,
     400             :                                                    context->offset);
     401      752514 :             if (var->varnosyn > 0)
     402      752514 :                 var->varnosyn += context->offset;
     403             :         }
     404      777342 :         return false;
     405             :     }
     406      717280 :     if (IsA(node, CurrentOfExpr))
     407             :     {
     408           0 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
     409             : 
     410           0 :         if (context->sublevels_up == 0)
     411           0 :             cexpr->cvarno += context->offset;
     412           0 :         return false;
     413             :     }
     414      717280 :     if (IsA(node, RangeTblRef))
     415             :     {
     416       62474 :         RangeTblRef *rtr = (RangeTblRef *) node;
     417             : 
     418       62474 :         if (context->sublevels_up == 0)
     419       56916 :             rtr->rtindex += context->offset;
     420             :         /* the subquery itself is visited separately */
     421       62474 :         return false;
     422             :     }
     423      654806 :     if (IsA(node, JoinExpr))
     424             :     {
     425       14702 :         JoinExpr   *j = (JoinExpr *) node;
     426             : 
     427       14702 :         if (j->rtindex && context->sublevels_up == 0)
     428       13776 :             j->rtindex += context->offset;
     429             :         /* fall through to examine children */
     430             :     }
     431      654806 :     if (IsA(node, PlaceHolderVar))
     432             :     {
     433         452 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
     434             : 
     435         452 :         if (phv->phlevelsup == context->sublevels_up)
     436             :         {
     437         344 :             phv->phrels = offset_relid_set(phv->phrels,
     438             :                                            context->offset);
     439         344 :             phv->phnullingrels = offset_relid_set(phv->phnullingrels,
     440             :                                                   context->offset);
     441             :         }
     442             :         /* fall through to examine children */
     443             :     }
     444      654806 :     if (IsA(node, AppendRelInfo))
     445             :     {
     446         940 :         AppendRelInfo *appinfo = (AppendRelInfo *) node;
     447             : 
     448         940 :         if (context->sublevels_up == 0)
     449             :         {
     450         940 :             appinfo->parent_relid += context->offset;
     451         940 :             appinfo->child_relid += context->offset;
     452             :         }
     453             :         /* fall through to examine children */
     454             :     }
     455             :     /* Shouldn't need to handle other planner auxiliary nodes here */
     456             :     Assert(!IsA(node, PlanRowMark));
     457             :     Assert(!IsA(node, SpecialJoinInfo));
     458             :     Assert(!IsA(node, PlaceHolderInfo));
     459             :     Assert(!IsA(node, MinMaxAggInfo));
     460             : 
     461      654806 :     if (IsA(node, Query))
     462             :     {
     463             :         /* Recurse into subselects */
     464             :         bool        result;
     465             : 
     466        4874 :         context->sublevels_up++;
     467        4874 :         result = query_tree_walker((Query *) node, OffsetVarNodes_walker,
     468             :                                    context, 0);
     469        4874 :         context->sublevels_up--;
     470        4874 :         return result;
     471             :     }
     472      649932 :     return expression_tree_walker(node, OffsetVarNodes_walker, context);
     473             : }
     474             : 
     475             : void
     476       82436 : OffsetVarNodes(Node *node, int offset, int sublevels_up)
     477             : {
     478             :     OffsetVarNodes_context context;
     479             : 
     480       82436 :     context.offset = offset;
     481       82436 :     context.sublevels_up = sublevels_up;
     482             : 
     483             :     /*
     484             :      * Must be prepared to start with a Query or a bare expression tree; if
     485             :      * it's a Query, go straight to query_tree_walker to make sure that
     486             :      * sublevels_up doesn't get incremented prematurely.
     487             :      */
     488       82436 :     if (node && IsA(node, Query))
     489       41218 :     {
     490       41218 :         Query      *qry = (Query *) node;
     491             : 
     492             :         /*
     493             :          * If we are starting at a Query, and sublevels_up is zero, then we
     494             :          * must also fix rangetable indexes in the Query itself --- namely
     495             :          * resultRelation, mergeTargetRelation, exclRelIndex and rowMarks
     496             :          * entries.  sublevels_up cannot be zero when recursing into a
     497             :          * subquery, so there's no need to have the same logic inside
     498             :          * OffsetVarNodes_walker.
     499             :          */
     500       41218 :         if (sublevels_up == 0)
     501             :         {
     502             :             ListCell   *l;
     503             : 
     504       41218 :             if (qry->resultRelation)
     505        1266 :                 qry->resultRelation += offset;
     506             : 
     507       41218 :             if (qry->mergeTargetRelation)
     508           0 :                 qry->mergeTargetRelation += offset;
     509             : 
     510       41218 :             if (qry->onConflict && qry->onConflict->exclRelIndex)
     511          36 :                 qry->onConflict->exclRelIndex += offset;
     512             : 
     513       41366 :             foreach(l, qry->rowMarks)
     514             :             {
     515         148 :                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
     516             : 
     517         148 :                 rc->rti += offset;
     518             :             }
     519             :         }
     520       41218 :         query_tree_walker(qry, OffsetVarNodes_walker, &context, 0);
     521             :     }
     522             :     else
     523       41218 :         OffsetVarNodes_walker(node, &context);
     524       82436 : }
     525             : 
     526             : static Relids
     527      753202 : offset_relid_set(Relids relids, int offset)
     528             : {
     529      753202 :     Relids      result = NULL;
     530             :     int         rtindex;
     531             : 
     532      753202 :     rtindex = -1;
     533      867140 :     while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
     534      113938 :         result = bms_add_member(result, rtindex + offset);
     535      753202 :     return result;
     536             : }
     537             : 
     538             : /*
     539             :  * ChangeVarNodes - adjust Var nodes for a specific change of RT index
     540             :  *
     541             :  * Find all Var nodes in the given tree belonging to a specific relation
     542             :  * (identified by sublevels_up and rt_index), and change their varno fields
     543             :  * to 'new_index'.  The varnosyn fields are changed too.  Also, adjust other
     544             :  * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr.
     545             :  * Specifying 'change_RangeTblRef' to false allows skipping RangeTblRef.
     546             :  * See ChangeVarNodesExtended for details.
     547             :  *
     548             :  * NOTE: although this has the form of a walker, we cheat and modify the
     549             :  * nodes in-place.  The given expression tree should have been copied
     550             :  * earlier to ensure that no unwanted side-effects occur!
     551             :  */
     552             : 
     553             : static bool
     554      343616 : ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context)
     555             : {
     556      343616 :     if (node == NULL)
     557      118740 :         return false;
     558             : 
     559      224876 :     if (context->callback && context->callback(node, context))
     560        4388 :         return false;
     561             : 
     562      220488 :     if (IsA(node, Var))
     563             :     {
     564       69922 :         Var        *var = (Var *) node;
     565             : 
     566       69922 :         if (var->varlevelsup == context->sublevels_up)
     567             :         {
     568       66820 :             if (var->varno == context->rt_index)
     569       42688 :                 var->varno = context->new_index;
     570       66820 :             var->varnullingrels = adjust_relid_set(var->varnullingrels,
     571             :                                                    context->rt_index,
     572             :                                                    context->new_index);
     573       66820 :             if (var->varnosyn == context->rt_index)
     574       42688 :                 var->varnosyn = context->new_index;
     575             :         }
     576       69922 :         return false;
     577             :     }
     578      150566 :     if (IsA(node, CurrentOfExpr))
     579             :     {
     580           0 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
     581             : 
     582           0 :         if (context->sublevels_up == 0 &&
     583           0 :             cexpr->cvarno == context->rt_index)
     584           0 :             cexpr->cvarno = context->new_index;
     585           0 :         return false;
     586             :     }
     587      150566 :     if (IsA(node, RangeTblRef))
     588             :     {
     589        5356 :         RangeTblRef *rtr = (RangeTblRef *) node;
     590             : 
     591        5356 :         if (context->sublevels_up == 0 &&
     592        3262 :             rtr->rtindex == context->rt_index)
     593        1712 :             rtr->rtindex = context->new_index;
     594             :         /* the subquery itself is visited separately */
     595        5356 :         return false;
     596             :     }
     597      145210 :     if (IsA(node, JoinExpr))
     598             :     {
     599         722 :         JoinExpr   *j = (JoinExpr *) node;
     600             : 
     601         722 :         if (context->sublevels_up == 0 &&
     602         722 :             j->rtindex == context->rt_index)
     603           0 :             j->rtindex = context->new_index;
     604             :         /* fall through to examine children */
     605             :     }
     606      145210 :     if (IsA(node, PlaceHolderVar))
     607             :     {
     608          96 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
     609             : 
     610          96 :         if (phv->phlevelsup == context->sublevels_up)
     611             :         {
     612          96 :             phv->phrels = adjust_relid_set(phv->phrels,
     613             :                                            context->rt_index,
     614             :                                            context->new_index);
     615          96 :             phv->phnullingrels = adjust_relid_set(phv->phnullingrels,
     616             :                                                   context->rt_index,
     617             :                                                   context->new_index);
     618             :         }
     619             :         /* fall through to examine children */
     620             :     }
     621      145210 :     if (IsA(node, PlanRowMark))
     622             :     {
     623           0 :         PlanRowMark *rowmark = (PlanRowMark *) node;
     624             : 
     625           0 :         if (context->sublevels_up == 0)
     626             :         {
     627           0 :             if (rowmark->rti == context->rt_index)
     628           0 :                 rowmark->rti = context->new_index;
     629           0 :             if (rowmark->prti == context->rt_index)
     630           0 :                 rowmark->prti = context->new_index;
     631             :         }
     632           0 :         return false;
     633             :     }
     634      145210 :     if (IsA(node, AppendRelInfo))
     635             :     {
     636           0 :         AppendRelInfo *appinfo = (AppendRelInfo *) node;
     637             : 
     638           0 :         if (context->sublevels_up == 0)
     639             :         {
     640           0 :             if (appinfo->parent_relid == context->rt_index)
     641           0 :                 appinfo->parent_relid = context->new_index;
     642           0 :             if (appinfo->child_relid == context->rt_index)
     643           0 :                 appinfo->child_relid = context->new_index;
     644             :         }
     645             :         /* fall through to examine children */
     646             :     }
     647             :     /* Shouldn't need to handle other planner auxiliary nodes here */
     648             :     Assert(!IsA(node, SpecialJoinInfo));
     649             :     Assert(!IsA(node, PlaceHolderInfo));
     650             :     Assert(!IsA(node, MinMaxAggInfo));
     651             : 
     652      145210 :     if (IsA(node, Query))
     653             :     {
     654             :         /* Recurse into subselects */
     655             :         bool        result;
     656             : 
     657        2388 :         context->sublevels_up++;
     658        2388 :         result = query_tree_walker((Query *) node, ChangeVarNodes_walker,
     659             :                                    context, 0);
     660        2388 :         context->sublevels_up--;
     661        2388 :         return result;
     662             :     }
     663      142822 :     return expression_tree_walker(node, ChangeVarNodes_walker, context);
     664             : }
     665             : 
     666             : /*
     667             :  * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an  additional
     668             :  *                          'callback' param
     669             :  *
     670             :  * ChangeVarNodes changes a given node and all of its underlying nodes.
     671             :  * This version of function additionally takes a callback, which has a
     672             :  * chance to process a node before ChangeVarNodes_walker.  A callback
     673             :  * returns a boolean value indicating if given node should be skipped from
     674             :  * further processing by ChangeVarNodes_walker.  The callback is called
     675             :  * only for expressions and other children nodes of a Query processed by
     676             :  * a walker.  Initial processing of the root Query doesn't involve the
     677             :  * callback.
     678             :  */
     679             : void
     680       36672 : ChangeVarNodesExtended(Node *node, int rt_index, int new_index,
     681             :                        int sublevels_up, ChangeVarNodes_callback callback)
     682             : {
     683             :     ChangeVarNodes_context context;
     684             : 
     685       36672 :     context.rt_index = rt_index;
     686       36672 :     context.new_index = new_index;
     687       36672 :     context.sublevels_up = sublevels_up;
     688       36672 :     context.callback = callback;
     689             : 
     690             :     /*
     691             :      * Must be prepared to start with a Query or a bare expression tree; if
     692             :      * it's a Query, go straight to query_tree_walker to make sure that
     693             :      * sublevels_up doesn't get incremented prematurely.
     694             :      */
     695       36672 :     if (node && IsA(node, Query))
     696        5198 :     {
     697        5198 :         Query      *qry = (Query *) node;
     698             : 
     699             :         /*
     700             :          * If we are starting at a Query, and sublevels_up is zero, then we
     701             :          * must also fix rangetable indexes in the Query itself --- namely
     702             :          * resultRelation, mergeTargetRelation, exclRelIndex  and rowMarks
     703             :          * entries.  sublevels_up cannot be zero when recursing into a
     704             :          * subquery, so there's no need to have the same logic inside
     705             :          * ChangeVarNodes_walker.
     706             :          */
     707        5198 :         if (sublevels_up == 0)
     708             :         {
     709             :             ListCell   *l;
     710             : 
     711        5198 :             if (qry->resultRelation == rt_index)
     712        3218 :                 qry->resultRelation = new_index;
     713             : 
     714        5198 :             if (qry->mergeTargetRelation == rt_index)
     715         852 :                 qry->mergeTargetRelation = new_index;
     716             : 
     717             :             /* this is unlikely to ever be used, but ... */
     718        5198 :             if (qry->onConflict && qry->onConflict->exclRelIndex == rt_index)
     719           0 :                 qry->onConflict->exclRelIndex = new_index;
     720             : 
     721        5382 :             foreach(l, qry->rowMarks)
     722             :             {
     723         184 :                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
     724             : 
     725         184 :                 if (rc->rti == rt_index)
     726          68 :                     rc->rti = new_index;
     727             :             }
     728             :         }
     729        5198 :         query_tree_walker(qry, ChangeVarNodes_walker, &context, 0);
     730             :     }
     731             :     else
     732       31474 :         ChangeVarNodes_walker(node, &context);
     733       36672 : }
     734             : 
     735             : void
     736       25218 : ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
     737             : {
     738       25218 :     ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL);
     739       25218 : }
     740             : 
     741             : /*
     742             :  * ChangeVarNodesWalkExpression - process expression within the custom
     743             :  *                                callback provided to the
     744             :  *                                ChangeVarNodesExtended.
     745             :  */
     746             : bool
     747        3552 : ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context)
     748             : {
     749        3552 :     return expression_tree_walker(node,
     750             :                                   ChangeVarNodes_walker,
     751             :                                   (void *) context);
     752             : }
     753             : 
     754             : /*
     755             :  * adjust_relid_set - substitute newrelid for oldrelid in a Relid set
     756             :  *
     757             :  * Attempt to remove oldrelid from a Relid set (as long as it's not a special
     758             :  * varno).  If oldrelid was found and removed, insert newrelid into a Relid
     759             :  * set (as long as it's not a special varno).  Therefore, when oldrelid is
     760             :  * a special varno, this function does nothing.  When newrelid is a special
     761             :  * varno, this function behaves as delete.
     762             :  */
     763             : Relids
     764      236240 : adjust_relid_set(Relids relids, int oldrelid, int newrelid)
     765             : {
     766      236240 :     if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids))
     767             :     {
     768             :         /* Ensure we have a modifiable copy */
     769       87796 :         relids = bms_copy(relids);
     770             :         /* Remove old, add new */
     771       87796 :         relids = bms_del_member(relids, oldrelid);
     772       87796 :         if (!IS_SPECIAL_VARNO(newrelid))
     773        9926 :             relids = bms_add_member(relids, newrelid);
     774             :     }
     775      236240 :     return relids;
     776             : }
     777             : 
     778             : /*
     779             :  * IncrementVarSublevelsUp - adjust Var nodes when pushing them down in tree
     780             :  *
     781             :  * Find all Var nodes in the given tree having varlevelsup >= min_sublevels_up,
     782             :  * and add delta_sublevels_up to their varlevelsup value.  This is needed when
     783             :  * an expression that's correct for some nesting level is inserted into a
     784             :  * subquery.  Ordinarily the initial call has min_sublevels_up == 0 so that
     785             :  * all Vars are affected.  The point of min_sublevels_up is that we can
     786             :  * increment it when we recurse into a sublink, so that local variables in
     787             :  * that sublink are not affected, only outer references to vars that belong
     788             :  * to the expression's original query level or parents thereof.
     789             :  *
     790             :  * Likewise for other nodes containing levelsup fields, such as Aggref.
     791             :  *
     792             :  * NOTE: although this has the form of a walker, we cheat and modify the
     793             :  * Var nodes in-place.  The given expression tree should have been copied
     794             :  * earlier to ensure that no unwanted side-effects occur!
     795             :  */
     796             : 
     797             : typedef struct
     798             : {
     799             :     int         delta_sublevels_up;
     800             :     int         min_sublevels_up;
     801             : } IncrementVarSublevelsUp_context;
     802             : 
     803             : static bool
     804     2604500 : IncrementVarSublevelsUp_walker(Node *node,
     805             :                                IncrementVarSublevelsUp_context *context)
     806             : {
     807     2604500 :     if (node == NULL)
     808      826884 :         return false;
     809     1777616 :     if (IsA(node, Var))
     810             :     {
     811      839344 :         Var        *var = (Var *) node;
     812             : 
     813      839344 :         if (var->varlevelsup >= context->min_sublevels_up)
     814       10894 :             var->varlevelsup += context->delta_sublevels_up;
     815      839344 :         return false;           /* done here */
     816             :     }
     817      938272 :     if (IsA(node, CurrentOfExpr))
     818             :     {
     819             :         /* this should not happen */
     820           0 :         if (context->min_sublevels_up == 0)
     821           0 :             elog(ERROR, "cannot push down CurrentOfExpr");
     822           0 :         return false;
     823             :     }
     824      938272 :     if (IsA(node, Aggref))
     825             :     {
     826        2394 :         Aggref     *agg = (Aggref *) node;
     827             : 
     828        2394 :         if (agg->agglevelsup >= context->min_sublevels_up)
     829          70 :             agg->agglevelsup += context->delta_sublevels_up;
     830             :         /* fall through to recurse into argument */
     831             :     }
     832      938272 :     if (IsA(node, GroupingFunc))
     833             :     {
     834          64 :         GroupingFunc *grp = (GroupingFunc *) node;
     835             : 
     836          64 :         if (grp->agglevelsup >= context->min_sublevels_up)
     837          64 :             grp->agglevelsup += context->delta_sublevels_up;
     838             :         /* fall through to recurse into argument */
     839             :     }
     840      938272 :     if (IsA(node, PlaceHolderVar))
     841             :     {
     842         832 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
     843             : 
     844         832 :         if (phv->phlevelsup >= context->min_sublevels_up)
     845         488 :             phv->phlevelsup += context->delta_sublevels_up;
     846             :         /* fall through to recurse into argument */
     847             :     }
     848      938272 :     if (IsA(node, ReturningExpr))
     849             :     {
     850         144 :         ReturningExpr *rexpr = (ReturningExpr *) node;
     851             : 
     852         144 :         if (rexpr->retlevelsup >= context->min_sublevels_up)
     853         144 :             rexpr->retlevelsup += context->delta_sublevels_up;
     854             :         /* fall through to recurse into argument */
     855             :     }
     856      938272 :     if (IsA(node, RangeTblEntry))
     857             :     {
     858      100738 :         RangeTblEntry *rte = (RangeTblEntry *) node;
     859             : 
     860      100738 :         if (rte->rtekind == RTE_CTE)
     861             :         {
     862        5678 :             if (rte->ctelevelsup >= context->min_sublevels_up)
     863        5648 :                 rte->ctelevelsup += context->delta_sublevels_up;
     864             :         }
     865      100738 :         return false;           /* allow range_table_walker to continue */
     866             :     }
     867      837534 :     if (IsA(node, Query))
     868             :     {
     869             :         /* Recurse into subselects */
     870             :         bool        result;
     871             : 
     872       16374 :         context->min_sublevels_up++;
     873       16374 :         result = query_tree_walker((Query *) node,
     874             :                                    IncrementVarSublevelsUp_walker,
     875             :                                    context,
     876             :                                    QTW_EXAMINE_RTES_BEFORE);
     877       16374 :         context->min_sublevels_up--;
     878       16374 :         return result;
     879             :     }
     880      821160 :     return expression_tree_walker(node, IncrementVarSublevelsUp_walker, context);
     881             : }
     882             : 
     883             : void
     884       86600 : IncrementVarSublevelsUp(Node *node, int delta_sublevels_up,
     885             :                         int min_sublevels_up)
     886             : {
     887             :     IncrementVarSublevelsUp_context context;
     888             : 
     889       86600 :     context.delta_sublevels_up = delta_sublevels_up;
     890       86600 :     context.min_sublevels_up = min_sublevels_up;
     891             : 
     892             :     /*
     893             :      * Must be prepared to start with a Query or a bare expression tree; if
     894             :      * it's a Query, we don't want to increment sublevels_up.
     895             :      */
     896       86600 :     query_or_expression_tree_walker(node,
     897             :                                     IncrementVarSublevelsUp_walker,
     898             :                                     &context,
     899             :                                     QTW_EXAMINE_RTES_BEFORE);
     900       86600 : }
     901             : 
     902             : /*
     903             :  * IncrementVarSublevelsUp_rtable -
     904             :  *  Same as IncrementVarSublevelsUp, but to be invoked on a range table.
     905             :  */
     906             : void
     907        4344 : IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up,
     908             :                                int min_sublevels_up)
     909             : {
     910             :     IncrementVarSublevelsUp_context context;
     911             : 
     912        4344 :     context.delta_sublevels_up = delta_sublevels_up;
     913        4344 :     context.min_sublevels_up = min_sublevels_up;
     914             : 
     915        4344 :     range_table_walker(rtable,
     916             :                        IncrementVarSublevelsUp_walker,
     917             :                        &context,
     918             :                        QTW_EXAMINE_RTES_BEFORE);
     919        4344 : }
     920             : 
     921             : /*
     922             :  * SetVarReturningType - adjust Var nodes for a specified varreturningtype.
     923             :  *
     924             :  * Find all Var nodes referring to the specified result relation in the given
     925             :  * expression and set their varreturningtype to the specified value.
     926             :  *
     927             :  * NOTE: although this has the form of a walker, we cheat and modify the
     928             :  * Var nodes in-place.  The given expression tree should have been copied
     929             :  * earlier to ensure that no unwanted side-effects occur!
     930             :  */
     931             : 
     932             : typedef struct
     933             : {
     934             :     int         result_relation;
     935             :     int         sublevels_up;
     936             :     VarReturningType returning_type;
     937             : } SetVarReturningType_context;
     938             : 
     939             : static bool
     940        2154 : SetVarReturningType_walker(Node *node, SetVarReturningType_context *context)
     941             : {
     942        2154 :     if (node == NULL)
     943         576 :         return false;
     944        1578 :     if (IsA(node, Var))
     945             :     {
     946         978 :         Var        *var = (Var *) node;
     947             : 
     948         978 :         if (var->varno == context->result_relation &&
     949         918 :             var->varlevelsup == context->sublevels_up)
     950         918 :             var->varreturningtype = context->returning_type;
     951             : 
     952         978 :         return false;
     953             :     }
     954             : 
     955         600 :     if (IsA(node, Query))
     956             :     {
     957             :         /* Recurse into subselects */
     958             :         bool        result;
     959             : 
     960          48 :         context->sublevels_up++;
     961          48 :         result = query_tree_walker((Query *) node, SetVarReturningType_walker,
     962             :                                    context, 0);
     963          48 :         context->sublevels_up--;
     964          48 :         return result;
     965             :     }
     966         552 :     return expression_tree_walker(node, SetVarReturningType_walker, context);
     967             : }
     968             : 
     969             : static void
     970        1170 : SetVarReturningType(Node *node, int result_relation, int sublevels_up,
     971             :                     VarReturningType returning_type)
     972             : {
     973             :     SetVarReturningType_context context;
     974             : 
     975        1170 :     context.result_relation = result_relation;
     976        1170 :     context.sublevels_up = sublevels_up;
     977        1170 :     context.returning_type = returning_type;
     978             : 
     979             :     /* Expect to start with an expression */
     980        1170 :     SetVarReturningType_walker(node, &context);
     981        1170 : }
     982             : 
     983             : /*
     984             :  * rangeTableEntry_used - detect whether an RTE is referenced somewhere
     985             :  *  in var nodes or join or setOp trees of a query or expression.
     986             :  */
     987             : 
     988             : typedef struct
     989             : {
     990             :     int         rt_index;
     991             :     int         sublevels_up;
     992             : } rangeTableEntry_used_context;
     993             : 
     994             : static bool
     995     4012212 : rangeTableEntry_used_walker(Node *node,
     996             :                             rangeTableEntry_used_context *context)
     997             : {
     998     4012212 :     if (node == NULL)
     999      754750 :         return false;
    1000     3257462 :     if (IsA(node, Var))
    1001             :     {
    1002      945416 :         Var        *var = (Var *) node;
    1003             : 
    1004      945416 :         if (var->varlevelsup == context->sublevels_up &&
    1005     1503378 :             (var->varno == context->rt_index ||
    1006      596834 :              bms_is_member(context->rt_index, var->varnullingrels)))
    1007      309710 :             return true;
    1008      635706 :         return false;
    1009             :     }
    1010     2312046 :     if (IsA(node, CurrentOfExpr))
    1011             :     {
    1012          12 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
    1013             : 
    1014          12 :         if (context->sublevels_up == 0 &&
    1015          12 :             cexpr->cvarno == context->rt_index)
    1016           0 :             return true;
    1017          12 :         return false;
    1018             :     }
    1019     2312034 :     if (IsA(node, RangeTblRef))
    1020             :     {
    1021      139476 :         RangeTblRef *rtr = (RangeTblRef *) node;
    1022             : 
    1023      139476 :         if (rtr->rtindex == context->rt_index &&
    1024       74140 :             context->sublevels_up == 0)
    1025       71170 :             return true;
    1026             :         /* the subquery itself is visited separately */
    1027       68306 :         return false;
    1028             :     }
    1029     2172558 :     if (IsA(node, JoinExpr))
    1030             :     {
    1031       48514 :         JoinExpr   *j = (JoinExpr *) node;
    1032             : 
    1033       48514 :         if (j->rtindex == context->rt_index &&
    1034          78 :             context->sublevels_up == 0)
    1035           0 :             return true;
    1036             :         /* fall through to examine children */
    1037             :     }
    1038             :     /* Shouldn't need to handle planner auxiliary nodes here */
    1039             :     Assert(!IsA(node, PlaceHolderVar));
    1040             :     Assert(!IsA(node, PlanRowMark));
    1041             :     Assert(!IsA(node, SpecialJoinInfo));
    1042             :     Assert(!IsA(node, AppendRelInfo));
    1043             :     Assert(!IsA(node, PlaceHolderInfo));
    1044             :     Assert(!IsA(node, MinMaxAggInfo));
    1045             : 
    1046     2172558 :     if (IsA(node, Query))
    1047             :     {
    1048             :         /* Recurse into subselects */
    1049             :         bool        result;
    1050             : 
    1051       16342 :         context->sublevels_up++;
    1052       16342 :         result = query_tree_walker((Query *) node, rangeTableEntry_used_walker,
    1053             :                                    context, 0);
    1054       16342 :         context->sublevels_up--;
    1055       16342 :         return result;
    1056             :     }
    1057     2156216 :     return expression_tree_walker(node, rangeTableEntry_used_walker, context);
    1058             : }
    1059             : 
    1060             : bool
    1061      396802 : rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
    1062             : {
    1063             :     rangeTableEntry_used_context context;
    1064             : 
    1065      396802 :     context.rt_index = rt_index;
    1066      396802 :     context.sublevels_up = sublevels_up;
    1067             : 
    1068             :     /*
    1069             :      * Must be prepared to start with a Query or a bare expression tree; if
    1070             :      * it's a Query, we don't want to increment sublevels_up.
    1071             :      */
    1072      396802 :     return query_or_expression_tree_walker(node,
    1073             :                                            rangeTableEntry_used_walker,
    1074             :                                            &context,
    1075             :                                            0);
    1076             : }
    1077             : 
    1078             : 
    1079             : /*
    1080             :  * If the given Query is an INSERT ... SELECT construct, extract and
    1081             :  * return the sub-Query node that represents the SELECT part.  Otherwise
    1082             :  * return the given Query.
    1083             :  *
    1084             :  * If subquery_ptr is not NULL, then *subquery_ptr is set to the location
    1085             :  * of the link to the SELECT subquery inside parsetree, or NULL if not an
    1086             :  * INSERT ... SELECT.
    1087             :  *
    1088             :  * This is a hack needed because transformations on INSERT ... SELECTs that
    1089             :  * appear in rule actions should be applied to the source SELECT, not to the
    1090             :  * INSERT part.  Perhaps this can be cleaned up with redesigned querytrees.
    1091             :  */
    1092             : Query *
    1093        3746 : getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
    1094             : {
    1095             :     Query      *selectquery;
    1096             :     RangeTblEntry *selectrte;
    1097             :     RangeTblRef *rtr;
    1098             : 
    1099        3746 :     if (subquery_ptr)
    1100        1380 :         *subquery_ptr = NULL;
    1101             : 
    1102        3746 :     if (parsetree == NULL)
    1103           0 :         return parsetree;
    1104        3746 :     if (parsetree->commandType != CMD_INSERT)
    1105        1634 :         return parsetree;
    1106             : 
    1107             :     /*
    1108             :      * Currently, this is ONLY applied to rule-action queries, and so we
    1109             :      * expect to find the OLD and NEW placeholder entries in the given query.
    1110             :      * If they're not there, it must be an INSERT/SELECT in which they've been
    1111             :      * pushed down to the SELECT.
    1112             :      */
    1113        2112 :     if (list_length(parsetree->rtable) >= 2 &&
    1114        2112 :         strcmp(rt_fetch(PRS2_OLD_VARNO, parsetree->rtable)->eref->aliasname,
    1115        1928 :                "old") == 0 &&
    1116        1928 :         strcmp(rt_fetch(PRS2_NEW_VARNO, parsetree->rtable)->eref->aliasname,
    1117             :                "new") == 0)
    1118        1928 :         return parsetree;
    1119             :     Assert(parsetree->jointree && IsA(parsetree->jointree, FromExpr));
    1120         184 :     if (list_length(parsetree->jointree->fromlist) != 1)
    1121           0 :         elog(ERROR, "expected to find SELECT subquery");
    1122         184 :     rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
    1123         184 :     if (!IsA(rtr, RangeTblRef))
    1124           0 :         elog(ERROR, "expected to find SELECT subquery");
    1125         184 :     selectrte = rt_fetch(rtr->rtindex, parsetree->rtable);
    1126         184 :     if (!(selectrte->rtekind == RTE_SUBQUERY &&
    1127         184 :           selectrte->subquery &&
    1128         184 :           IsA(selectrte->subquery, Query) &&
    1129         184 :           selectrte->subquery->commandType == CMD_SELECT))
    1130           0 :         elog(ERROR, "expected to find SELECT subquery");
    1131         184 :     selectquery = selectrte->subquery;
    1132         184 :     if (list_length(selectquery->rtable) >= 2 &&
    1133         184 :         strcmp(rt_fetch(PRS2_OLD_VARNO, selectquery->rtable)->eref->aliasname,
    1134         184 :                "old") == 0 &&
    1135         184 :         strcmp(rt_fetch(PRS2_NEW_VARNO, selectquery->rtable)->eref->aliasname,
    1136             :                "new") == 0)
    1137             :     {
    1138         184 :         if (subquery_ptr)
    1139          60 :             *subquery_ptr = &(selectrte->subquery);
    1140         184 :         return selectquery;
    1141             :     }
    1142           0 :     elog(ERROR, "could not find rule placeholders");
    1143             :     return NULL;                /* not reached */
    1144             : }
    1145             : 
    1146             : 
    1147             : /*
    1148             :  * Add the given qualifier condition to the query's WHERE clause
    1149             :  */
    1150             : void
    1151        3716 : AddQual(Query *parsetree, Node *qual)
    1152             : {
    1153             :     Node       *copy;
    1154             : 
    1155        3716 :     if (qual == NULL)
    1156        1728 :         return;
    1157             : 
    1158        1988 :     if (parsetree->commandType == CMD_UTILITY)
    1159             :     {
    1160             :         /*
    1161             :          * There's noplace to put the qual on a utility statement.
    1162             :          *
    1163             :          * If it's a NOTIFY, silently ignore the qual; this means that the
    1164             :          * NOTIFY will execute, whether or not there are any qualifying rows.
    1165             :          * While clearly wrong, this is much more useful than refusing to
    1166             :          * execute the rule at all, and extra NOTIFY events are harmless for
    1167             :          * typical uses of NOTIFY.
    1168             :          *
    1169             :          * If it isn't a NOTIFY, error out, since unconditional execution of
    1170             :          * other utility stmts is unlikely to be wanted.  (This case is not
    1171             :          * currently allowed anyway, but keep the test for safety.)
    1172             :          */
    1173           0 :         if (parsetree->utilityStmt && IsA(parsetree->utilityStmt, NotifyStmt))
    1174           0 :             return;
    1175             :         else
    1176           0 :             ereport(ERROR,
    1177             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1178             :                      errmsg("conditional utility statements are not implemented")));
    1179             :     }
    1180             : 
    1181        1988 :     if (parsetree->setOperations != NULL)
    1182             :     {
    1183             :         /*
    1184             :          * There's noplace to put the qual on a setop statement, either. (This
    1185             :          * could be fixed, but right now the planner simply ignores any qual
    1186             :          * condition on a setop query.)
    1187             :          */
    1188           0 :         ereport(ERROR,
    1189             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1190             :                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
    1191             :     }
    1192             : 
    1193             :     /* INTERSECT wants the original, but we need to copy - Jan */
    1194        1988 :     copy = copyObject(qual);
    1195             : 
    1196        1988 :     parsetree->jointree->quals = make_and_qual(parsetree->jointree->quals,
    1197             :                                                copy);
    1198             : 
    1199             :     /*
    1200             :      * We had better not have stuck an aggregate into the WHERE clause.
    1201             :      */
    1202             :     Assert(!contain_aggs_of_level(copy, 0));
    1203             : 
    1204             :     /*
    1205             :      * Make sure query is marked correctly if added qual has sublinks. Need
    1206             :      * not search qual when query is already marked.
    1207             :      */
    1208        1988 :     if (!parsetree->hasSubLinks)
    1209        1946 :         parsetree->hasSubLinks = checkExprHasSubLink(copy);
    1210             : }
    1211             : 
    1212             : 
    1213             : /*
    1214             :  * Invert the given clause and add it to the WHERE qualifications of the
    1215             :  * given querytree.  Inversion means "x IS NOT TRUE", not just "NOT x",
    1216             :  * else we will do the wrong thing when x evaluates to NULL.
    1217             :  */
    1218             : void
    1219         444 : AddInvertedQual(Query *parsetree, Node *qual)
    1220             : {
    1221             :     BooleanTest *invqual;
    1222             : 
    1223         444 :     if (qual == NULL)
    1224           0 :         return;
    1225             : 
    1226             :     /* Need not copy input qual, because AddQual will... */
    1227         444 :     invqual = makeNode(BooleanTest);
    1228         444 :     invqual->arg = (Expr *) qual;
    1229         444 :     invqual->booltesttype = IS_NOT_TRUE;
    1230         444 :     invqual->location = -1;
    1231             : 
    1232         444 :     AddQual(parsetree, (Node *) invqual);
    1233             : }
    1234             : 
    1235             : 
    1236             : /*
    1237             :  * add_nulling_relids() finds Vars and PlaceHolderVars that belong to any
    1238             :  * of the target_relids, and adds added_relids to their varnullingrels
    1239             :  * and phnullingrels fields.  If target_relids is NULL, all level-zero
    1240             :  * Vars and PHVs are modified.
    1241             :  */
    1242             : Node *
    1243        7774 : add_nulling_relids(Node *node,
    1244             :                    const Bitmapset *target_relids,
    1245             :                    const Bitmapset *added_relids)
    1246             : {
    1247             :     add_nulling_relids_context context;
    1248             : 
    1249        7774 :     context.target_relids = target_relids;
    1250        7774 :     context.added_relids = added_relids;
    1251        7774 :     context.sublevels_up = 0;
    1252        7774 :     return query_or_expression_tree_mutator(node,
    1253             :                                             add_nulling_relids_mutator,
    1254             :                                             &context,
    1255             :                                             0);
    1256             : }
    1257             : 
    1258             : static Node *
    1259       33044 : add_nulling_relids_mutator(Node *node,
    1260             :                            add_nulling_relids_context *context)
    1261             : {
    1262       33044 :     if (node == NULL)
    1263        1092 :         return NULL;
    1264       31952 :     if (IsA(node, Var))
    1265             :     {
    1266       12078 :         Var        *var = (Var *) node;
    1267             : 
    1268       12078 :         if (var->varlevelsup == context->sublevels_up &&
    1269       23940 :             (context->target_relids == NULL ||
    1270       11868 :              bms_is_member(var->varno, context->target_relids)))
    1271             :         {
    1272        6638 :             Relids      newnullingrels = bms_union(var->varnullingrels,
    1273             :                                                    context->added_relids);
    1274             : 
    1275             :             /* Copy the Var ... */
    1276        6638 :             var = copyObject(var);
    1277             :             /* ... and replace the copy's varnullingrels field */
    1278        6638 :             var->varnullingrels = newnullingrels;
    1279        6638 :             return (Node *) var;
    1280             :         }
    1281             :         /* Otherwise fall through to copy the Var normally */
    1282             :     }
    1283       19874 :     else if (IsA(node, PlaceHolderVar))
    1284             :     {
    1285         800 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    1286             : 
    1287         800 :         if (phv->phlevelsup == context->sublevels_up &&
    1288        1600 :             (context->target_relids == NULL ||
    1289         800 :              bms_overlap(phv->phrels, context->target_relids)))
    1290             :         {
    1291         800 :             Relids      newnullingrels = bms_union(phv->phnullingrels,
    1292             :                                                    context->added_relids);
    1293             : 
    1294             :             /*
    1295             :              * We don't modify the contents of the PHV's expression, only add
    1296             :              * to phnullingrels.  This corresponds to assuming that the PHV
    1297             :              * will be evaluated at the same level as before, then perhaps be
    1298             :              * nulled as it bubbles up.  Hence, just flat-copy the node ...
    1299             :              */
    1300         800 :             phv = makeNode(PlaceHolderVar);
    1301         800 :             memcpy(phv, node, sizeof(PlaceHolderVar));
    1302             :             /* ... and replace the copy's phnullingrels field */
    1303         800 :             phv->phnullingrels = newnullingrels;
    1304         800 :             return (Node *) phv;
    1305             :         }
    1306             :         /* Otherwise fall through to copy the PlaceHolderVar normally */
    1307             :     }
    1308       19074 :     else if (IsA(node, Query))
    1309             :     {
    1310             :         /* Recurse into RTE or sublink subquery */
    1311             :         Query      *newnode;
    1312             : 
    1313          48 :         context->sublevels_up++;
    1314          48 :         newnode = query_tree_mutator((Query *) node,
    1315             :                                      add_nulling_relids_mutator,
    1316             :                                      context,
    1317             :                                      0);
    1318          48 :         context->sublevels_up--;
    1319          48 :         return (Node *) newnode;
    1320             :     }
    1321       24466 :     return expression_tree_mutator(node, add_nulling_relids_mutator, context);
    1322             : }
    1323             : 
    1324             : /*
    1325             :  * remove_nulling_relids() removes mentions of the specified RT index(es)
    1326             :  * in Var.varnullingrels and PlaceHolderVar.phnullingrels fields within
    1327             :  * the given expression, except in nodes belonging to rels listed in
    1328             :  * except_relids.
    1329             :  */
    1330             : Node *
    1331      392270 : remove_nulling_relids(Node *node,
    1332             :                       const Bitmapset *removable_relids,
    1333             :                       const Bitmapset *except_relids)
    1334             : {
    1335             :     remove_nulling_relids_context context;
    1336             : 
    1337      392270 :     context.removable_relids = removable_relids;
    1338      392270 :     context.except_relids = except_relids;
    1339      392270 :     context.sublevels_up = 0;
    1340      392270 :     return query_or_expression_tree_mutator(node,
    1341             :                                             remove_nulling_relids_mutator,
    1342             :                                             &context,
    1343             :                                             0);
    1344             : }
    1345             : 
    1346             : static Node *
    1347      649380 : remove_nulling_relids_mutator(Node *node,
    1348             :                               remove_nulling_relids_context *context)
    1349             : {
    1350      649380 :     if (node == NULL)
    1351       57110 :         return NULL;
    1352      592270 :     if (IsA(node, Var))
    1353             :     {
    1354      433984 :         Var        *var = (Var *) node;
    1355             : 
    1356      433984 :         if (var->varlevelsup == context->sublevels_up &&
    1357      861454 :             !bms_is_member(var->varno, context->except_relids) &&
    1358      430680 :             bms_overlap(var->varnullingrels, context->removable_relids))
    1359             :         {
    1360             :             /* Copy the Var ... */
    1361       14902 :             var = copyObject(var);
    1362             :             /* ... and replace the copy's varnullingrels field */
    1363       14902 :             var->varnullingrels = bms_difference(var->varnullingrels,
    1364             :                                                  context->removable_relids);
    1365       14902 :             return (Node *) var;
    1366             :         }
    1367             :         /* Otherwise fall through to copy the Var normally */
    1368             :     }
    1369      158286 :     else if (IsA(node, PlaceHolderVar))
    1370             :     {
    1371        4458 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    1372             : 
    1373        4458 :         if (phv->phlevelsup == context->sublevels_up &&
    1374        4458 :             !bms_overlap(phv->phrels, context->except_relids))
    1375             :         {
    1376             :             /*
    1377             :              * Note: it might seem desirable to remove the PHV altogether if
    1378             :              * phnullingrels goes to empty.  Currently we dare not do that
    1379             :              * because we use PHVs in some cases to enforce separate identity
    1380             :              * of subexpressions; see wrap_option usages in prepjointree.c.
    1381             :              */
    1382             :             /* Copy the PlaceHolderVar and mutate what's below ... */
    1383             :             phv = (PlaceHolderVar *)
    1384        4458 :                 expression_tree_mutator(node,
    1385             :                                         remove_nulling_relids_mutator,
    1386             :                                         context);
    1387             :             /* ... and replace the copy's phnullingrels field */
    1388        4458 :             phv->phnullingrels = bms_difference(phv->phnullingrels,
    1389             :                                                 context->removable_relids);
    1390             :             /* We must also update phrels, if it contains a removable RTI */
    1391        4458 :             phv->phrels = bms_difference(phv->phrels,
    1392             :                                          context->removable_relids);
    1393             :             Assert(!bms_is_empty(phv->phrels));
    1394        4458 :             return (Node *) phv;
    1395             :         }
    1396             :         /* Otherwise fall through to copy the PlaceHolderVar normally */
    1397             :     }
    1398      153828 :     else if (IsA(node, Query))
    1399             :     {
    1400             :         /* Recurse into RTE or sublink subquery */
    1401             :         Query      *newnode;
    1402             : 
    1403         186 :         context->sublevels_up++;
    1404         186 :         newnode = query_tree_mutator((Query *) node,
    1405             :                                      remove_nulling_relids_mutator,
    1406             :                                      context,
    1407             :                                      0);
    1408         186 :         context->sublevels_up--;
    1409         186 :         return (Node *) newnode;
    1410             :     }
    1411      572724 :     return expression_tree_mutator(node, remove_nulling_relids_mutator, context);
    1412             : }
    1413             : 
    1414             : 
    1415             : /*
    1416             :  * replace_rte_variables() finds all Vars in an expression tree
    1417             :  * that reference a particular RTE, and replaces them with substitute
    1418             :  * expressions obtained from a caller-supplied callback function.
    1419             :  *
    1420             :  * When invoking replace_rte_variables on a portion of a Query, pass the
    1421             :  * address of the containing Query's hasSubLinks field as outer_hasSubLinks.
    1422             :  * Otherwise, pass NULL, but inserting a SubLink into a non-Query expression
    1423             :  * will then cause an error.
    1424             :  *
    1425             :  * Note: the business with inserted_sublink is needed to update hasSubLinks
    1426             :  * in subqueries when the replacement adds a subquery inside a subquery.
    1427             :  * Messy, isn't it?  We do not need to do similar pushups for hasAggs,
    1428             :  * because it isn't possible for this transformation to insert a level-zero
    1429             :  * aggregate reference into a subquery --- it could only insert outer aggs.
    1430             :  * Likewise for hasWindowFuncs.
    1431             :  *
    1432             :  * Note: usually, we'd not expose the mutator function or context struct
    1433             :  * for a function like this.  We do so because callbacks often find it
    1434             :  * convenient to recurse directly to the mutator on sub-expressions of
    1435             :  * what they will return.
    1436             :  */
    1437             : Node *
    1438      211380 : replace_rte_variables(Node *node, int target_varno, int sublevels_up,
    1439             :                       replace_rte_variables_callback callback,
    1440             :                       void *callback_arg,
    1441             :                       bool *outer_hasSubLinks)
    1442             : {
    1443             :     Node       *result;
    1444             :     replace_rte_variables_context context;
    1445             : 
    1446      211380 :     context.callback = callback;
    1447      211380 :     context.callback_arg = callback_arg;
    1448      211380 :     context.target_varno = target_varno;
    1449      211380 :     context.sublevels_up = sublevels_up;
    1450             : 
    1451             :     /*
    1452             :      * We try to initialize inserted_sublink to true if there is no need to
    1453             :      * detect new sublinks because the query already has some.
    1454             :      */
    1455      211380 :     if (node && IsA(node, Query))
    1456        5848 :         context.inserted_sublink = ((Query *) node)->hasSubLinks;
    1457      205532 :     else if (outer_hasSubLinks)
    1458      205326 :         context.inserted_sublink = *outer_hasSubLinks;
    1459             :     else
    1460         206 :         context.inserted_sublink = false;
    1461             : 
    1462             :     /*
    1463             :      * Must be prepared to start with a Query or a bare expression tree; if
    1464             :      * it's a Query, we don't want to increment sublevels_up.
    1465             :      */
    1466      211380 :     result = query_or_expression_tree_mutator(node,
    1467             :                                               replace_rte_variables_mutator,
    1468             :                                               &context,
    1469             :                                               0);
    1470             : 
    1471      211374 :     if (context.inserted_sublink)
    1472             :     {
    1473       24118 :         if (result && IsA(result, Query))
    1474         162 :             ((Query *) result)->hasSubLinks = true;
    1475       23956 :         else if (outer_hasSubLinks)
    1476       23956 :             *outer_hasSubLinks = true;
    1477             :         else
    1478           0 :             elog(ERROR, "replace_rte_variables inserted a SubLink, but has noplace to record it");
    1479             :     }
    1480             : 
    1481      211374 :     return result;
    1482             : }
    1483             : 
    1484             : Node *
    1485      959190 : replace_rte_variables_mutator(Node *node,
    1486             :                               replace_rte_variables_context *context)
    1487             : {
    1488      959190 :     if (node == NULL)
    1489      287232 :         return NULL;
    1490      671958 :     if (IsA(node, Var))
    1491             :     {
    1492      263982 :         Var        *var = (Var *) node;
    1493             : 
    1494      263982 :         if (var->varno == context->target_varno &&
    1495      131862 :             var->varlevelsup == context->sublevels_up)
    1496             :         {
    1497             :             /* Found a matching variable, make the substitution */
    1498             :             Node       *newnode;
    1499             : 
    1500      124046 :             newnode = context->callback(var, context);
    1501             :             /* Detect if we are adding a sublink to query */
    1502      124046 :             if (!context->inserted_sublink)
    1503      110856 :                 context->inserted_sublink = checkExprHasSubLink(newnode);
    1504      124046 :             return newnode;
    1505             :         }
    1506             :         /* otherwise fall through to copy the var normally */
    1507             :     }
    1508      407976 :     else if (IsA(node, CurrentOfExpr))
    1509             :     {
    1510           6 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
    1511             : 
    1512           6 :         if (cexpr->cvarno == context->target_varno &&
    1513           6 :             context->sublevels_up == 0)
    1514             :         {
    1515             :             /*
    1516             :              * We get here if a WHERE CURRENT OF expression turns out to apply
    1517             :              * to a view.  Someday we might be able to translate the
    1518             :              * expression to apply to an underlying table of the view, but
    1519             :              * right now it's not implemented.
    1520             :              */
    1521           6 :             ereport(ERROR,
    1522             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1523             :                      errmsg("WHERE CURRENT OF on a view is not implemented")));
    1524             :         }
    1525             :         /* otherwise fall through to copy the expr normally */
    1526             :     }
    1527      407970 :     else if (IsA(node, Query))
    1528             :     {
    1529             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
    1530             :         Query      *newnode;
    1531             :         bool        save_inserted_sublink;
    1532             : 
    1533        3276 :         context->sublevels_up++;
    1534        3276 :         save_inserted_sublink = context->inserted_sublink;
    1535        3276 :         context->inserted_sublink = ((Query *) node)->hasSubLinks;
    1536        3276 :         newnode = query_tree_mutator((Query *) node,
    1537             :                                      replace_rte_variables_mutator,
    1538             :                                      context,
    1539             :                                      0);
    1540        3276 :         newnode->hasSubLinks |= context->inserted_sublink;
    1541        3276 :         context->inserted_sublink = save_inserted_sublink;
    1542        3276 :         context->sublevels_up--;
    1543        3276 :         return (Node *) newnode;
    1544             :     }
    1545      544630 :     return expression_tree_mutator(node, replace_rte_variables_mutator, context);
    1546             : }
    1547             : 
    1548             : 
    1549             : /*
    1550             :  * map_variable_attnos() finds all user-column Vars in an expression tree
    1551             :  * that reference a particular RTE, and adjusts their varattnos according
    1552             :  * to the given mapping array (varattno n is replaced by attno_map[n-1]).
    1553             :  * Vars for system columns are not modified.
    1554             :  *
    1555             :  * A zero in the mapping array represents a dropped column, which should not
    1556             :  * appear in the expression.
    1557             :  *
    1558             :  * If the expression tree contains a whole-row Var for the target RTE,
    1559             :  * *found_whole_row is set to true.  In addition, if to_rowtype is
    1560             :  * not InvalidOid, we replace the Var with a Var of that vartype, inserting
    1561             :  * a ConvertRowtypeExpr to map back to the rowtype expected by the expression.
    1562             :  * (Therefore, to_rowtype had better be a child rowtype of the rowtype of the
    1563             :  * RTE we're changing references to.)  Callers that don't provide to_rowtype
    1564             :  * should report an error if *found_whole_row is true; we don't do that here
    1565             :  * because we don't know exactly what wording for the error message would
    1566             :  * be most appropriate.  The caller will be aware of the context.
    1567             :  *
    1568             :  * This could be built using replace_rte_variables and a callback function,
    1569             :  * but since we don't ever need to insert sublinks, replace_rte_variables is
    1570             :  * overly complicated.
    1571             :  */
    1572             : 
    1573             : typedef struct
    1574             : {
    1575             :     int         target_varno;   /* RTE index to search for */
    1576             :     int         sublevels_up;   /* (current) nesting depth */
    1577             :     const AttrMap *attno_map;   /* map array for user attnos */
    1578             :     Oid         to_rowtype;     /* change whole-row Vars to this type */
    1579             :     bool       *found_whole_row;    /* output flag */
    1580             : } map_variable_attnos_context;
    1581             : 
    1582             : static Node *
    1583      123964 : map_variable_attnos_mutator(Node *node,
    1584             :                             map_variable_attnos_context *context)
    1585             : {
    1586      123964 :     if (node == NULL)
    1587         172 :         return NULL;
    1588      123792 :     if (IsA(node, Var))
    1589             :     {
    1590       29088 :         Var        *var = (Var *) node;
    1591             : 
    1592       29088 :         if (var->varno == context->target_varno &&
    1593       28872 :             var->varlevelsup == context->sublevels_up)
    1594             :         {
    1595             :             /* Found a matching variable, make the substitution */
    1596       28872 :             Var        *newvar = (Var *) palloc(sizeof(Var));
    1597       28872 :             int         attno = var->varattno;
    1598             : 
    1599       28872 :             *newvar = *var;     /* initially copy all fields of the Var */
    1600             : 
    1601       28872 :             if (attno > 0)
    1602             :             {
    1603             :                 /* user-defined column, replace attno */
    1604       28548 :                 if (attno > context->attno_map->maplen ||
    1605       28548 :                     context->attno_map->attnums[attno - 1] == 0)
    1606           0 :                     elog(ERROR, "unexpected varattno %d in expression to be mapped",
    1607             :                          attno);
    1608       28548 :                 newvar->varattno = context->attno_map->attnums[attno - 1];
    1609             :                 /* If the syntactic referent is same RTE, fix it too */
    1610       28548 :                 if (newvar->varnosyn == context->target_varno)
    1611       28470 :                     newvar->varattnosyn = newvar->varattno;
    1612             :             }
    1613         324 :             else if (attno == 0)
    1614             :             {
    1615             :                 /* whole-row variable, warn caller */
    1616          54 :                 *(context->found_whole_row) = true;
    1617             : 
    1618             :                 /* If the caller expects us to convert the Var, do so. */
    1619          54 :                 if (OidIsValid(context->to_rowtype) &&
    1620          48 :                     context->to_rowtype != var->vartype)
    1621             :                 {
    1622             :                     ConvertRowtypeExpr *r;
    1623             : 
    1624             :                     /* This certainly won't work for a RECORD variable. */
    1625             :                     Assert(var->vartype != RECORDOID);
    1626             : 
    1627             :                     /* Var itself is changed to the requested type. */
    1628          48 :                     newvar->vartype = context->to_rowtype;
    1629             : 
    1630             :                     /*
    1631             :                      * Add a conversion node on top to convert back to the
    1632             :                      * original type expected by the expression.
    1633             :                      */
    1634          48 :                     r = makeNode(ConvertRowtypeExpr);
    1635          48 :                     r->arg = (Expr *) newvar;
    1636          48 :                     r->resulttype = var->vartype;
    1637          48 :                     r->convertformat = COERCE_IMPLICIT_CAST;
    1638          48 :                     r->location = -1;
    1639             : 
    1640          48 :                     return (Node *) r;
    1641             :                 }
    1642             :             }
    1643       28824 :             return (Node *) newvar;
    1644             :         }
    1645             :         /* otherwise fall through to copy the var normally */
    1646             :     }
    1647       94704 :     else if (IsA(node, ConvertRowtypeExpr))
    1648             :     {
    1649          48 :         ConvertRowtypeExpr *r = (ConvertRowtypeExpr *) node;
    1650          48 :         Var        *var = (Var *) r->arg;
    1651             : 
    1652             :         /*
    1653             :          * If this is coercing a whole-row Var that we need to convert, then
    1654             :          * just convert the Var without adding an extra ConvertRowtypeExpr.
    1655             :          * Effectively we're simplifying var::parenttype::grandparenttype into
    1656             :          * just var::grandparenttype.  This avoids building stacks of CREs if
    1657             :          * this function is applied repeatedly.
    1658             :          */
    1659          48 :         if (IsA(var, Var) &&
    1660          36 :             var->varno == context->target_varno &&
    1661          30 :             var->varlevelsup == context->sublevels_up &&
    1662          30 :             var->varattno == 0 &&
    1663          30 :             OidIsValid(context->to_rowtype) &&
    1664          30 :             context->to_rowtype != var->vartype)
    1665             :         {
    1666             :             ConvertRowtypeExpr *newnode;
    1667          30 :             Var        *newvar = (Var *) palloc(sizeof(Var));
    1668             : 
    1669             :             /* whole-row variable, warn caller */
    1670          30 :             *(context->found_whole_row) = true;
    1671             : 
    1672          30 :             *newvar = *var;     /* initially copy all fields of the Var */
    1673             : 
    1674             :             /* This certainly won't work for a RECORD variable. */
    1675             :             Assert(var->vartype != RECORDOID);
    1676             : 
    1677             :             /* Var itself is changed to the requested type. */
    1678          30 :             newvar->vartype = context->to_rowtype;
    1679             : 
    1680          30 :             newnode = (ConvertRowtypeExpr *) palloc(sizeof(ConvertRowtypeExpr));
    1681          30 :             *newnode = *r;      /* initially copy all fields of the CRE */
    1682          30 :             newnode->arg = (Expr *) newvar;
    1683             : 
    1684          30 :             return (Node *) newnode;
    1685             :         }
    1686             :         /* otherwise fall through to process the expression normally */
    1687             :     }
    1688       94656 :     else if (IsA(node, Query))
    1689             :     {
    1690             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
    1691             :         Query      *newnode;
    1692             : 
    1693           0 :         context->sublevels_up++;
    1694           0 :         newnode = query_tree_mutator((Query *) node,
    1695             :                                      map_variable_attnos_mutator,
    1696             :                                      context,
    1697             :                                      0);
    1698           0 :         context->sublevels_up--;
    1699           0 :         return (Node *) newnode;
    1700             :     }
    1701       94890 :     return expression_tree_mutator(node, map_variable_attnos_mutator, context);
    1702             : }
    1703             : 
    1704             : Node *
    1705       10016 : map_variable_attnos(Node *node,
    1706             :                     int target_varno, int sublevels_up,
    1707             :                     const AttrMap *attno_map,
    1708             :                     Oid to_rowtype, bool *found_whole_row)
    1709             : {
    1710             :     map_variable_attnos_context context;
    1711             : 
    1712       10016 :     context.target_varno = target_varno;
    1713       10016 :     context.sublevels_up = sublevels_up;
    1714       10016 :     context.attno_map = attno_map;
    1715       10016 :     context.to_rowtype = to_rowtype;
    1716       10016 :     context.found_whole_row = found_whole_row;
    1717             : 
    1718       10016 :     *found_whole_row = false;
    1719             : 
    1720             :     /*
    1721             :      * Must be prepared to start with a Query or a bare expression tree; if
    1722             :      * it's a Query, we don't want to increment sublevels_up.
    1723             :      */
    1724       10016 :     return query_or_expression_tree_mutator(node,
    1725             :                                             map_variable_attnos_mutator,
    1726             :                                             &context,
    1727             :                                             0);
    1728             : }
    1729             : 
    1730             : 
    1731             : /*
    1732             :  * ReplaceVarsFromTargetList - replace Vars with items from a targetlist
    1733             :  *
    1734             :  * Vars matching target_varno and sublevels_up are replaced by the
    1735             :  * entry with matching resno from targetlist, if there is one.
    1736             :  *
    1737             :  * If there is no matching resno for such a Var, the action depends on the
    1738             :  * nomatch_option:
    1739             :  *  REPLACEVARS_REPORT_ERROR: throw an error
    1740             :  *  REPLACEVARS_CHANGE_VARNO: change Var's varno to nomatch_varno
    1741             :  *  REPLACEVARS_SUBSTITUTE_NULL: replace Var with a NULL Const of same type
    1742             :  *
    1743             :  * The caller must also provide target_rte, the RTE describing the target
    1744             :  * relation.  This is needed to handle whole-row Vars referencing the target.
    1745             :  * We expand such Vars into RowExpr constructs.
    1746             :  *
    1747             :  * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must
    1748             :  * provide result_relation, the index of the result relation in the rewritten
    1749             :  * query.  This is needed to handle OLD/NEW RETURNING list Vars referencing
    1750             :  * target_varno.  When such Vars are expanded, their varreturningtype is
    1751             :  * copied onto any replacement Vars referencing result_relation.  In addition,
    1752             :  * if the replacement expression from the targetlist is not simply a Var
    1753             :  * referencing result_relation, it is wrapped in a ReturningExpr node (causing
    1754             :  * the executor to return NULL if the OLD/NEW row doesn't exist).
    1755             :  *
    1756             :  * Note that ReplaceVarFromTargetList always generates the replacement
    1757             :  * expression with varlevelsup = 0.  The caller is responsible for adjusting
    1758             :  * the varlevelsup if needed.  This simplifies the caller's life if it wants to
    1759             :  * cache the replacement expressions.
    1760             :  *
    1761             :  * outer_hasSubLinks works the same as for replace_rte_variables().
    1762             :  */
    1763             : 
    1764             : typedef struct
    1765             : {
    1766             :     RangeTblEntry *target_rte;
    1767             :     List       *targetlist;
    1768             :     int         result_relation;
    1769             :     ReplaceVarsNoMatchOption nomatch_option;
    1770             :     int         nomatch_varno;
    1771             : } ReplaceVarsFromTargetList_context;
    1772             : 
    1773             : static Node *
    1774       11306 : ReplaceVarsFromTargetList_callback(Var *var,
    1775             :                                    replace_rte_variables_context *context)
    1776             : {
    1777       11306 :     ReplaceVarsFromTargetList_context *rcon = (ReplaceVarsFromTargetList_context *) context->callback_arg;
    1778             :     Node       *newnode;
    1779             : 
    1780       11306 :     newnode = ReplaceVarFromTargetList(var,
    1781             :                                        rcon->target_rte,
    1782             :                                        rcon->targetlist,
    1783             :                                        rcon->result_relation,
    1784             :                                        rcon->nomatch_option,
    1785             :                                        rcon->nomatch_varno);
    1786             : 
    1787             :     /* Must adjust varlevelsup if replaced Var is within a subquery */
    1788       11306 :     if (var->varlevelsup > 0)
    1789         258 :         IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
    1790             : 
    1791       11306 :     return newnode;
    1792             : }
    1793             : 
    1794             : Node *
    1795      123284 : ReplaceVarFromTargetList(Var *var,
    1796             :                          RangeTblEntry *target_rte,
    1797             :                          List *targetlist,
    1798             :                          int result_relation,
    1799             :                          ReplaceVarsNoMatchOption nomatch_option,
    1800             :                          int nomatch_varno)
    1801             : {
    1802             :     TargetEntry *tle;
    1803             : 
    1804      123284 :     if (var->varattno == InvalidAttrNumber)
    1805             :     {
    1806             :         /* Must expand whole-tuple reference into RowExpr */
    1807             :         RowExpr    *rowexpr;
    1808             :         List       *colnames;
    1809             :         List       *fields;
    1810             :         ListCell   *lc;
    1811             : 
    1812             :         /*
    1813             :          * If generating an expansion for a var of a named rowtype (ie, this
    1814             :          * is a plain relation RTE), then we must include dummy items for
    1815             :          * dropped columns.  If the var is RECORD (ie, this is a JOIN), then
    1816             :          * omit dropped columns.  In the latter case, attach column names to
    1817             :          * the RowExpr for use of the executor and ruleutils.c.
    1818             :          *
    1819             :          * In order to be able to cache the results, we always generate the
    1820             :          * expansion with varlevelsup = 0.  The caller is responsible for
    1821             :          * adjusting it if needed.
    1822             :          *
    1823             :          * The varreturningtype is copied onto each individual field Var, so
    1824             :          * that it is handled correctly when we recurse.
    1825             :          */
    1826         732 :         expandRTE(target_rte,
    1827             :                   var->varno, 0 /* not varlevelsup */ ,
    1828             :                   var->varreturningtype, var->location,
    1829         732 :                   (var->vartype != RECORDOID),
    1830             :                   &colnames, &fields);
    1831         732 :         rowexpr = makeNode(RowExpr);
    1832             :         /* the fields will be set below */
    1833         732 :         rowexpr->args = NIL;
    1834         732 :         rowexpr->row_typeid = var->vartype;
    1835         732 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
    1836         732 :         rowexpr->colnames = (var->vartype == RECORDOID) ? colnames : NIL;
    1837         732 :         rowexpr->location = var->location;
    1838             :         /* Adjust the generated per-field Vars... */
    1839        2714 :         foreach(lc, fields)
    1840             :         {
    1841        1982 :             Node       *field = lfirst(lc);
    1842             : 
    1843        1982 :             if (field && IsA(field, Var))
    1844        1982 :                 field = ReplaceVarFromTargetList((Var *) field,
    1845             :                                                  target_rte,
    1846             :                                                  targetlist,
    1847             :                                                  result_relation,
    1848             :                                                  nomatch_option,
    1849             :                                                  nomatch_varno);
    1850        1982 :             rowexpr->args = lappend(rowexpr->args, field);
    1851             :         }
    1852             : 
    1853             :         /* Wrap it in a ReturningExpr, if needed, per comments above */
    1854         732 :         if (var->varreturningtype != VAR_RETURNING_DEFAULT)
    1855             :         {
    1856          78 :             ReturningExpr *rexpr = makeNode(ReturningExpr);
    1857             : 
    1858          78 :             rexpr->retlevelsup = 0;
    1859          78 :             rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
    1860          78 :             rexpr->retexpr = (Expr *) rowexpr;
    1861             : 
    1862          78 :             return (Node *) rexpr;
    1863             :         }
    1864             : 
    1865         654 :         return (Node *) rowexpr;
    1866             :     }
    1867             : 
    1868             :     /* Normal case referencing one targetlist element */
    1869      122552 :     tle = get_tle_by_resno(targetlist, var->varattno);
    1870             : 
    1871      122552 :     if (tle == NULL || tle->resjunk)
    1872             :     {
    1873             :         /* Failed to find column in targetlist */
    1874         434 :         switch (nomatch_option)
    1875             :         {
    1876           0 :             case REPLACEVARS_REPORT_ERROR:
    1877             :                 /* fall through, throw error below */
    1878           0 :                 break;
    1879             : 
    1880         284 :             case REPLACEVARS_CHANGE_VARNO:
    1881         284 :                 var = copyObject(var);
    1882         284 :                 var->varno = nomatch_varno;
    1883         284 :                 var->varlevelsup = 0;
    1884             :                 /* we leave the syntactic referent alone */
    1885         284 :                 return (Node *) var;
    1886             : 
    1887         150 :             case REPLACEVARS_SUBSTITUTE_NULL:
    1888             :                 {
    1889             :                     /*
    1890             :                      * If Var is of domain type, we must add a CoerceToDomain
    1891             :                      * node, in case there is a NOT NULL domain constraint.
    1892             :                      */
    1893             :                     int16       vartyplen;
    1894             :                     bool        vartypbyval;
    1895             : 
    1896         150 :                     get_typlenbyval(var->vartype, &vartyplen, &vartypbyval);
    1897         150 :                     return coerce_null_to_domain(var->vartype,
    1898             :                                                  var->vartypmod,
    1899             :                                                  var->varcollid,
    1900             :                                                  vartyplen,
    1901             :                                                  vartypbyval);
    1902             :                 }
    1903             :         }
    1904           0 :         elog(ERROR, "could not find replacement targetlist entry for attno %d",
    1905             :              var->varattno);
    1906             :         return NULL;            /* keep compiler quiet */
    1907             :     }
    1908             :     else
    1909             :     {
    1910             :         /* Make a copy of the tlist item to return */
    1911      122118 :         Expr       *newnode = copyObject(tle->expr);
    1912             : 
    1913             :         /*
    1914             :          * Check to see if the tlist item contains a PARAM_MULTIEXPR Param,
    1915             :          * and throw error if so.  This case could only happen when expanding
    1916             :          * an ON UPDATE rule's NEW variable and the referenced tlist item in
    1917             :          * the original UPDATE command is part of a multiple assignment. There
    1918             :          * seems no practical way to handle such cases without multiple
    1919             :          * evaluation of the multiple assignment's sub-select, which would
    1920             :          * create semantic oddities that users of rules would probably prefer
    1921             :          * not to cope with.  So treat it as an unimplemented feature.
    1922             :          */
    1923      122118 :         if (contains_multiexpr_param((Node *) newnode, NULL))
    1924           0 :             ereport(ERROR,
    1925             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1926             :                      errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command")));
    1927             : 
    1928             :         /* Handle any OLD/NEW RETURNING list Vars */
    1929      122118 :         if (var->varreturningtype != VAR_RETURNING_DEFAULT)
    1930             :         {
    1931             :             /*
    1932             :              * Copy varreturningtype onto any Vars in the tlist item that
    1933             :              * refer to result_relation (which had better be non-zero).
    1934             :              */
    1935        1170 :             if (result_relation == 0)
    1936           0 :                 elog(ERROR, "variable returning old/new found outside RETURNING list");
    1937             : 
    1938        1170 :             SetVarReturningType((Node *) newnode, result_relation,
    1939             :                                 0, var->varreturningtype);
    1940             : 
    1941             :             /* Wrap it in a ReturningExpr, if needed, per comments above */
    1942        1170 :             if (!IsA(newnode, Var) ||
    1943         894 :                 ((Var *) newnode)->varno != result_relation ||
    1944         834 :                 ((Var *) newnode)->varlevelsup != 0)
    1945             :             {
    1946         336 :                 ReturningExpr *rexpr = makeNode(ReturningExpr);
    1947             : 
    1948         336 :                 rexpr->retlevelsup = 0;
    1949         336 :                 rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
    1950         336 :                 rexpr->retexpr = newnode;
    1951             : 
    1952         336 :                 newnode = (Expr *) rexpr;
    1953             :             }
    1954             :         }
    1955             : 
    1956      122118 :         return (Node *) newnode;
    1957             :     }
    1958             : }
    1959             : 
    1960             : Node *
    1961        7632 : ReplaceVarsFromTargetList(Node *node,
    1962             :                           int target_varno, int sublevels_up,
    1963             :                           RangeTblEntry *target_rte,
    1964             :                           List *targetlist,
    1965             :                           int result_relation,
    1966             :                           ReplaceVarsNoMatchOption nomatch_option,
    1967             :                           int nomatch_varno,
    1968             :                           bool *outer_hasSubLinks)
    1969             : {
    1970             :     ReplaceVarsFromTargetList_context context;
    1971             : 
    1972        7632 :     context.target_rte = target_rte;
    1973        7632 :     context.targetlist = targetlist;
    1974        7632 :     context.result_relation = result_relation;
    1975        7632 :     context.nomatch_option = nomatch_option;
    1976        7632 :     context.nomatch_varno = nomatch_varno;
    1977             : 
    1978        7632 :     return replace_rte_variables(node, target_varno, sublevels_up,
    1979             :                                  ReplaceVarsFromTargetList_callback,
    1980             :                                  &context,
    1981             :                                  outer_hasSubLinks);
    1982             : }

Generated by: LCOV version 1.14