LCOV - differential code coverage report
Current view: top level - src/backend/rewrite - rewriteManip.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 89.8 % 650 584 66 3 581 9
Current Date: 2026-07-25 19:08:27 +0900 Functions: 100.0 % 40 40 1 39 1
Baseline: lcov-20260725-baseline Branches: 71.4 % 514 367 147 367
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 3 3 3
(30,360] days: 100.0 % 10 10 10
(360..) days: 89.6 % 637 571 66 571
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 38 38 1 37
Branch coverage date bins:
(360..) days: 71.4 % 514 367 147 367

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

Generated by: LCOV version 2.0-1