LCOV - differential code coverage report
Current view: top level - src/backend/rewrite - rewriteManip.c (source / functions) Coverage Total Hit UBC GBC GNC CBC DCB
Current: 7a15cff1f11193467898da1c1fabf06fd2caee04 vs 84a3778c79c2d28b4dc281d03ef2ab019b16483b Lines: 90.9 % 656 596 60 2 3 591 3
Current Date: 2025-12-15 18:36:29 -0500 Functions: 100.0 % 41 41 1 40
Baseline: lcov-20251216-010103-baseline Branches: 72.3 % 524 379 145 2 377
Baseline Date: 2025-12-15 13:30:48 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 3 3 3
(30,360] days: 98.7 % 75 74 1 74
(360..) days: 89.8 % 578 519 59 2 517
Function coverage date bins:
(30,360] days: 100.0 % 6 6 6
(360..) days: 100.0 % 35 35 1 34
Branch coverage date bins:
(30,360] days: 78.8 % 52 41 11 41
(360..) days: 71.6 % 472 338 134 2 336

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

Generated by: LCOV version 2.4-beta