LCOV - differential code coverage report
Current view: top level - src/backend/rewrite - rewriteManip.c (source / functions) Coverage Total Hit UBC CBC
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 90.5 % 656 594 62 594
Current Date: 2025-09-06 07:49:51 +0900 Functions: 100.0 % 41 41 41
Baseline: lcov-20250906-005545-baseline Branches: 71.9 % 524 377 147 377
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 97.8 % 89 87 2 87
(360..) days: 89.4 % 567 507 60 507
Function coverage date bins:
(30,360] days: 100.0 % 6 6 6
(360..) days: 100.0 % 35 35 35
Branch coverage date bins:
(30,360] days: 78.8 % 52 41 11 41
(360..) days: 71.2 % 472 336 136 336

 Age         Owner                    Branch data    TLA  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
 6224 tgl@sss.pgh.pa.us          85                 :CBC        1366 : contain_aggs_of_level(Node *node, int levelsup)
                                 86                 :                : {
                                 87                 :                :     contain_aggs_of_level_context context;
                                 88                 :                : 
                                 89                 :           1366 :     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                 :                :      */
 8268                            95                 :           1366 :     return query_or_expression_tree_walker(node,
                                 96                 :                :                                            contain_aggs_of_level_walker,
                                 97                 :                :                                            &context,
                                 98                 :                :                                            0);
                                 99                 :                : }
                                100                 :                : 
                                101                 :                : static bool
 6224                           102                 :           6502 : contain_aggs_of_level_walker(Node *node,
                                103                 :                :                              contain_aggs_of_level_context *context)
                                104                 :                : {
 9305                           105         [ +  + ]:           6502 :     if (node == NULL)
                                106                 :            903 :         return false;
                                107         [ -  + ]:           5599 :     if (IsA(node, Aggref))
                                108                 :                :     {
 8128 tgl@sss.pgh.pa.us         109         [ #  # ]:UBC           0 :         if (((Aggref *) node)->agglevelsup == context->sublevels_up)
 7266 bruce@momjian.us          110                 :              0 :             return true;        /* abort the tree traversal and return true */
                                111                 :                :         /* else fall through to examine argument */
                                112                 :                :     }
 3766 andres@anarazel.de        113         [ -  + ]:CBC        5599 :     if (IsA(node, GroupingFunc))
                                114                 :                :     {
 3766 andres@anarazel.de        115         [ #  # ]:UBC           0 :         if (((GroupingFunc *) node)->agglevelsup == context->sublevels_up)
                                116                 :              0 :             return true;
                                117                 :                :         /* else fall through to examine argument */
                                118                 :                :     }
 8128 tgl@sss.pgh.pa.us         119         [ +  + ]:CBC        5599 :     if (IsA(node, Query))
                                120                 :                :     {
                                121                 :                :         /* Recurse into subselects */
                                122                 :                :         bool        result;
                                123                 :                : 
                                124                 :             65 :         context->sublevels_up++;
                                125                 :             65 :         result = query_tree_walker((Query *) node,
                                126                 :                :                                    contain_aggs_of_level_walker,
                                127                 :                :                                    context, 0);
                                128                 :             65 :         context->sublevels_up--;
                                129                 :             65 :         return result;
                                130                 :                :     }
 6224                           131                 :           5534 :     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
 6214                           149                 :             30 : locate_agg_of_level(Node *node, int levelsup)
                                150                 :                : {
                                151                 :                :     locate_agg_of_level_context context;
                                152                 :                : 
 5931 bruce@momjian.us          153                 :             30 :     context.agg_location = -1;  /* in case we find nothing */
 6214 tgl@sss.pgh.pa.us         154                 :             30 :     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                 :             30 :     (void) query_or_expression_tree_walker(node,
                                161                 :                :                                            locate_agg_of_level_walker,
                                162                 :                :                                            &context,
                                163                 :                :                                            0);
                                164                 :                : 
                                165                 :             30 :     return context.agg_location;
                                166                 :                : }
                                167                 :                : 
                                168                 :                : static bool
                                169                 :            120 : locate_agg_of_level_walker(Node *node,
                                170                 :                :                            locate_agg_of_level_context *context)
                                171                 :                : {
                                172         [ +  + ]:            120 :     if (node == NULL)
                                173                 :              6 :         return false;
                                174         [ +  + ]:            114 :     if (IsA(node, Aggref))
                                175                 :                :     {
                                176         [ +  + ]:             27 :         if (((Aggref *) node)->agglevelsup == context->sublevels_up &&
                                177         [ +  - ]:             24 :             ((Aggref *) node)->location >= 0)
                                178                 :                :         {
                                179                 :             24 :             context->agg_location = ((Aggref *) node)->location;
                                180                 :             24 :             return true;        /* abort the tree traversal and return true */
                                181                 :                :         }
                                182                 :                :         /* else fall through to examine argument */
                                183                 :                :     }
 3766 andres@anarazel.de        184         [ -  + ]:             90 :     if (IsA(node, GroupingFunc))
                                185                 :                :     {
 3766 andres@anarazel.de        186         [ #  # ]:UBC           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                 :                :     }
 6214 tgl@sss.pgh.pa.us         193         [ +  + ]:CBC          90 :     if (IsA(node, Query))
                                194                 :                :     {
                                195                 :                :         /* Recurse into subselects */
                                196                 :                :         bool        result;
                                197                 :                : 
                                198                 :              6 :         context->sublevels_up++;
                                199                 :              6 :         result = query_tree_walker((Query *) node,
                                200                 :                :                                    locate_agg_of_level_walker,
                                201                 :                :                                    context, 0);
                                202                 :              6 :         context->sublevels_up--;
                                203                 :              6 :         return result;
                                204                 :                :     }
  282 peter@eisentraut.org      205                 :             84 :     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
 4775 tgl@sss.pgh.pa.us         214                 :           4755 : 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                 :                :      */
 6096                           220                 :           4755 :     return query_or_expression_tree_walker(node,
                                221                 :                :                                            contain_windowfuncs_walker,
                                222                 :                :                                            NULL,
                                223                 :                :                                            0);
                                224                 :                : }
                                225                 :                : 
                                226                 :                : static bool
                                227                 :           5235 : contain_windowfuncs_walker(Node *node, void *context)
                                228                 :                : {
                                229         [ +  + ]:           5235 :     if (node == NULL)
                                230                 :             84 :         return false;
                                231         [ +  + ]:           5151 :     if (IsA(node, WindowFunc))
 5931 bruce@momjian.us          232                 :              6 :         return true;            /* abort the tree traversal and return true */
                                233                 :                :     /* Mustn't recurse into subselects */
  282 peter@eisentraut.org      234                 :           5145 :     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
 6096 tgl@sss.pgh.pa.us         251                 :              3 : locate_windowfunc(Node *node)
                                252                 :                : {
                                253                 :                :     locate_windowfunc_context context;
                                254                 :                : 
 5931 bruce@momjian.us          255                 :              3 :     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                 :                :      */
 6096 tgl@sss.pgh.pa.us         261                 :              3 :     (void) query_or_expression_tree_walker(node,
                                262                 :                :                                            locate_windowfunc_walker,
                                263                 :                :                                            &context,
                                264                 :                :                                            0);
                                265                 :                : 
                                266                 :              3 :     return context.win_location;
                                267                 :                : }
                                268                 :                : 
                                269                 :                : static bool
                                270                 :              3 : locate_windowfunc_walker(Node *node, locate_windowfunc_context *context)
                                271                 :                : {
                                272         [ -  + ]:              3 :     if (node == NULL)
 6096 tgl@sss.pgh.pa.us         273                 :UBC           0 :         return false;
 6096 tgl@sss.pgh.pa.us         274         [ +  - ]:CBC           3 :     if (IsA(node, WindowFunc))
                                275                 :                :     {
                                276         [ +  - ]:              3 :         if (((WindowFunc *) node)->location >= 0)
                                277                 :                :         {
                                278                 :              3 :             context->win_location = ((WindowFunc *) node)->location;
                                279                 :              3 :             return true;        /* abort the tree traversal and return true */
                                280                 :                :         }
                                281                 :                :         /* else fall through to examine argument */
                                282                 :                :     }
                                283                 :                :     /* Mustn't recurse into subselects */
  282 peter@eisentraut.org      284                 :UBC           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
 9305 tgl@sss.pgh.pa.us         292                 :CBC       59988 : 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                 :                :      */
 8268                           298                 :          59988 :     return query_or_expression_tree_walker(node,
                                299                 :                :                                            checkExprHasSubLink_walker,
                                300                 :                :                                            NULL,
                                301                 :                :                                            QTW_IGNORE_RC_SUBQUERIES);
                                302                 :                : }
                                303                 :                : 
                                304                 :                : static bool
 9305                           305                 :         101103 : checkExprHasSubLink_walker(Node *node, void *context)
                                306                 :                : {
                                307         [ +  + ]:         101103 :     if (node == NULL)
                                308                 :           1934 :         return false;
                                309         [ +  + ]:          99169 :     if (IsA(node, SubLink))
 7266 bruce@momjian.us          310                 :            928 :         return true;            /* abort the tree traversal and return true */
 9305 tgl@sss.pgh.pa.us         311                 :          98241 :     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
 4098                           321                 :          94879 : contains_multiexpr_param(Node *node, void *context)
                                322                 :                : {
                                323         [ +  + ]:          94879 :     if (node == NULL)
                                324                 :           1698 :         return false;
                                325         [ +  + ]:          93181 :     if (IsA(node, Param))
                                326                 :                :     {
                                327         [ -  + ]:            241 :         if (((Param *) node)->paramkind == PARAM_MULTIEXPR)
 4098 tgl@sss.pgh.pa.us         328                 :UBC           0 :             return true;        /* abort the tree traversal and return true */
 4098 tgl@sss.pgh.pa.us         329                 :CBC         241 :         return false;
                                330                 :                :     }
                                331                 :          92940 :     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
 1005 alvherre@alvh.no-ip.      347                 :          22978 : CombineRangeTables(List **dst_rtable, List **dst_perminfos,
                                348                 :                :                    List *src_rtable, List *src_perminfos)
                                349                 :                : {
                                350                 :                :     ListCell   *l;
                                351                 :          22978 :     int         offset = list_length(*dst_perminfos);
                                352                 :                : 
                                353         [ +  + ]:          22978 :     if (offset > 0)
                                354                 :                :     {
                                355   [ +  +  +  +  :          56248 :         foreach(l, src_rtable)
                                              +  + ]
                                356                 :                :         {
                                357                 :          37239 :             RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
                                358                 :                : 
                                359         [ +  + ]:          37239 :             if (rte->perminfoindex > 0)
                                360                 :          16976 :                 rte->perminfoindex += offset;
                                361                 :                :         }
                                362                 :                :     }
                                363                 :                : 
                                364                 :          22978 :     *dst_perminfos = list_concat(*dst_perminfos, src_perminfos);
                                365                 :          22978 :     *dst_rtable = list_concat(*dst_rtable, src_rtable);
                                366                 :          22978 : }
                                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
 9472 tgl@sss.pgh.pa.us         388                 :        1096227 : OffsetVarNodes_walker(Node *node, OffsetVarNodes_context *context)
                                389                 :                : {
                                390         [ +  + ]:        1096227 :     if (node == NULL)
                                391                 :         340555 :         return false;
                                392         [ +  + ]:         755672 :     if (IsA(node, Var))
                                393                 :                :     {
                                394                 :         393325 :         Var        *var = (Var *) node;
                                395                 :                : 
                                396         [ +  + ]:         393325 :         if (var->varlevelsup == context->sublevels_up)
                                397                 :                :         {
                                398                 :         380526 :             var->varno += context->offset;
  950                           399                 :         380526 :             var->varnullingrels = offset_relid_set(var->varnullingrels,
                                400                 :                :                                                    context->offset);
 2067                           401         [ +  - ]:         380526 :             if (var->varnosyn > 0)
                                402                 :         380526 :                 var->varnosyn += context->offset;
                                403                 :                :         }
 9472                           404                 :         393325 :         return false;
                                405                 :                :     }
 6662                           406         [ -  + ]:         362347 :     if (IsA(node, CurrentOfExpr))
                                407                 :                :     {
 6662 tgl@sss.pgh.pa.us         408                 :UBC           0 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
                                409                 :                : 
                                410         [ #  # ]:              0 :         if (context->sublevels_up == 0)
                                411                 :              0 :             cexpr->cvarno += context->offset;
                                412                 :              0 :         return false;
                                413                 :                :     }
 9125 tgl@sss.pgh.pa.us         414         [ +  + ]:CBC      362347 :     if (IsA(node, RangeTblRef))
                                415                 :                :     {
 8934 bruce@momjian.us          416                 :          31660 :         RangeTblRef *rtr = (RangeTblRef *) node;
                                417                 :                : 
 9125 tgl@sss.pgh.pa.us         418         [ +  + ]:          31660 :         if (context->sublevels_up == 0)
                                419                 :          28628 :             rtr->rtindex += context->offset;
                                420                 :                :         /* the subquery itself is visited separately */
 9472                           421                 :          31660 :         return false;
                                422                 :                :     }
 8579                           423         [ +  + ]:         330687 :     if (IsA(node, JoinExpr))
                                424                 :                :     {
 8403 bruce@momjian.us          425                 :           7318 :         JoinExpr   *j = (JoinExpr *) node;
                                426                 :                : 
 6037 tgl@sss.pgh.pa.us         427   [ +  +  +  + ]:           7318 :         if (j->rtindex && context->sublevels_up == 0)
 8579                           428                 :           6824 :             j->rtindex += context->offset;
                                429                 :                :         /* fall through to examine children */
                                430                 :                :     }
 6164                           431         [ +  + ]:         330687 :     if (IsA(node, PlaceHolderVar))
                                432                 :                :     {
                                433                 :            235 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                                434                 :                : 
                                435         [ +  + ]:            235 :         if (phv->phlevelsup == context->sublevels_up)
                                436                 :                :         {
                                437                 :            181 :             phv->phrels = offset_relid_set(phv->phrels,
                                438                 :                :                                            context->offset);
  950                           439                 :            181 :             phv->phnullingrels = offset_relid_set(phv->phnullingrels,
                                440                 :                :                                                   context->offset);
                                441                 :                :         }
                                442                 :                :         /* fall through to examine children */
                                443                 :                :     }
 7158                           444         [ +  + ]:         330687 :     if (IsA(node, AppendRelInfo))
                                445                 :                :     {
                                446                 :            534 :         AppendRelInfo *appinfo = (AppendRelInfo *) node;
                                447                 :                : 
                                448         [ +  - ]:            534 :         if (context->sublevels_up == 0)
                                449                 :                :         {
                                450                 :            534 :             appinfo->parent_relid += context->offset;
                                451                 :            534 :             appinfo->child_relid += context->offset;
                                452                 :                :         }
                                453                 :                :         /* fall through to examine children */
                                454                 :                :     }
                                455                 :                :     /* Shouldn't need to handle other planner auxiliary nodes here */
 5117                           456         [ -  + ]:         330687 :     Assert(!IsA(node, PlanRowMark));
 6163                           457         [ -  + ]:         330687 :     Assert(!IsA(node, SpecialJoinInfo));
                                458         [ -  + ]:         330687 :     Assert(!IsA(node, PlaceHolderInfo));
 5420                           459         [ -  + ]:         330687 :     Assert(!IsA(node, MinMaxAggInfo));
                                460                 :                : 
 9472                           461         [ +  + ]:         330687 :     if (IsA(node, Query))
                                462                 :                :     {
                                463                 :                :         /* Recurse into subselects */
                                464                 :                :         bool        result;
                                465                 :                : 
 9125                           466                 :           2691 :         context->sublevels_up++;
                                467                 :           2691 :         result = query_tree_walker((Query *) node, OffsetVarNodes_walker,
                                468                 :                :                                    context, 0);
                                469                 :           2691 :         context->sublevels_up--;
                                470                 :           2691 :         return result;
                                471                 :                :     }
  282 peter@eisentraut.org      472                 :         327996 :     return expression_tree_walker(node, OffsetVarNodes_walker, context);
                                473                 :                : }
                                474                 :                : 
                                475                 :                : void
 9472 tgl@sss.pgh.pa.us         476                 :          41560 : OffsetVarNodes(Node *node, int offset, int sublevels_up)
                                477                 :                : {
                                478                 :                :     OffsetVarNodes_context context;
                                479                 :                : 
                                480                 :          41560 :     context.offset = offset;
                                481                 :          41560 :     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                 :                :      */
 9125                           488   [ +  +  +  + ]:          41560 :     if (node && IsA(node, Query))
 9040                           489                 :          20780 :     {
 8934 bruce@momjian.us          490                 :          20780 :         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                 :                :          */
 9040 tgl@sss.pgh.pa.us         500         [ +  - ]:          20780 :         if (sublevels_up == 0)
                                501                 :                :         {
                                502                 :                :             ListCell   *l;
                                503                 :                : 
                                504         [ +  + ]:          20780 :             if (qry->resultRelation)
                                505                 :            633 :                 qry->resultRelation += offset;
                                506                 :                : 
  555 dean.a.rasheed@gmail      507         [ -  + ]:          20780 :             if (qry->mergeTargetRelation)
  555 dean.a.rasheed@gmail      508                 :UBC           0 :                 qry->mergeTargetRelation += offset;
                                509                 :                : 
 3769 andres@anarazel.de        510   [ +  +  +  + ]:CBC       20780 :             if (qry->onConflict && qry->onConflict->exclRelIndex)
                                511                 :             18 :                 qry->onConflict->exclRelIndex += offset;
                                512                 :                : 
 9040 tgl@sss.pgh.pa.us         513   [ +  +  +  +  :          20854 :             foreach(l, qry->rowMarks)
                                              +  + ]
                                514                 :                :             {
 7069                           515                 :             74 :                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
                                516                 :                : 
                                517                 :             74 :                 rc->rti += offset;
                                518                 :                :             }
                                519                 :                :         }
  282 peter@eisentraut.org      520                 :          20780 :         query_tree_walker(qry, OffsetVarNodes_walker, &context, 0);
                                521                 :                :     }
                                522                 :                :     else
 9125 tgl@sss.pgh.pa.us         523                 :          20780 :         OffsetVarNodes_walker(node, &context);
 9472                           524                 :          41560 : }
                                525                 :                : 
                                526                 :                : static Relids
 8246                           527                 :         380888 : offset_relid_set(Relids relids, int offset)
                                528                 :                : {
                                529                 :         380888 :     Relids      result = NULL;
                                530                 :                :     int         rtindex;
                                531                 :                : 
 3935                           532                 :         380888 :     rtindex = -1;
                                533         [ +  + ]:         441950 :     while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
 8246                           534                 :          61062 :         result = bms_add_member(result, rtindex + offset);
                                535                 :         380888 :     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
 9472                           554                 :         172954 : ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context)
                                555                 :                : {
                                556         [ +  + ]:         172954 :     if (node == NULL)
                                557                 :          59370 :         return false;
                                558                 :                : 
  122 akorotkov@postgresql      559   [ +  +  +  + ]:         113584 :     if (context->callback && context->callback(node, context))
                                560                 :           2194 :         return false;
                                561                 :                : 
 9472 tgl@sss.pgh.pa.us         562         [ +  + ]:         111390 :     if (IsA(node, Var))
                                563                 :                :     {
                                564                 :          35320 :         Var        *var = (Var *) node;
                                565                 :                : 
  950                           566         [ +  + ]:          35320 :         if (var->varlevelsup == context->sublevels_up)
                                567                 :                :         {
                                568         [ +  + ]:          33769 :             if (var->varno == context->rt_index)
                                569                 :          21703 :                 var->varno = context->new_index;
                                570                 :          33769 :             var->varnullingrels = adjust_relid_set(var->varnullingrels,
                                571                 :                :                                                    context->rt_index,
                                572                 :                :                                                    context->new_index);
 2067                           573         [ +  + ]:          33769 :             if (var->varnosyn == context->rt_index)
                                574                 :          21703 :                 var->varnosyn = context->new_index;
                                575                 :                :         }
 9472                           576                 :          35320 :         return false;
                                577                 :                :     }
 6662                           578         [ -  + ]:          76070 :     if (IsA(node, CurrentOfExpr))
                                579                 :                :     {
 6662 tgl@sss.pgh.pa.us         580                 :UBC           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                 :                :     }
  122 akorotkov@postgresql      587         [ +  + ]:CBC       76070 :     if (IsA(node, RangeTblRef))
                                588                 :                :     {
 8934 bruce@momjian.us          589                 :           2678 :         RangeTblRef *rtr = (RangeTblRef *) node;
                                590                 :                : 
 9125 tgl@sss.pgh.pa.us         591         [ +  + ]:           2678 :         if (context->sublevels_up == 0 &&
                                592         [ +  + ]:           1631 :             rtr->rtindex == context->rt_index)
                                593                 :            856 :             rtr->rtindex = context->new_index;
                                594                 :                :         /* the subquery itself is visited separately */
 9472                           595                 :           2678 :         return false;
                                596                 :                :     }
 8579                           597         [ +  + ]:          73392 :     if (IsA(node, JoinExpr))
                                598                 :                :     {
 8403 bruce@momjian.us          599                 :            361 :         JoinExpr   *j = (JoinExpr *) node;
                                600                 :                : 
 8579 tgl@sss.pgh.pa.us         601         [ +  - ]:            361 :         if (context->sublevels_up == 0 &&
                                602         [ -  + ]:            361 :             j->rtindex == context->rt_index)
 8579 tgl@sss.pgh.pa.us         603                 :UBC           0 :             j->rtindex = context->new_index;
                                604                 :                :         /* fall through to examine children */
                                605                 :                :     }
 6164 tgl@sss.pgh.pa.us         606         [ +  + ]:CBC       73392 :     if (IsA(node, PlaceHolderVar))
                                607                 :                :     {
                                608                 :             48 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                                609                 :                : 
                                610         [ +  - ]:             48 :         if (phv->phlevelsup == context->sublevels_up)
                                611                 :                :         {
                                612                 :             48 :             phv->phrels = adjust_relid_set(phv->phrels,
                                613                 :                :                                            context->rt_index,
                                614                 :                :                                            context->new_index);
  950                           615                 :             48 :             phv->phnullingrels = adjust_relid_set(phv->phnullingrels,
                                616                 :                :                                                   context->rt_index,
                                617                 :                :                                                   context->new_index);
                                618                 :                :         }
                                619                 :                :         /* fall through to examine children */
                                620                 :                :     }
 5117                           621         [ -  + ]:          73392 :     if (IsA(node, PlanRowMark))
                                622                 :                :     {
 5117 tgl@sss.pgh.pa.us         623                 :UBC           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                 :                :     }
 7158 tgl@sss.pgh.pa.us         634         [ -  + ]:CBC       73392 :     if (IsA(node, AppendRelInfo))
                                635                 :                :     {
 7158 tgl@sss.pgh.pa.us         636                 :UBC           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 */
 6163 tgl@sss.pgh.pa.us         648         [ -  + ]:CBC       73392 :     Assert(!IsA(node, SpecialJoinInfo));
                                649         [ -  + ]:          73392 :     Assert(!IsA(node, PlaceHolderInfo));
 5420                           650         [ -  + ]:          73392 :     Assert(!IsA(node, MinMaxAggInfo));
                                651                 :                : 
 9472                           652         [ +  + ]:          73392 :     if (IsA(node, Query))
                                653                 :                :     {
                                654                 :                :         /* Recurse into subselects */
                                655                 :                :         bool        result;
                                656                 :                : 
 9125                           657                 :           1194 :         context->sublevels_up++;
                                658                 :           1194 :         result = query_tree_walker((Query *) node, ChangeVarNodes_walker,
                                659                 :                :                                    context, 0);
                                660                 :           1194 :         context->sublevels_up--;
                                661                 :           1194 :         return result;
                                662                 :                :     }
  282 peter@eisentraut.org      663                 :          72198 :     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
  205 akorotkov@postgresql      680                 :          18596 : ChangeVarNodesExtended(Node *node, int rt_index, int new_index,
                                681                 :                :                        int sublevels_up, ChangeVarNodes_callback callback)
                                682                 :                : {
                                683                 :                :     ChangeVarNodes_context context;
                                684                 :                : 
 9472 tgl@sss.pgh.pa.us         685                 :          18596 :     context.rt_index = rt_index;
                                686                 :          18596 :     context.new_index = new_index;
                                687                 :          18596 :     context.sublevels_up = sublevels_up;
  122 akorotkov@postgresql      688                 :          18596 :     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                 :                :      */
 9125 tgl@sss.pgh.pa.us         695   [ +  +  +  + ]:          18596 :     if (node && IsA(node, Query))
 9040                           696                 :           2599 :     {
 8934 bruce@momjian.us          697                 :           2599 :         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                 :                :          */
 9040 tgl@sss.pgh.pa.us         707         [ +  - ]:           2599 :         if (sublevels_up == 0)
                                708                 :                :         {
                                709                 :                :             ListCell   *l;
                                710                 :                : 
                                711         [ +  + ]:           2599 :             if (qry->resultRelation == rt_index)
                                712                 :           1609 :                 qry->resultRelation = new_index;
                                713                 :                : 
  555 dean.a.rasheed@gmail      714         [ +  + ]:           2599 :             if (qry->mergeTargetRelation == rt_index)
                                715                 :            426 :                 qry->mergeTargetRelation = new_index;
                                716                 :                : 
                                717                 :                :             /* this is unlikely to ever be used, but ... */
 3769 andres@anarazel.de        718   [ +  +  -  + ]:           2599 :             if (qry->onConflict && qry->onConflict->exclRelIndex == rt_index)
 3769 andres@anarazel.de        719                 :UBC           0 :                 qry->onConflict->exclRelIndex = new_index;
                                720                 :                : 
 9040 tgl@sss.pgh.pa.us         721   [ +  +  +  +  :CBC        2691 :             foreach(l, qry->rowMarks)
                                              +  + ]
                                722                 :                :             {
 7069                           723                 :             92 :                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
                                724                 :                : 
                                725         [ +  + ]:             92 :                 if (rc->rti == rt_index)
                                726                 :             34 :                     rc->rti = new_index;
                                727                 :                :             }
                                728                 :                :         }
  282 peter@eisentraut.org      729                 :           2599 :         query_tree_walker(qry, ChangeVarNodes_walker, &context, 0);
                                730                 :                :     }
                                731                 :                :     else
 9125 tgl@sss.pgh.pa.us         732                 :          15997 :         ChangeVarNodes_walker(node, &context);
 9472                           733                 :          18596 : }
                                734                 :                : 
                                735                 :                : void
  205 akorotkov@postgresql      736                 :          12848 : ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
                                737                 :                : {
  122                           738                 :          12848 :     ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL);
                                739                 :          12848 : }
                                740                 :                : 
                                741                 :                : /*
                                742                 :                :  * ChangeVarNodesWalkExpression - process expression within the custom
                                743                 :                :  *                                callback provided to the
                                744                 :                :  *                                ChangeVarNodesExtended.
                                745                 :                :  */
                                746                 :                : bool
                                747                 :           1776 : ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context)
                                748                 :                : {
                                749                 :           1776 :     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
 8246 tgl@sss.pgh.pa.us         764                 :         117943 : adjust_relid_set(Relids relids, int oldrelid, int newrelid)
                                765                 :                : {
  821                           766   [ +  -  +  + ]:         117943 :     if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids))
                                767                 :                :     {
                                768                 :                :         /* Ensure we have a modifiable copy */
 8246                           769                 :          43351 :         relids = bms_copy(relids);
                                770                 :                :         /* Remove old, add new */
                                771                 :          43351 :         relids = bms_del_member(relids, oldrelid);
  205 akorotkov@postgresql      772         [ +  + ]:          43351 :         if (!IS_SPECIAL_VARNO(newrelid))
                                773                 :           4963 :             relids = bms_add_member(relids, newrelid);
                                774                 :                :     }
 8246 tgl@sss.pgh.pa.us         775                 :         117943 :     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
 9305                           804                 :        1320823 : IncrementVarSublevelsUp_walker(Node *node,
                                805                 :                :                                IncrementVarSublevelsUp_context *context)
                                806                 :                : {
                                807         [ +  + ]:        1320823 :     if (node == NULL)
                                808                 :         421360 :         return false;
                                809         [ +  + ]:         899463 :     if (IsA(node, Var))
                                810                 :                :     {
                                811                 :         424421 :         Var        *var = (Var *) node;
                                812                 :                : 
                                813         [ +  + ]:         424421 :         if (var->varlevelsup >= context->min_sublevels_up)
                                814                 :           5374 :             var->varlevelsup += context->delta_sublevels_up;
 8128                           815                 :         424421 :         return false;           /* done here */
                                816                 :                :     }
 6662                           817         [ -  + ]:         475042 :     if (IsA(node, CurrentOfExpr))
                                818                 :                :     {
                                819                 :                :         /* this should not happen */
 6662 tgl@sss.pgh.pa.us         820         [ #  # ]:UBC           0 :         if (context->min_sublevels_up == 0)
                                821         [ #  # ]:              0 :             elog(ERROR, "cannot push down CurrentOfExpr");
                                822                 :              0 :         return false;
                                823                 :                :     }
 8128 tgl@sss.pgh.pa.us         824         [ +  + ]:CBC      475042 :     if (IsA(node, Aggref))
                                825                 :                :     {
                                826                 :           1339 :         Aggref     *agg = (Aggref *) node;
                                827                 :                : 
                                828         [ +  + ]:           1339 :         if (agg->agglevelsup >= context->min_sublevels_up)
                                829                 :             35 :             agg->agglevelsup += context->delta_sublevels_up;
                                830                 :                :         /* fall through to recurse into argument */
                                831                 :                :     }
 3766 andres@anarazel.de        832         [ +  + ]:         475042 :     if (IsA(node, GroupingFunc))
                                833                 :                :     {
 3759 bruce@momjian.us          834                 :             32 :         GroupingFunc *grp = (GroupingFunc *) node;
                                835                 :                : 
 3766 andres@anarazel.de        836         [ +  - ]:             32 :         if (grp->agglevelsup >= context->min_sublevels_up)
                                837                 :             32 :             grp->agglevelsup += context->delta_sublevels_up;
                                838                 :                :         /* fall through to recurse into argument */
                                839                 :                :     }
 6164 tgl@sss.pgh.pa.us         840         [ +  + ]:         475042 :     if (IsA(node, PlaceHolderVar))
                                841                 :                :     {
                                842                 :            452 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                                843                 :                : 
                                844         [ +  + ]:            452 :         if (phv->phlevelsup >= context->min_sublevels_up)
                                845                 :            271 :             phv->phlevelsup += context->delta_sublevels_up;
                                846                 :                :         /* fall through to recurse into argument */
                                847                 :                :     }
  233 dean.a.rasheed@gmail      848         [ +  + ]:         475042 :     if (IsA(node, ReturningExpr))
                                849                 :                :     {
                                850                 :             72 :         ReturningExpr *rexpr = (ReturningExpr *) node;
                                851                 :                : 
                                852         [ +  - ]:             72 :         if (rexpr->retlevelsup >= context->min_sublevels_up)
                                853                 :             72 :             rexpr->retlevelsup += context->delta_sublevels_up;
                                854                 :                :         /* fall through to recurse into argument */
                                855                 :                :     }
 6181 tgl@sss.pgh.pa.us         856         [ +  + ]:         475042 :     if (IsA(node, RangeTblEntry))
                                857                 :                :     {
                                858                 :          51207 :         RangeTblEntry *rte = (RangeTblEntry *) node;
                                859                 :                : 
                                860         [ +  + ]:          51207 :         if (rte->rtekind == RTE_CTE)
                                861                 :                :         {
                                862         [ +  + ]:           3159 :             if (rte->ctelevelsup >= context->min_sublevels_up)
                                863                 :           3144 :                 rte->ctelevelsup += context->delta_sublevels_up;
                                864                 :                :         }
                                865                 :          51207 :         return false;           /* allow range_table_walker to continue */
                                866                 :                :     }
 9125                           867         [ +  + ]:         423835 :     if (IsA(node, Query))
                                868                 :                :     {
                                869                 :                :         /* Recurse into subselects */
                                870                 :                :         bool        result;
                                871                 :                : 
                                872                 :           8663 :         context->min_sublevels_up++;
                                873                 :           8663 :         result = query_tree_walker((Query *) node,
                                874                 :                :                                    IncrementVarSublevelsUp_walker,
                                875                 :                :                                    context,
                                876                 :                :                                    QTW_EXAMINE_RTES_BEFORE);
                                877                 :           8663 :         context->min_sublevels_up--;
                                878                 :           8663 :         return result;
                                879                 :                :     }
  282 peter@eisentraut.org      880                 :         415172 :     return expression_tree_walker(node, IncrementVarSublevelsUp_walker, context);
                                881                 :                : }
                                882                 :                : 
                                883                 :                : void
 9125 tgl@sss.pgh.pa.us         884                 :          43650 : IncrementVarSublevelsUp(Node *node, int delta_sublevels_up,
                                885                 :                :                         int min_sublevels_up)
                                886                 :                : {
                                887                 :                :     IncrementVarSublevelsUp_context context;
                                888                 :                : 
                                889                 :          43650 :     context.delta_sublevels_up = delta_sublevels_up;
                                890                 :          43650 :     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                 :                :      */
 8268                           896                 :          43650 :     query_or_expression_tree_walker(node,
                                897                 :                :                                     IncrementVarSublevelsUp_walker,
                                898                 :                :                                     &context,
                                899                 :                :                                     QTW_EXAMINE_RTES_BEFORE);
 9125                           900                 :          43650 : }
                                901                 :                : 
                                902                 :                : /*
                                903                 :                :  * IncrementVarSublevelsUp_rtable -
                                904                 :                :  *  Same as IncrementVarSublevelsUp, but to be invoked on a range table.
                                905                 :                :  */
                                906                 :                : void
 6232 heikki.linnakangas@i      907                 :           2223 : IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up,
                                908                 :                :                                int min_sublevels_up)
                                909                 :                : {
                                910                 :                :     IncrementVarSublevelsUp_context context;
                                911                 :                : 
                                912                 :           2223 :     context.delta_sublevels_up = delta_sublevels_up;
                                913                 :           2223 :     context.min_sublevels_up = min_sublevels_up;
                                914                 :                : 
                                915                 :           2223 :     range_table_walker(rtable,
                                916                 :                :                        IncrementVarSublevelsUp_walker,
                                917                 :                :                        &context,
                                918                 :                :                        QTW_EXAMINE_RTES_BEFORE);
                                919                 :           2223 : }
                                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
  233 dean.a.rasheed@gmail      940                 :           1077 : SetVarReturningType_walker(Node *node, SetVarReturningType_context *context)
                                941                 :                : {
                                942         [ +  + ]:           1077 :     if (node == NULL)
                                943                 :            288 :         return false;
                                944         [ +  + ]:            789 :     if (IsA(node, Var))
                                945                 :                :     {
                                946                 :            489 :         Var        *var = (Var *) node;
                                947                 :                : 
                                948         [ +  + ]:            489 :         if (var->varno == context->result_relation &&
                                949         [ +  - ]:            459 :             var->varlevelsup == context->sublevels_up)
                                950                 :            459 :             var->varreturningtype = context->returning_type;
                                951                 :                : 
                                952                 :            489 :         return false;
                                953                 :                :     }
                                954                 :                : 
                                955         [ +  + ]:            300 :     if (IsA(node, Query))
                                956                 :                :     {
                                957                 :                :         /* Recurse into subselects */
                                958                 :                :         bool        result;
                                959                 :                : 
                                960                 :             24 :         context->sublevels_up++;
                                961                 :             24 :         result = query_tree_walker((Query *) node, SetVarReturningType_walker,
                                962                 :                :                                    context, 0);
                                963                 :             24 :         context->sublevels_up--;
                                964                 :             24 :         return result;
                                965                 :                :     }
                                966                 :            276 :     return expression_tree_walker(node, SetVarReturningType_walker, context);
                                967                 :                : }
                                968                 :                : 
                                969                 :                : static void
                                970                 :            585 : SetVarReturningType(Node *node, int result_relation, int sublevels_up,
                                971                 :                :                     VarReturningType returning_type)
                                972                 :                : {
                                973                 :                :     SetVarReturningType_context context;
                                974                 :                : 
                                975                 :            585 :     context.result_relation = result_relation;
                                976                 :            585 :     context.sublevels_up = sublevels_up;
                                977                 :            585 :     context.returning_type = returning_type;
                                978                 :                : 
                                979                 :                :     /* Expect to start with an expression */
                                980                 :            585 :     SetVarReturningType_walker(node, &context);
                                981                 :            585 : }
                                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
 9125 tgl@sss.pgh.pa.us         995                 :        1935639 : rangeTableEntry_used_walker(Node *node,
                                996                 :                :                             rangeTableEntry_used_context *context)
                                997                 :                : {
                                998         [ +  + ]:        1935639 :     if (node == NULL)
                                999                 :         360956 :         return false;
                               1000         [ +  + ]:        1574683 :     if (IsA(node, Var))
                               1001                 :                :     {
                               1002                 :         457483 :         Var        *var = (Var *) node;
                               1003                 :                : 
                               1004         [ +  + ]:         457483 :         if (var->varlevelsup == context->sublevels_up &&
  950                          1005   [ +  +  -  + ]:         725974 :             (var->varno == context->rt_index ||
                               1006                 :         287087 :              bms_is_member(context->rt_index, var->varnullingrels)))
 9305                          1007                 :         151800 :             return true;
                               1008                 :         305683 :         return false;
                               1009                 :                :     }
 6662                          1010         [ +  + ]:        1117200 :     if (IsA(node, CurrentOfExpr))
                               1011                 :                :     {
                               1012                 :              6 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
                               1013                 :                : 
                               1014         [ +  - ]:              6 :         if (context->sublevels_up == 0 &&
                               1015         [ -  + ]:              6 :             cexpr->cvarno == context->rt_index)
 6662 tgl@sss.pgh.pa.us        1016                 :UBC           0 :             return true;
 6662 tgl@sss.pgh.pa.us        1017                 :CBC           6 :         return false;
                               1018                 :                :     }
 9125                          1019         [ +  + ]:        1117194 :     if (IsA(node, RangeTblRef))
                               1020                 :                :     {
                               1021                 :          66944 :         RangeTblRef *rtr = (RangeTblRef *) node;
                               1022                 :                : 
                               1023         [ +  + ]:          66944 :         if (rtr->rtindex == context->rt_index &&
                               1024         [ +  + ]:          35141 :             context->sublevels_up == 0)
 9305                          1025                 :          33683 :             return true;
                               1026                 :                :         /* the subquery itself is visited separately */
 9125                          1027                 :          33261 :         return false;
                               1028                 :                :     }
 8579                          1029         [ +  + ]:        1050250 :     if (IsA(node, JoinExpr))
                               1030                 :                :     {
 8403 bruce@momjian.us         1031                 :          23169 :         JoinExpr   *j = (JoinExpr *) node;
                               1032                 :                : 
 8579 tgl@sss.pgh.pa.us        1033         [ +  + ]:          23169 :         if (j->rtindex == context->rt_index &&
                               1034         [ -  + ]:             39 :             context->sublevels_up == 0)
 8579 tgl@sss.pgh.pa.us        1035                 :UBC           0 :             return true;
                               1036                 :                :         /* fall through to examine children */
                               1037                 :                :     }
                               1038                 :                :     /* Shouldn't need to handle planner auxiliary nodes here */
 6164 tgl@sss.pgh.pa.us        1039         [ -  + ]:CBC     1050250 :     Assert(!IsA(node, PlaceHolderVar));
 5117                          1040         [ -  + ]:        1050250 :     Assert(!IsA(node, PlanRowMark));
 6232                          1041         [ -  + ]:        1050250 :     Assert(!IsA(node, SpecialJoinInfo));
 7158                          1042         [ -  + ]:        1050250 :     Assert(!IsA(node, AppendRelInfo));
 6164                          1043         [ -  + ]:        1050250 :     Assert(!IsA(node, PlaceHolderInfo));
 5420                          1044         [ -  + ]:        1050250 :     Assert(!IsA(node, MinMaxAggInfo));
                               1045                 :                : 
 9125                          1046         [ +  + ]:        1050250 :     if (IsA(node, Query))
                               1047                 :                :     {
                               1048                 :                :         /* Recurse into subselects */
                               1049                 :                :         bool        result;
                               1050                 :                : 
                               1051                 :           7821 :         context->sublevels_up++;
                               1052                 :           7821 :         result = query_tree_walker((Query *) node, rangeTableEntry_used_walker,
                               1053                 :                :                                    context, 0);
                               1054                 :           7821 :         context->sublevels_up--;
                               1055                 :           7821 :         return result;
                               1056                 :                :     }
  282 peter@eisentraut.org     1057                 :        1042429 :     return expression_tree_walker(node, rangeTableEntry_used_walker, context);
                               1058                 :                : }
                               1059                 :                : 
                               1060                 :                : bool
 9125 tgl@sss.pgh.pa.us        1061                 :         193235 : rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
                               1062                 :                : {
                               1063                 :                :     rangeTableEntry_used_context context;
                               1064                 :                : 
                               1065                 :         193235 :     context.rt_index = rt_index;
                               1066                 :         193235 :     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                 :                :      */
 8268                          1072                 :         193235 :     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 *
 9041                          1093                 :           1757 : getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
                               1094                 :                : {
                               1095                 :                :     Query      *selectquery;
                               1096                 :                :     RangeTblEntry *selectrte;
                               1097                 :                :     RangeTblRef *rtr;
                               1098                 :                : 
                               1099         [ +  + ]:           1757 :     if (subquery_ptr)
                               1100                 :            690 :         *subquery_ptr = NULL;
                               1101                 :                : 
                               1102         [ -  + ]:           1757 :     if (parsetree == NULL)
 9041 tgl@sss.pgh.pa.us        1103                 :UBC           0 :         return parsetree;
 9041 tgl@sss.pgh.pa.us        1104         [ +  + ]:CBC        1757 :     if (parsetree->commandType != CMD_INSERT)
                               1105                 :            775 :         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                 :                :      */
 7769 neilc@samurai.com        1113         [ +  - ]:            982 :     if (list_length(parsetree->rtable) >= 2 &&
 7266 bruce@momjian.us         1114         [ +  + ]:            982 :         strcmp(rt_fetch(PRS2_OLD_VARNO, parsetree->rtable)->eref->aliasname,
 5784 tgl@sss.pgh.pa.us        1115                 :            894 :                "old") == 0 &&
 7266 bruce@momjian.us         1116         [ +  - ]:            894 :         strcmp(rt_fetch(PRS2_NEW_VARNO, parsetree->rtable)->eref->aliasname,
                               1117                 :                :                "new") == 0)
 9041 tgl@sss.pgh.pa.us        1118                 :            894 :         return parsetree;
                               1119   [ +  -  -  + ]:             88 :     Assert(parsetree->jointree && IsA(parsetree->jointree, FromExpr));
 7769 neilc@samurai.com        1120         [ -  + ]:             88 :     if (list_length(parsetree->jointree->fromlist) != 1)
 8079 tgl@sss.pgh.pa.us        1121         [ #  # ]:UBC           0 :         elog(ERROR, "expected to find SELECT subquery");
 7773 neilc@samurai.com        1122                 :CBC          88 :     rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
  926 dean.a.rasheed@gmail     1123         [ -  + ]:             88 :     if (!IsA(rtr, RangeTblRef))
  926 dean.a.rasheed@gmail     1124         [ #  # ]:UBC           0 :         elog(ERROR, "expected to find SELECT subquery");
 9041 tgl@sss.pgh.pa.us        1125                 :CBC          88 :     selectrte = rt_fetch(rtr->rtindex, parsetree->rtable);
  926 dean.a.rasheed@gmail     1126         [ +  - ]:             88 :     if (!(selectrte->rtekind == RTE_SUBQUERY &&
                               1127         [ +  - ]:             88 :           selectrte->subquery &&
                               1128         [ +  - ]:             88 :           IsA(selectrte->subquery, Query) &&
                               1129         [ -  + ]:             88 :           selectrte->subquery->commandType == CMD_SELECT))
 8079 tgl@sss.pgh.pa.us        1130         [ #  # ]:UBC           0 :         elog(ERROR, "expected to find SELECT subquery");
  926 dean.a.rasheed@gmail     1131                 :CBC          88 :     selectquery = selectrte->subquery;
 7769 neilc@samurai.com        1132         [ +  - ]:             88 :     if (list_length(selectquery->rtable) >= 2 &&
 7266 bruce@momjian.us         1133         [ +  - ]:             88 :         strcmp(rt_fetch(PRS2_OLD_VARNO, selectquery->rtable)->eref->aliasname,
 5784 tgl@sss.pgh.pa.us        1134                 :             88 :                "old") == 0 &&
 7266 bruce@momjian.us         1135         [ +  - ]:             88 :         strcmp(rt_fetch(PRS2_NEW_VARNO, selectquery->rtable)->eref->aliasname,
                               1136                 :                :                "new") == 0)
                               1137                 :                :     {
 9041 tgl@sss.pgh.pa.us        1138         [ +  + ]:             88 :         if (subquery_ptr)
 8934 bruce@momjian.us         1139                 :             30 :             *subquery_ptr = &(selectrte->subquery);
 9041 tgl@sss.pgh.pa.us        1140                 :             88 :         return selectquery;
                               1141                 :                :     }
 8079 tgl@sss.pgh.pa.us        1142         [ #  # ]:UBC           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
10225 bruce@momjian.us         1151                 :CBC        1858 : AddQual(Query *parsetree, Node *qual)
                               1152                 :                : {
                               1153                 :                :     Node       *copy;
                               1154                 :                : 
10226                          1155         [ +  + ]:           1858 :     if (qual == NULL)
                               1156                 :            864 :         return;
                               1157                 :                : 
 8988 tgl@sss.pgh.pa.us        1158         [ -  + ]:            994 :     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                 :                :          */
 8988 tgl@sss.pgh.pa.us        1173   [ #  #  #  # ]:UBC           0 :         if (parsetree->utilityStmt && IsA(parsetree->utilityStmt, NotifyStmt))
 8765                          1174                 :              0 :             return;
                               1175                 :                :         else
 8079                          1176         [ #  # ]:              0 :             ereport(ERROR,
                               1177                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1178                 :                :                      errmsg("conditional utility statements are not implemented")));
                               1179                 :                :     }
                               1180                 :                : 
 8088 tgl@sss.pgh.pa.us        1181         [ -  + ]:CBC         994 :     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                 :                :          */
 8079 tgl@sss.pgh.pa.us        1188         [ #  # ]:UBC           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 */
 9707 JanWieck@Yahoo.com       1194                 :CBC         994 :     copy = copyObject(qual);
                               1195                 :                : 
 9108 tgl@sss.pgh.pa.us        1196                 :            994 :     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                 :                :      */
 4775                          1202         [ -  + ]:            994 :     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                 :                :      */
 7992                          1208         [ +  + ]:            994 :     if (!parsetree->hasSubLinks)
                               1209                 :            973 :         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
 8357                          1219                 :            222 : AddInvertedQual(Query *parsetree, Node *qual)
                               1220                 :                : {
                               1221                 :                :     BooleanTest *invqual;
                               1222                 :                : 
10226 bruce@momjian.us         1223         [ -  + ]:            222 :     if (qual == NULL)
10226 bruce@momjian.us         1224                 :UBC           0 :         return;
                               1225                 :                : 
                               1226                 :                :     /* Need not copy input qual, because AddQual will... */
 8357 tgl@sss.pgh.pa.us        1227                 :CBC         222 :     invqual = makeNode(BooleanTest);
 8304                          1228                 :            222 :     invqual->arg = (Expr *) qual;
 8357                          1229                 :            222 :     invqual->booltesttype = IS_NOT_TRUE;
 3849                          1230                 :            222 :     invqual->location = -1;
                               1231                 :                : 
 8357                          1232                 :            222 :     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 *
  950                          1243                 :           4069 : add_nulling_relids(Node *node,
                               1244                 :                :                    const Bitmapset *target_relids,
                               1245                 :                :                    const Bitmapset *added_relids)
                               1246                 :                : {
                               1247                 :                :     add_nulling_relids_context context;
                               1248                 :                : 
                               1249                 :           4069 :     context.target_relids = target_relids;
                               1250                 :           4069 :     context.added_relids = added_relids;
                               1251                 :           4069 :     context.sublevels_up = 0;
                               1252                 :           4069 :     return query_or_expression_tree_mutator(node,
                               1253                 :                :                                             add_nulling_relids_mutator,
                               1254                 :                :                                             &context,
                               1255                 :                :                                             0);
                               1256                 :                : }
                               1257                 :                : 
                               1258                 :                : static Node *
                               1259                 :          18144 : add_nulling_relids_mutator(Node *node,
                               1260                 :                :                            add_nulling_relids_context *context)
                               1261                 :                : {
                               1262         [ +  + ]:          18144 :     if (node == NULL)
                               1263                 :            546 :         return NULL;
                               1264         [ +  + ]:          17598 :     if (IsA(node, Var))
                               1265                 :                :     {
                               1266                 :           6756 :         Var        *var = (Var *) node;
                               1267                 :                : 
                               1268         [ +  + ]:           6756 :         if (var->varlevelsup == context->sublevels_up &&
  372                          1269   [ +  +  +  + ]:          13404 :             (context->target_relids == NULL ||
                               1270                 :           6651 :              bms_is_member(var->varno, context->target_relids)))
                               1271                 :                :         {
  950                          1272                 :           3676 :             Relids      newnullingrels = bms_union(var->varnullingrels,
                               1273                 :                :                                                    context->added_relids);
                               1274                 :                : 
                               1275                 :                :             /* Copy the Var ... */
                               1276                 :           3676 :             var = copyObject(var);
                               1277                 :                :             /* ... and replace the copy's varnullingrels field */
                               1278                 :           3676 :             var->varnullingrels = newnullingrels;
                               1279                 :           3676 :             return (Node *) var;
                               1280                 :                :         }
                               1281                 :                :         /* Otherwise fall through to copy the Var normally */
                               1282                 :                :     }
                               1283         [ +  + ]:          10842 :     else if (IsA(node, PlaceHolderVar))
                               1284                 :                :     {
                               1285                 :            409 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               1286                 :                : 
                               1287         [ +  - ]:            409 :         if (phv->phlevelsup == context->sublevels_up &&
  372                          1288   [ +  -  +  - ]:            818 :             (context->target_relids == NULL ||
                               1289                 :            409 :              bms_overlap(phv->phrels, context->target_relids)))
                               1290                 :                :         {
  950                          1291                 :            409 :             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                 :            409 :             phv = makeNode(PlaceHolderVar);
                               1301                 :            409 :             memcpy(phv, node, sizeof(PlaceHolderVar));
                               1302                 :                :             /* ... and replace the copy's phnullingrels field */
                               1303                 :            409 :             phv->phnullingrels = newnullingrels;
                               1304                 :            409 :             return (Node *) phv;
                               1305                 :                :         }
                               1306                 :                :         /* Otherwise fall through to copy the PlaceHolderVar normally */
                               1307                 :                :     }
                               1308         [ +  + ]:          10433 :     else if (IsA(node, Query))
                               1309                 :                :     {
                               1310                 :                :         /* Recurse into RTE or sublink subquery */
                               1311                 :                :         Query      *newnode;
                               1312                 :                : 
                               1313                 :             24 :         context->sublevels_up++;
                               1314                 :             24 :         newnode = query_tree_mutator((Query *) node,
                               1315                 :                :                                      add_nulling_relids_mutator,
                               1316                 :                :                                      context,
                               1317                 :                :                                      0);
                               1318                 :             24 :         context->sublevels_up--;
                               1319                 :             24 :         return (Node *) newnode;
                               1320                 :                :     }
  282 peter@eisentraut.org     1321                 :          13489 :     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 *
  950 tgl@sss.pgh.pa.us        1331                 :         190692 : remove_nulling_relids(Node *node,
                               1332                 :                :                       const Bitmapset *removable_relids,
                               1333                 :                :                       const Bitmapset *except_relids)
                               1334                 :                : {
                               1335                 :                :     remove_nulling_relids_context context;
                               1336                 :                : 
                               1337                 :         190692 :     context.removable_relids = removable_relids;
                               1338                 :         190692 :     context.except_relids = except_relids;
                               1339                 :         190692 :     context.sublevels_up = 0;
                               1340                 :         190692 :     return query_or_expression_tree_mutator(node,
                               1341                 :                :                                             remove_nulling_relids_mutator,
                               1342                 :                :                                             &context,
                               1343                 :                :                                             0);
                               1344                 :                : }
                               1345                 :                : 
                               1346                 :                : static Node *
                               1347                 :         323475 : remove_nulling_relids_mutator(Node *node,
                               1348                 :                :                               remove_nulling_relids_context *context)
                               1349                 :                : {
                               1350         [ +  + ]:         323475 :     if (node == NULL)
                               1351                 :          29604 :         return NULL;
                               1352         [ +  + ]:         293871 :     if (IsA(node, Var))
                               1353                 :                :     {
                               1354                 :         212328 :         Var        *var = (Var *) node;
                               1355                 :                : 
                               1356         [ +  + ]:         212328 :         if (var->varlevelsup == context->sublevels_up &&
                               1357   [ +  +  +  + ]:         421387 :             !bms_is_member(var->varno, context->except_relids) &&
                               1358                 :         210670 :             bms_overlap(var->varnullingrels, context->removable_relids))
                               1359                 :                :         {
                               1360                 :                :             /* Copy the Var ... */
                               1361                 :           7859 :             var = copyObject(var);
                               1362                 :                :             /* ... and replace the copy's varnullingrels field */
  919                          1363                 :           7859 :             var->varnullingrels = bms_difference(var->varnullingrels,
                               1364                 :                :                                                  context->removable_relids);
  950                          1365                 :           7859 :             return (Node *) var;
                               1366                 :                :         }
                               1367                 :                :         /* Otherwise fall through to copy the Var normally */
                               1368                 :                :     }
                               1369         [ +  + ]:          81543 :     else if (IsA(node, PlaceHolderVar))
                               1370                 :                :     {
                               1371                 :           2286 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
                               1372                 :                : 
                               1373         [ +  - ]:           2286 :         if (phv->phlevelsup == context->sublevels_up &&
                               1374         [ +  - ]:           2286 :             !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                 :           2286 :                 expression_tree_mutator(node,
                               1385                 :                :                                         remove_nulling_relids_mutator,
                               1386                 :                :                                         context);
                               1387                 :                :             /* ... and replace the copy's phnullingrels field */
  919                          1388                 :           2286 :             phv->phnullingrels = bms_difference(phv->phnullingrels,
                               1389                 :                :                                                 context->removable_relids);
                               1390                 :                :             /* We must also update phrels, if it contains a removable RTI */
  950                          1391                 :           2286 :             phv->phrels = bms_difference(phv->phrels,
                               1392                 :                :                                          context->removable_relids);
                               1393         [ -  + ]:           2286 :             Assert(!bms_is_empty(phv->phrels));
                               1394                 :           2286 :             return (Node *) phv;
                               1395                 :                :         }
                               1396                 :                :         /* Otherwise fall through to copy the PlaceHolderVar normally */
                               1397                 :                :     }
                               1398         [ +  + ]:          79257 :     else if (IsA(node, Query))
                               1399                 :                :     {
                               1400                 :                :         /* Recurse into RTE or sublink subquery */
                               1401                 :                :         Query      *newnode;
                               1402                 :                : 
                               1403                 :            129 :         context->sublevels_up++;
                               1404                 :            129 :         newnode = query_tree_mutator((Query *) node,
                               1405                 :                :                                      remove_nulling_relids_mutator,
                               1406                 :                :                                      context,
                               1407                 :                :                                      0);
                               1408                 :            129 :         context->sublevels_up--;
                               1409                 :            129 :         return (Node *) newnode;
                               1410                 :                :     }
  282 peter@eisentraut.org     1411                 :         283597 :     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 *
 5848 tgl@sss.pgh.pa.us        1438                 :         106794 : 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                 :         106794 :     context.callback = callback;
                               1447                 :         106794 :     context.callback_arg = callback_arg;
                               1448                 :         106794 :     context.target_varno = target_varno;
                               1449                 :         106794 :     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   [ +  +  +  + ]:         106794 :     if (node && IsA(node, Query))
                               1456                 :           2943 :         context.inserted_sublink = ((Query *) node)->hasSubLinks;
                               1457         [ +  + ]:         103851 :     else if (outer_hasSubLinks)
                               1458                 :         103724 :         context.inserted_sublink = *outer_hasSubLinks;
                               1459                 :                :     else
                               1460                 :            127 :         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                 :         106794 :     result = query_or_expression_tree_mutator(node,
                               1467                 :                :                                               replace_rte_variables_mutator,
                               1468                 :                :                                               &context,
                               1469                 :                :                                               0);
                               1470                 :                : 
                               1471         [ +  + ]:         106791 :     if (context.inserted_sublink)
                               1472                 :                :     {
                               1473   [ +  +  +  + ]:          12566 :         if (result && IsA(result, Query))
                               1474                 :             99 :             ((Query *) result)->hasSubLinks = true;
                               1475         [ +  - ]:          12467 :         else if (outer_hasSubLinks)
                               1476                 :          12467 :             *outer_hasSubLinks = true;
                               1477                 :                :         else
 5848 tgl@sss.pgh.pa.us        1478         [ #  # ]:UBC           0 :             elog(ERROR, "replace_rte_variables inserted a SubLink, but has noplace to record it");
                               1479                 :                :     }
                               1480                 :                : 
 5848 tgl@sss.pgh.pa.us        1481                 :CBC      106791 :     return result;
                               1482                 :                : }
                               1483                 :                : 
                               1484                 :                : Node *
                               1485                 :         484158 : replace_rte_variables_mutator(Node *node,
                               1486                 :                :                               replace_rte_variables_context *context)
                               1487                 :                : {
10226 bruce@momjian.us         1488         [ +  + ]:         484158 :     if (node == NULL)
 9472 tgl@sss.pgh.pa.us        1489                 :         145120 :         return NULL;
                               1490         [ +  + ]:         339038 :     if (IsA(node, Var))
                               1491                 :                :     {
                               1492                 :         133712 :         Var        *var = (Var *) node;
                               1493                 :                : 
 5848                          1494         [ +  + ]:         133712 :         if (var->varno == context->target_varno &&
                               1495         [ +  + ]:          66481 :             var->varlevelsup == context->sublevels_up)
                               1496                 :                :         {
                               1497                 :                :             /* Found a matching variable, make the substitution */
                               1498                 :                :             Node       *newnode;
                               1499                 :                : 
 2921 peter_e@gmx.net          1500                 :          62542 :             newnode = context->callback(var, context);
                               1501                 :                :             /* Detect if we are adding a sublink to query */
 5848 tgl@sss.pgh.pa.us        1502         [ +  + ]:          62542 :             if (!context->inserted_sublink)
                               1503                 :          55720 :                 context->inserted_sublink = checkExprHasSubLink(newnode);
                               1504                 :          62542 :             return newnode;
                               1505                 :                :         }
                               1506                 :                :         /* otherwise fall through to copy the var normally */
                               1507                 :                :     }
 6662                          1508         [ +  + ]:         205326 :     else if (IsA(node, CurrentOfExpr))
                               1509                 :                :     {
                               1510                 :              3 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
                               1511                 :                : 
 5848                          1512         [ +  - ]:              3 :         if (cexpr->cvarno == context->target_varno &&
 6662                          1513         [ +  - ]:              3 :             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         [ +  - ]:              3 :             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         [ +  + ]:         205323 :     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                 :                : 
 9102                          1533                 :           1681 :         context->sublevels_up++;
 7992                          1534                 :           1681 :         save_inserted_sublink = context->inserted_sublink;
 5848                          1535                 :           1681 :         context->inserted_sublink = ((Query *) node)->hasSubLinks;
 8268                          1536                 :           1681 :         newnode = query_tree_mutator((Query *) node,
                               1537                 :                :                                      replace_rte_variables_mutator,
                               1538                 :                :                                      context,
                               1539                 :                :                                      0);
 7992                          1540                 :           1681 :         newnode->hasSubLinks |= context->inserted_sublink;
                               1541                 :           1681 :         context->inserted_sublink = save_inserted_sublink;
 9102                          1542                 :           1681 :         context->sublevels_up--;
 9472                          1543                 :           1681 :         return (Node *) newnode;
                               1544                 :                :     }
  282 peter@eisentraut.org     1545                 :         274812 :     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 *
 4816 tgl@sss.pgh.pa.us        1583                 :          55500 : map_variable_attnos_mutator(Node *node,
                               1584                 :                :                             map_variable_attnos_context *context)
                               1585                 :                : {
                               1586         [ +  + ]:          55500 :     if (node == NULL)
                               1587                 :             86 :         return NULL;
                               1588         [ +  + ]:          55414 :     if (IsA(node, Var))
                               1589                 :                :     {
                               1590                 :          13084 :         Var        *var = (Var *) node;
                               1591                 :                : 
                               1592         [ +  + ]:          13084 :         if (var->varno == context->target_varno &&
                               1593         [ +  - ]:          12976 :             var->varlevelsup == context->sublevels_up)
                               1594                 :                :         {
                               1595                 :                :             /* Found a matching variable, make the substitution */
 4483 bruce@momjian.us         1596                 :          12976 :             Var        *newvar = (Var *) palloc(sizeof(Var));
                               1597                 :          12976 :             int         attno = var->varattno;
                               1598                 :                : 
 2885 tgl@sss.pgh.pa.us        1599                 :          12976 :             *newvar = *var;     /* initially copy all fields of the Var */
                               1600                 :                : 
 4816                          1601         [ +  + ]:          12976 :             if (attno > 0)
                               1602                 :                :             {
                               1603                 :                :                 /* user-defined column, replace attno */
 2089 michael@paquier.xyz      1604         [ +  - ]:          12814 :                 if (attno > context->attno_map->maplen ||
                               1605         [ -  + ]:          12814 :                     context->attno_map->attnums[attno - 1] == 0)
 4816 tgl@sss.pgh.pa.us        1606         [ #  # ]:UBC           0 :                     elog(ERROR, "unexpected varattno %d in expression to be mapped",
                               1607                 :                :                          attno);
 2067 tgl@sss.pgh.pa.us        1608                 :CBC       12814 :                 newvar->varattno = context->attno_map->attnums[attno - 1];
                               1609                 :                :                 /* If the syntactic referent is same RTE, fix it too */
                               1610         [ +  + ]:          12814 :                 if (newvar->varnosyn == context->target_varno)
                               1611                 :          12775 :                     newvar->varattnosyn = newvar->varattno;
                               1612                 :                :             }
 4816                          1613         [ +  + ]:            162 :             else if (attno == 0)
                               1614                 :                :             {
                               1615                 :                :                 /* whole-row variable, warn caller */
                               1616                 :             27 :                 *(context->found_whole_row) = true;
                               1617                 :                : 
                               1618                 :                :                 /* If the caller expects us to convert the Var, do so. */
 2885                          1619         [ +  + ]:             27 :                 if (OidIsValid(context->to_rowtype) &&
                               1620         [ +  - ]:             24 :                     context->to_rowtype != var->vartype)
                               1621                 :                :                 {
                               1622                 :                :                     ConvertRowtypeExpr *r;
                               1623                 :                : 
                               1624                 :                :                     /* This certainly won't work for a RECORD variable. */
 2956 rhaas@postgresql.org     1625         [ -  + ]:             24 :                     Assert(var->vartype != RECORDOID);
                               1626                 :                : 
                               1627                 :                :                     /* Var itself is changed to the requested type. */
 2885 tgl@sss.pgh.pa.us        1628                 :             24 :                     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                 :             24 :                     r = makeNode(ConvertRowtypeExpr);
                               1635                 :             24 :                     r->arg = (Expr *) newvar;
                               1636                 :             24 :                     r->resulttype = var->vartype;
                               1637                 :             24 :                     r->convertformat = COERCE_IMPLICIT_CAST;
                               1638                 :             24 :                     r->location = -1;
                               1639                 :                : 
                               1640                 :             24 :                     return (Node *) r;
                               1641                 :                :                 }
                               1642                 :                :             }
 4816                          1643                 :          12952 :             return (Node *) newvar;
                               1644                 :                :         }
                               1645                 :                :         /* otherwise fall through to copy the var normally */
                               1646                 :                :     }
 2886 rhaas@postgresql.org     1647         [ +  + ]:          42330 :     else if (IsA(node, ConvertRowtypeExpr))
                               1648                 :                :     {
                               1649                 :             24 :         ConvertRowtypeExpr *r = (ConvertRowtypeExpr *) node;
 2885 tgl@sss.pgh.pa.us        1650                 :             24 :         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         [ +  + ]:             24 :         if (IsA(var, Var) &&
                               1660         [ +  + ]:             18 :             var->varno == context->target_varno &&
                               1661         [ +  - ]:             15 :             var->varlevelsup == context->sublevels_up &&
                               1662         [ +  - ]:             15 :             var->varattno == 0 &&
                               1663         [ +  - ]:             15 :             OidIsValid(context->to_rowtype) &&
                               1664         [ +  - ]:             15 :             context->to_rowtype != var->vartype)
                               1665                 :                :         {
                               1666                 :                :             ConvertRowtypeExpr *newnode;
                               1667                 :             15 :             Var        *newvar = (Var *) palloc(sizeof(Var));
                               1668                 :                : 
                               1669                 :                :             /* whole-row variable, warn caller */
                               1670                 :             15 :             *(context->found_whole_row) = true;
                               1671                 :                : 
                               1672                 :             15 :             *newvar = *var;     /* initially copy all fields of the Var */
                               1673                 :                : 
                               1674                 :                :             /* This certainly won't work for a RECORD variable. */
                               1675         [ -  + ]:             15 :             Assert(var->vartype != RECORDOID);
                               1676                 :                : 
                               1677                 :                :             /* Var itself is changed to the requested type. */
                               1678                 :             15 :             newvar->vartype = context->to_rowtype;
                               1679                 :                : 
 2886 rhaas@postgresql.org     1680                 :             15 :             newnode = (ConvertRowtypeExpr *) palloc(sizeof(ConvertRowtypeExpr));
 2885 tgl@sss.pgh.pa.us        1681                 :             15 :             *newnode = *r;      /* initially copy all fields of the CRE */
                               1682                 :             15 :             newnode->arg = (Expr *) newvar;
                               1683                 :                : 
 2886 rhaas@postgresql.org     1684                 :             15 :             return (Node *) newnode;
                               1685                 :                :         }
                               1686                 :                :         /* otherwise fall through to process the expression normally */
                               1687                 :                :     }
 4816 tgl@sss.pgh.pa.us        1688         [ -  + ]:          42306 :     else if (IsA(node, Query))
                               1689                 :                :     {
                               1690                 :                :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
                               1691                 :                :         Query      *newnode;
                               1692                 :                : 
 4816 tgl@sss.pgh.pa.us        1693                 :UBC           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                 :                :     }
  282 peter@eisentraut.org     1701                 :CBC       42423 :     return expression_tree_mutator(node, map_variable_attnos_mutator, context);
                               1702                 :                : }
                               1703                 :                : 
                               1704                 :                : Node *
 4816 tgl@sss.pgh.pa.us        1705                 :           4618 : 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                 :           4618 :     context.target_varno = target_varno;
                               1713                 :           4618 :     context.sublevels_up = sublevels_up;
                               1714                 :           4618 :     context.attno_map = attno_map;
 2956 rhaas@postgresql.org     1715                 :           4618 :     context.to_rowtype = to_rowtype;
 4816 tgl@sss.pgh.pa.us        1716                 :           4618 :     context.found_whole_row = found_whole_row;
                               1717                 :                : 
                               1718                 :           4618 :     *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                 :           4618 :     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 *
 4685                          1774                 :           5589 : ReplaceVarsFromTargetList_callback(Var *var,
                               1775                 :                :                                    replace_rte_variables_context *context)
                               1776                 :                : {
                               1777                 :           5589 :     ReplaceVarsFromTargetList_context *rcon = (ReplaceVarsFromTargetList_context *) context->callback_arg;
                               1778                 :                :     Node       *newnode;
                               1779                 :                : 
  193 rguo@postgresql.org      1780                 :           5589 :     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         [ +  + ]:           5589 :     if (var->varlevelsup > 0)
                               1789                 :            129 :         IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
                               1790                 :                : 
                               1791                 :           5589 :     return newnode;
                               1792                 :                : }
                               1793                 :                : 
                               1794                 :                : Node *
                               1795                 :          62111 : 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                 :                : 
 5848 tgl@sss.pgh.pa.us        1804         [ +  + ]:          62111 :     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                 :                :          */
  193 rguo@postgresql.org      1826                 :            365 :         expandRTE(target_rte,
                               1827                 :                :                   var->varno, 0 /* not varlevelsup */ ,
                               1828                 :                :                   var->varreturningtype, var->location,
                               1829                 :            365 :                   (var->vartype != RECORDOID),
                               1830                 :                :                   &colnames, &fields);
 5848 tgl@sss.pgh.pa.us        1831                 :            365 :         rowexpr = makeNode(RowExpr);
                               1832                 :                :         /* the fields will be set below */
  193 rguo@postgresql.org      1833                 :            365 :         rowexpr->args = NIL;
 5848 tgl@sss.pgh.pa.us        1834                 :            365 :         rowexpr->row_typeid = var->vartype;
                               1835                 :            365 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
 1269                          1836         [ +  + ]:            365 :         rowexpr->colnames = (var->vartype == RECORDOID) ? colnames : NIL;
 5848                          1837                 :            365 :         rowexpr->location = var->location;
                               1838                 :                :         /* Adjust the generated per-field Vars... */
  193 rguo@postgresql.org      1839   [ +  -  +  +  :           1354 :         foreach(lc, fields)
                                              +  + ]
                               1840                 :                :         {
                               1841                 :            989 :             Node       *field = lfirst(lc);
                               1842                 :                : 
                               1843   [ +  -  +  - ]:            989 :             if (field && IsA(field, Var))
                               1844                 :            989 :                 field = ReplaceVarFromTargetList((Var *) field,
                               1845                 :                :                                                  target_rte,
                               1846                 :                :                                                  targetlist,
                               1847                 :                :                                                  result_relation,
                               1848                 :                :                                                  nomatch_option,
                               1849                 :                :                                                  nomatch_varno);
                               1850                 :            989 :             rowexpr->args = lappend(rowexpr->args, field);
                               1851                 :                :         }
                               1852                 :                : 
                               1853                 :                :         /* Wrap it in a ReturningExpr, if needed, per comments above */
  233 dean.a.rasheed@gmail     1854         [ +  + ]:            365 :         if (var->varreturningtype != VAR_RETURNING_DEFAULT)
                               1855                 :                :         {
                               1856                 :             39 :             ReturningExpr *rexpr = makeNode(ReturningExpr);
                               1857                 :                : 
  193 rguo@postgresql.org      1858                 :             39 :             rexpr->retlevelsup = 0;
  233 dean.a.rasheed@gmail     1859                 :             39 :             rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
                               1860                 :             39 :             rexpr->retexpr = (Expr *) rowexpr;
                               1861                 :                : 
                               1862                 :             39 :             return (Node *) rexpr;
                               1863                 :                :         }
                               1864                 :                : 
 5848 tgl@sss.pgh.pa.us        1865                 :            326 :         return (Node *) rowexpr;
                               1866                 :                :     }
                               1867                 :                : 
                               1868                 :                :     /* Normal case referencing one targetlist element */
  193 rguo@postgresql.org      1869                 :          61746 :     tle = get_tle_by_resno(targetlist, var->varattno);
                               1870                 :                : 
 5445 tgl@sss.pgh.pa.us        1871   [ +  +  -  + ]:          61746 :     if (tle == NULL || tle->resjunk)
                               1872                 :                :     {
                               1873                 :                :         /* Failed to find column in targetlist */
  193 rguo@postgresql.org      1874   [ -  +  +  - ]:            243 :         switch (nomatch_option)
                               1875                 :                :         {
 4685 tgl@sss.pgh.pa.us        1876                 :UBC           0 :             case REPLACEVARS_REPORT_ERROR:
                               1877                 :                :                 /* fall through, throw error below */
                               1878                 :              0 :                 break;
                               1879                 :                : 
 4685 tgl@sss.pgh.pa.us        1880                 :CBC         168 :             case REPLACEVARS_CHANGE_VARNO:
  324 peter@eisentraut.org     1881                 :            168 :                 var = copyObject(var);
  193 rguo@postgresql.org      1882                 :            168 :                 var->varno = nomatch_varno;
                               1883                 :            168 :                 var->varlevelsup = 0;
                               1884                 :                :                 /* we leave the syntactic referent alone */
 4685 tgl@sss.pgh.pa.us        1885                 :            168 :                 return (Node *) var;
                               1886                 :                : 
                               1887                 :             75 :             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                 :                : 
  220                          1896                 :             75 :                     get_typlenbyval(var->vartype, &vartyplen, &vartypbyval);
                               1897                 :             75 :                     return coerce_null_to_domain(var->vartype,
                               1898                 :                :                                                  var->vartypmod,
                               1899                 :                :                                                  var->varcollid,
                               1900                 :                :                                                  vartyplen,
                               1901                 :                :                                                  vartypbyval);
                               1902                 :                :                 }
                               1903                 :                :         }
 4685 tgl@sss.pgh.pa.us        1904         [ #  # ]:UBC           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 */
 3103 peter_e@gmx.net          1911                 :CBC       61503 :         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         [ -  + ]:          61503 :         if (contains_multiexpr_param((Node *) newnode, NULL))
 4098 tgl@sss.pgh.pa.us        1924         [ #  # ]:UBC           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 */
  233 dean.a.rasheed@gmail     1929         [ +  + ]:CBC       61503 :         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                 :                :              */
  193 rguo@postgresql.org      1935         [ -  + ]:            585 :             if (result_relation == 0)
  233 dean.a.rasheed@gmail     1936         [ #  # ]:UBC           0 :                 elog(ERROR, "variable returning old/new found outside RETURNING list");
                               1937                 :                : 
  193 rguo@postgresql.org      1938                 :CBC         585 :             SetVarReturningType((Node *) newnode, result_relation,
                               1939                 :                :                                 0, var->varreturningtype);
                               1940                 :                : 
                               1941                 :                :             /* Wrap it in a ReturningExpr, if needed, per comments above */
  233 dean.a.rasheed@gmail     1942         [ +  + ]:            585 :             if (!IsA(newnode, Var) ||
  193 rguo@postgresql.org      1943         [ +  + ]:            447 :                 ((Var *) newnode)->varno != result_relation ||
                               1944         [ -  + ]:            417 :                 ((Var *) newnode)->varlevelsup != 0)
                               1945                 :                :             {
  233 dean.a.rasheed@gmail     1946                 :            168 :                 ReturningExpr *rexpr = makeNode(ReturningExpr);
                               1947                 :                : 
  193 rguo@postgresql.org      1948                 :            168 :                 rexpr->retlevelsup = 0;
  233 dean.a.rasheed@gmail     1949                 :            168 :                 rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
                               1950                 :            168 :                 rexpr->retexpr = newnode;
                               1951                 :                : 
                               1952                 :            168 :                 newnode = (Expr *) rexpr;
                               1953                 :                :             }
                               1954                 :                :         }
                               1955                 :                : 
 3103 peter_e@gmx.net          1956                 :          61503 :         return (Node *) newnode;
                               1957                 :                :     }
                               1958                 :                : }
                               1959                 :                : 
                               1960                 :                : Node *
 4685 tgl@sss.pgh.pa.us        1961                 :           3752 : 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                 :                : 
 7399                          1972                 :           3752 :     context.target_rte = target_rte;
 9108                          1973                 :           3752 :     context.targetlist = targetlist;
  233 dean.a.rasheed@gmail     1974                 :           3752 :     context.result_relation = result_relation;
 4685 tgl@sss.pgh.pa.us        1975                 :           3752 :     context.nomatch_option = nomatch_option;
                               1976                 :           3752 :     context.nomatch_varno = nomatch_varno;
                               1977                 :                : 
 5848                          1978                 :           3752 :     return replace_rte_variables(node, target_varno, sublevels_up,
                               1979                 :                :                                  ReplaceVarsFromTargetList_callback,
                               1980                 :                :                                  &context,
                               1981                 :                :                                  outer_hasSubLinks);
                               1982                 :                : }
        

Generated by: LCOV version 2.4-beta