LCOV - differential code coverage report
Current view: top level - src/backend/rewrite - rewriteManip.c (source / functions) Coverage Total Hit UBC GBC GIC GNC CBC DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 90.2 % 656 592 64 2 5 9 576 9
Current Date: 2026-05-05 10:23:31 +0900 Functions: 100.0 % 41 41 3 38 2
Baseline: lcov-20260505-025707-baseline Branches: 71.9 % 516 371 145 2 369
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 100.0 % 10 10 9 1
(360..) days: 90.1 % 646 582 64 2 5 575
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 39 39 1 38
Branch coverage date bins:
(360..) days: 71.9 % 516 371 145 2 369

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

Generated by: LCOV version 2.5.0-beta