LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - var.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 377 436 86.5 %
Date: 2025-01-18 04:15:08 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * var.c
       4             :  *    Var node manipulation routines
       5             :  *
       6             :  * Note: for most purposes, PlaceHolderVar is considered a Var too,
       7             :  * even if its contained expression is variable-free.  Also, CurrentOfExpr
       8             :  * is treated as a Var for purposes of determining whether an expression
       9             :  * contains variables.
      10             :  *
      11             :  *
      12             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
      13             :  * Portions Copyright (c) 1994, Regents of the University of California
      14             :  *
      15             :  *
      16             :  * IDENTIFICATION
      17             :  *    src/backend/optimizer/util/var.c
      18             :  *
      19             :  *-------------------------------------------------------------------------
      20             :  */
      21             : #include "postgres.h"
      22             : 
      23             : #include "access/sysattr.h"
      24             : #include "nodes/nodeFuncs.h"
      25             : #include "optimizer/clauses.h"
      26             : #include "optimizer/optimizer.h"
      27             : #include "optimizer/placeholder.h"
      28             : #include "optimizer/prep.h"
      29             : #include "parser/parsetree.h"
      30             : #include "rewrite/rewriteManip.h"
      31             : 
      32             : 
      33             : typedef struct
      34             : {
      35             :     Relids      varnos;
      36             :     PlannerInfo *root;
      37             :     int         sublevels_up;
      38             : } pull_varnos_context;
      39             : 
      40             : typedef struct
      41             : {
      42             :     Bitmapset  *varattnos;
      43             :     Index       varno;
      44             : } pull_varattnos_context;
      45             : 
      46             : typedef struct
      47             : {
      48             :     List       *vars;
      49             :     int         sublevels_up;
      50             : } pull_vars_context;
      51             : 
      52             : typedef struct
      53             : {
      54             :     int         var_location;
      55             :     int         sublevels_up;
      56             : } locate_var_of_level_context;
      57             : 
      58             : typedef struct
      59             : {
      60             :     List       *varlist;
      61             :     int         flags;
      62             : } pull_var_clause_context;
      63             : 
      64             : typedef struct
      65             : {
      66             :     PlannerInfo *root;          /* could be NULL! */
      67             :     Query      *query;          /* outer Query */
      68             :     int         sublevels_up;
      69             :     bool        possible_sublink;   /* could aliases include a SubLink? */
      70             :     bool        inserted_sublink;   /* have we inserted a SubLink? */
      71             : } flatten_join_alias_vars_context;
      72             : 
      73             : static bool pull_varnos_walker(Node *node,
      74             :                                pull_varnos_context *context);
      75             : static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context);
      76             : static bool pull_vars_walker(Node *node, pull_vars_context *context);
      77             : static bool contain_var_clause_walker(Node *node, void *context);
      78             : static bool contain_vars_of_level_walker(Node *node, int *sublevels_up);
      79             : static bool contain_vars_returning_old_or_new_walker(Node *node, void *context);
      80             : static bool locate_var_of_level_walker(Node *node,
      81             :                                        locate_var_of_level_context *context);
      82             : static bool pull_var_clause_walker(Node *node,
      83             :                                    pull_var_clause_context *context);
      84             : static Node *flatten_join_alias_vars_mutator(Node *node,
      85             :                                              flatten_join_alias_vars_context *context);
      86             : static Node *flatten_group_exprs_mutator(Node *node,
      87             :                                          flatten_join_alias_vars_context *context);
      88             : static Node *mark_nullable_by_grouping(PlannerInfo *root, Node *newnode,
      89             :                                        Var *oldvar);
      90             : static Node *add_nullingrels_if_needed(PlannerInfo *root, Node *newnode,
      91             :                                        Var *oldvar);
      92             : static bool is_standard_join_alias_expression(Node *newnode, Var *oldvar);
      93             : static void adjust_standard_join_alias_expression(Node *newnode, Var *oldvar);
      94             : static Relids alias_relid_set(Query *query, Relids relids);
      95             : 
      96             : 
      97             : /*
      98             :  * pull_varnos
      99             :  *      Create a set of all the distinct varnos present in a parsetree.
     100             :  *      Only varnos that reference level-zero rtable entries are considered.
     101             :  *
     102             :  * The result includes outer-join relids mentioned in Var.varnullingrels and
     103             :  * PlaceHolderVar.phnullingrels fields in the parsetree.
     104             :  *
     105             :  * "root" can be passed as NULL if it is not necessary to process
     106             :  * PlaceHolderVars.
     107             :  *
     108             :  * NOTE: this is used on not-yet-planned expressions.  It may therefore find
     109             :  * bare SubLinks, and if so it needs to recurse into them to look for uplevel
     110             :  * references to the desired rtable level!  But when we find a completed
     111             :  * SubPlan, we only need to look at the parameters passed to the subplan.
     112             :  */
     113             : Relids
     114     2836296 : pull_varnos(PlannerInfo *root, Node *node)
     115             : {
     116             :     pull_varnos_context context;
     117             : 
     118     2836296 :     context.varnos = NULL;
     119     2836296 :     context.root = root;
     120     2836296 :     context.sublevels_up = 0;
     121             : 
     122             :     /*
     123             :      * Must be prepared to start with a Query or a bare expression tree; if
     124             :      * it's a Query, we don't want to increment sublevels_up.
     125             :      */
     126     2836296 :     query_or_expression_tree_walker(node,
     127             :                                     pull_varnos_walker,
     128             :                                     &context,
     129             :                                     0);
     130             : 
     131     2836296 :     return context.varnos;
     132             : }
     133             : 
     134             : /*
     135             :  * pull_varnos_of_level
     136             :  *      Create a set of all the distinct varnos present in a parsetree.
     137             :  *      Only Vars of the specified level are considered.
     138             :  */
     139             : Relids
     140        5356 : pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
     141             : {
     142             :     pull_varnos_context context;
     143             : 
     144        5356 :     context.varnos = NULL;
     145        5356 :     context.root = root;
     146        5356 :     context.sublevels_up = levelsup;
     147             : 
     148             :     /*
     149             :      * Must be prepared to start with a Query or a bare expression tree; if
     150             :      * it's a Query, we don't want to increment sublevels_up.
     151             :      */
     152        5356 :     query_or_expression_tree_walker(node,
     153             :                                     pull_varnos_walker,
     154             :                                     &context,
     155             :                                     0);
     156             : 
     157        5356 :     return context.varnos;
     158             : }
     159             : 
     160             : static bool
     161     4807832 : pull_varnos_walker(Node *node, pull_varnos_context *context)
     162             : {
     163     4807832 :     if (node == NULL)
     164      111600 :         return false;
     165     4696232 :     if (IsA(node, Var))
     166             :     {
     167     2313748 :         Var        *var = (Var *) node;
     168             : 
     169     2313748 :         if (var->varlevelsup == context->sublevels_up)
     170             :         {
     171     2307592 :             context->varnos = bms_add_member(context->varnos, var->varno);
     172     2307592 :             context->varnos = bms_add_members(context->varnos,
     173     2307592 :                                               var->varnullingrels);
     174             :         }
     175     2313748 :         return false;
     176             :     }
     177     2382484 :     if (IsA(node, CurrentOfExpr))
     178             :     {
     179         800 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
     180             : 
     181         800 :         if (context->sublevels_up == 0)
     182         800 :             context->varnos = bms_add_member(context->varnos, cexpr->cvarno);
     183         800 :         return false;
     184             :     }
     185     2381684 :     if (IsA(node, PlaceHolderVar))
     186             :     {
     187        5376 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
     188             : 
     189             :         /*
     190             :          * If a PlaceHolderVar is not of the target query level, ignore it,
     191             :          * instead recursing into its expression to see if it contains any
     192             :          * vars that are of the target level.  We'll also do that when the
     193             :          * caller doesn't pass a "root" pointer.  (We probably shouldn't see
     194             :          * PlaceHolderVars at all in such cases, but if we do, this is a
     195             :          * reasonable behavior.)
     196             :          */
     197        5376 :         if (phv->phlevelsup == context->sublevels_up &&
     198        5376 :             context->root != NULL)
     199             :         {
     200             :             /*
     201             :              * Ideally, the PHV's contribution to context->varnos is its
     202             :              * ph_eval_at set.  However, this code can be invoked before
     203             :              * that's been computed.  If we cannot find a PlaceHolderInfo,
     204             :              * fall back to the conservative assumption that the PHV will be
     205             :              * evaluated at its syntactic level (phv->phrels).
     206             :              *
     207             :              * Another problem is that a PlaceHolderVar can appear in quals or
     208             :              * tlists that have been translated for use in a child appendrel.
     209             :              * Typically such a PHV is a parameter expression sourced by some
     210             :              * other relation, so that the translation from parent appendrel
     211             :              * to child doesn't change its phrels, and we should still take
     212             :              * ph_eval_at at face value.  But in corner cases, the PHV's
     213             :              * original phrels can include the parent appendrel itself, in
     214             :              * which case the translated PHV will have the child appendrel in
     215             :              * phrels, and we must translate ph_eval_at to match.
     216             :              */
     217        5376 :             PlaceHolderInfo *phinfo = NULL;
     218             : 
     219        5376 :             if (phv->phlevelsup == 0)
     220             :             {
     221        5280 :                 if (phv->phid < context->root->placeholder_array_size)
     222        4358 :                     phinfo = context->root->placeholder_array[phv->phid];
     223             :             }
     224        5376 :             if (phinfo == NULL)
     225             :             {
     226             :                 /* No PlaceHolderInfo yet, use phrels */
     227        1030 :                 context->varnos = bms_add_members(context->varnos,
     228        1030 :                                                   phv->phrels);
     229             :             }
     230        4346 :             else if (bms_equal(phv->phrels, phinfo->ph_var->phrels))
     231             :             {
     232             :                 /* Normal case: use ph_eval_at */
     233        3452 :                 context->varnos = bms_add_members(context->varnos,
     234        3452 :                                                   phinfo->ph_eval_at);
     235             :             }
     236             :             else
     237             :             {
     238             :                 /* Translated PlaceHolderVar: translate ph_eval_at to match */
     239             :                 Relids      newevalat,
     240             :                             delta;
     241             : 
     242             :                 /* remove what was removed from phv->phrels ... */
     243         894 :                 delta = bms_difference(phinfo->ph_var->phrels, phv->phrels);
     244         894 :                 newevalat = bms_difference(phinfo->ph_eval_at, delta);
     245             :                 /* ... then if that was in fact part of ph_eval_at ... */
     246         894 :                 if (!bms_equal(newevalat, phinfo->ph_eval_at))
     247             :                 {
     248             :                     /* ... add what was added */
     249         600 :                     delta = bms_difference(phv->phrels, phinfo->ph_var->phrels);
     250         600 :                     newevalat = bms_join(newevalat, delta);
     251             :                 }
     252         894 :                 context->varnos = bms_join(context->varnos,
     253             :                                            newevalat);
     254             :             }
     255             : 
     256             :             /*
     257             :              * In all three cases, include phnullingrels in the result.  We
     258             :              * don't worry about possibly needing to translate it, because
     259             :              * appendrels only translate varnos of baserels, not outer joins.
     260             :              */
     261       10752 :             context->varnos = bms_add_members(context->varnos,
     262        5376 :                                               phv->phnullingrels);
     263        5376 :             return false;       /* don't recurse into expression */
     264             :         }
     265             :     }
     266     2376308 :     else if (IsA(node, Query))
     267             :     {
     268             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
     269             :         bool        result;
     270             : 
     271        1630 :         context->sublevels_up++;
     272        1630 :         result = query_tree_walker((Query *) node, pull_varnos_walker,
     273             :                                    context, 0);
     274        1630 :         context->sublevels_up--;
     275        1630 :         return result;
     276             :     }
     277     2374678 :     return expression_tree_walker(node, pull_varnos_walker, context);
     278             : }
     279             : 
     280             : 
     281             : /*
     282             :  * pull_varattnos
     283             :  *      Find all the distinct attribute numbers present in an expression tree,
     284             :  *      and add them to the initial contents of *varattnos.
     285             :  *      Only Vars of the given varno and rtable level zero are considered.
     286             :  *
     287             :  * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
     288             :  * we can include system attributes (e.g., OID) in the bitmap representation.
     289             :  *
     290             :  * Currently, this does not support unplanned subqueries; that is not needed
     291             :  * for current uses.  It will handle already-planned SubPlan nodes, though,
     292             :  * looking into only the "testexpr" and the "args" list.  (The subplan cannot
     293             :  * contain any other references to Vars of the current level.)
     294             :  */
     295             : void
     296     1605300 : pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
     297             : {
     298             :     pull_varattnos_context context;
     299             : 
     300     1605300 :     context.varattnos = *varattnos;
     301     1605300 :     context.varno = varno;
     302             : 
     303     1605300 :     (void) pull_varattnos_walker(node, &context);
     304             : 
     305     1605300 :     *varattnos = context.varattnos;
     306     1605300 : }
     307             : 
     308             : static bool
     309     5335564 : pull_varattnos_walker(Node *node, pull_varattnos_context *context)
     310             : {
     311     5335564 :     if (node == NULL)
     312       73034 :         return false;
     313     5262530 :     if (IsA(node, Var))
     314             :     {
     315     3024330 :         Var        *var = (Var *) node;
     316             : 
     317     3024330 :         if (var->varno == context->varno && var->varlevelsup == 0)
     318     3023888 :             context->varattnos =
     319     3023888 :                 bms_add_member(context->varattnos,
     320     3023888 :                                var->varattno - FirstLowInvalidHeapAttributeNumber);
     321     3024330 :         return false;
     322             :     }
     323             : 
     324             :     /* Should not find an unplanned subquery */
     325             :     Assert(!IsA(node, Query));
     326             : 
     327     2238200 :     return expression_tree_walker(node, pull_varattnos_walker, context);
     328             : }
     329             : 
     330             : 
     331             : /*
     332             :  * pull_vars_of_level
     333             :  *      Create a list of all Vars (and PlaceHolderVars) referencing the
     334             :  *      specified query level in the given parsetree.
     335             :  *
     336             :  * Caution: the Vars are not copied, only linked into the list.
     337             :  */
     338             : List *
     339        9460 : pull_vars_of_level(Node *node, int levelsup)
     340             : {
     341             :     pull_vars_context context;
     342             : 
     343        9460 :     context.vars = NIL;
     344        9460 :     context.sublevels_up = levelsup;
     345             : 
     346             :     /*
     347             :      * Must be prepared to start with a Query or a bare expression tree; if
     348             :      * it's a Query, we don't want to increment sublevels_up.
     349             :      */
     350        9460 :     query_or_expression_tree_walker(node,
     351             :                                     pull_vars_walker,
     352             :                                     &context,
     353             :                                     0);
     354             : 
     355        9460 :     return context.vars;
     356             : }
     357             : 
     358             : static bool
     359      110840 : pull_vars_walker(Node *node, pull_vars_context *context)
     360             : {
     361      110840 :     if (node == NULL)
     362       13268 :         return false;
     363       97572 :     if (IsA(node, Var))
     364             :     {
     365       13470 :         Var        *var = (Var *) node;
     366             : 
     367       13470 :         if (var->varlevelsup == context->sublevels_up)
     368       10276 :             context->vars = lappend(context->vars, var);
     369       13470 :         return false;
     370             :     }
     371       84102 :     if (IsA(node, PlaceHolderVar))
     372             :     {
     373          84 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
     374             : 
     375          84 :         if (phv->phlevelsup == context->sublevels_up)
     376          84 :             context->vars = lappend(context->vars, phv);
     377             :         /* we don't want to look into the contained expression */
     378          84 :         return false;
     379             :     }
     380       84018 :     if (IsA(node, Query))
     381             :     {
     382             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
     383             :         bool        result;
     384             : 
     385         336 :         context->sublevels_up++;
     386         336 :         result = query_tree_walker((Query *) node, pull_vars_walker,
     387             :                                    context, 0);
     388         336 :         context->sublevels_up--;
     389         336 :         return result;
     390             :     }
     391       83682 :     return expression_tree_walker(node, pull_vars_walker, context);
     392             : }
     393             : 
     394             : 
     395             : /*
     396             :  * contain_var_clause
     397             :  *    Recursively scan a clause to discover whether it contains any Var nodes
     398             :  *    (of the current query level).
     399             :  *
     400             :  *    Returns true if any varnode found.
     401             :  *
     402             :  * Does not examine subqueries, therefore must only be used after reduction
     403             :  * of sublinks to subplans!
     404             :  */
     405             : bool
     406       20436 : contain_var_clause(Node *node)
     407             : {
     408       20436 :     return contain_var_clause_walker(node, NULL);
     409             : }
     410             : 
     411             : static bool
     412       26352 : contain_var_clause_walker(Node *node, void *context)
     413             : {
     414       26352 :     if (node == NULL)
     415         118 :         return false;
     416       26234 :     if (IsA(node, Var))
     417             :     {
     418        2252 :         if (((Var *) node)->varlevelsup == 0)
     419        2252 :             return true;        /* abort the tree traversal and return true */
     420           0 :         return false;
     421             :     }
     422       23982 :     if (IsA(node, CurrentOfExpr))
     423           0 :         return true;
     424       23982 :     if (IsA(node, PlaceHolderVar))
     425             :     {
     426          12 :         if (((PlaceHolderVar *) node)->phlevelsup == 0)
     427          12 :             return true;        /* abort the tree traversal and return true */
     428             :         /* else fall through to check the contained expr */
     429             :     }
     430       23970 :     return expression_tree_walker(node, contain_var_clause_walker, context);
     431             : }
     432             : 
     433             : 
     434             : /*
     435             :  * contain_vars_of_level
     436             :  *    Recursively scan a clause to discover whether it contains any Var nodes
     437             :  *    of the specified query level.
     438             :  *
     439             :  *    Returns true if any such Var found.
     440             :  *
     441             :  * Will recurse into sublinks.  Also, may be invoked directly on a Query.
     442             :  */
     443             : bool
     444      147390 : contain_vars_of_level(Node *node, int levelsup)
     445             : {
     446      147390 :     int         sublevels_up = levelsup;
     447             : 
     448      147390 :     return query_or_expression_tree_walker(node,
     449             :                                            contain_vars_of_level_walker,
     450             :                                            &sublevels_up,
     451             :                                            0);
     452             : }
     453             : 
     454             : static bool
     455      458784 : contain_vars_of_level_walker(Node *node, int *sublevels_up)
     456             : {
     457      458784 :     if (node == NULL)
     458       82448 :         return false;
     459      376336 :     if (IsA(node, Var))
     460             :     {
     461       63090 :         if (((Var *) node)->varlevelsup == *sublevels_up)
     462       41296 :             return true;        /* abort tree traversal and return true */
     463       21794 :         return false;
     464             :     }
     465      313246 :     if (IsA(node, CurrentOfExpr))
     466             :     {
     467         184 :         if (*sublevels_up == 0)
     468         184 :             return true;
     469           0 :         return false;
     470             :     }
     471      313062 :     if (IsA(node, PlaceHolderVar))
     472             :     {
     473          72 :         if (((PlaceHolderVar *) node)->phlevelsup == *sublevels_up)
     474          72 :             return true;        /* abort the tree traversal and return true */
     475             :         /* else fall through to check the contained expr */
     476             :     }
     477      312990 :     if (IsA(node, Query))
     478             :     {
     479             :         /* Recurse into subselects */
     480             :         bool        result;
     481             : 
     482         598 :         (*sublevels_up)++;
     483         598 :         result = query_tree_walker((Query *) node,
     484             :                                    contain_vars_of_level_walker,
     485             :                                    sublevels_up,
     486             :                                    0);
     487         598 :         (*sublevels_up)--;
     488         598 :         return result;
     489             :     }
     490      312392 :     return expression_tree_walker(node,
     491             :                                   contain_vars_of_level_walker,
     492             :                                   sublevels_up);
     493             : }
     494             : 
     495             : 
     496             : /*
     497             :  * contain_vars_returning_old_or_new
     498             :  *    Recursively scan a clause to discover whether it contains any Var nodes
     499             :  *    (of the current query level) whose varreturningtype is VAR_RETURNING_OLD
     500             :  *    or VAR_RETURNING_NEW.
     501             :  *
     502             :  *    Returns true if any found.
     503             :  *
     504             :  * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten,
     505             :  * we still regard this as a clause that returns OLD/NEW values.
     506             :  *
     507             :  * Does not examine subqueries, therefore must only be used after reduction
     508             :  * of sublinks to subplans!
     509             :  */
     510             : bool
     511         386 : contain_vars_returning_old_or_new(Node *node)
     512             : {
     513         386 :     return contain_vars_returning_old_or_new_walker(node, NULL);
     514             : }
     515             : 
     516             : static bool
     517        1210 : contain_vars_returning_old_or_new_walker(Node *node, void *context)
     518             : {
     519        1210 :     if (node == NULL)
     520         270 :         return false;
     521         940 :     if (IsA(node, Var))
     522             :     {
     523         402 :         if (((Var *) node)->varlevelsup == 0 &&
     524         402 :             ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT)
     525          14 :             return true;        /* abort the tree traversal and return true */
     526         388 :         return false;
     527             :     }
     528         538 :     if (IsA(node, ReturningExpr))
     529             :     {
     530           0 :         if (((ReturningExpr *) node)->retlevelsup == 0)
     531           0 :             return true;        /* abort the tree traversal and return true */
     532           0 :         return false;
     533             :     }
     534         538 :     return expression_tree_walker(node, contain_vars_returning_old_or_new_walker,
     535             :                                   context);
     536             : }
     537             : 
     538             : 
     539             : /*
     540             :  * locate_var_of_level
     541             :  *    Find the parse location of any Var of the specified query level.
     542             :  *
     543             :  * Returns -1 if no such Var is in the querytree, or if they all have
     544             :  * unknown parse location.  (The former case is probably caller error,
     545             :  * but we don't bother to distinguish it from the latter case.)
     546             :  *
     547             :  * Will recurse into sublinks.  Also, may be invoked directly on a Query.
     548             :  *
     549             :  * Note: it might seem appropriate to merge this functionality into
     550             :  * contain_vars_of_level, but that would complicate that function's API.
     551             :  * Currently, the only uses of this function are for error reporting,
     552             :  * and so shaving cycles probably isn't very important.
     553             :  */
     554             : int
     555          12 : locate_var_of_level(Node *node, int levelsup)
     556             : {
     557             :     locate_var_of_level_context context;
     558             : 
     559          12 :     context.var_location = -1;  /* in case we find nothing */
     560          12 :     context.sublevels_up = levelsup;
     561             : 
     562          12 :     (void) query_or_expression_tree_walker(node,
     563             :                                            locate_var_of_level_walker,
     564             :                                            &context,
     565             :                                            0);
     566             : 
     567          12 :     return context.var_location;
     568             : }
     569             : 
     570             : static bool
     571          30 : locate_var_of_level_walker(Node *node,
     572             :                            locate_var_of_level_context *context)
     573             : {
     574          30 :     if (node == NULL)
     575           0 :         return false;
     576          30 :     if (IsA(node, Var))
     577             :     {
     578          12 :         Var        *var = (Var *) node;
     579             : 
     580          12 :         if (var->varlevelsup == context->sublevels_up &&
     581          12 :             var->location >= 0)
     582             :         {
     583          12 :             context->var_location = var->location;
     584          12 :             return true;        /* abort tree traversal and return true */
     585             :         }
     586           0 :         return false;
     587             :     }
     588          18 :     if (IsA(node, CurrentOfExpr))
     589             :     {
     590             :         /* since CurrentOfExpr doesn't carry location, nothing we can do */
     591           0 :         return false;
     592             :     }
     593             :     /* No extra code needed for PlaceHolderVar; just look in contained expr */
     594          18 :     if (IsA(node, Query))
     595             :     {
     596             :         /* Recurse into subselects */
     597             :         bool        result;
     598             : 
     599           0 :         context->sublevels_up++;
     600           0 :         result = query_tree_walker((Query *) node,
     601             :                                    locate_var_of_level_walker,
     602             :                                    context,
     603             :                                    0);
     604           0 :         context->sublevels_up--;
     605           0 :         return result;
     606             :     }
     607          18 :     return expression_tree_walker(node,
     608             :                                   locate_var_of_level_walker,
     609             :                                   context);
     610             : }
     611             : 
     612             : 
     613             : /*
     614             :  * pull_var_clause
     615             :  *    Recursively pulls all Var nodes from an expression clause.
     616             :  *
     617             :  *    Aggrefs are handled according to these bits in 'flags':
     618             :  *      PVC_INCLUDE_AGGREGATES      include Aggrefs in output list
     619             :  *      PVC_RECURSE_AGGREGATES      recurse into Aggref arguments
     620             :  *      neither flag                throw error if Aggref found
     621             :  *    Vars within an Aggref's expression are included in the result only
     622             :  *    when PVC_RECURSE_AGGREGATES is specified.
     623             :  *
     624             :  *    WindowFuncs are handled according to these bits in 'flags':
     625             :  *      PVC_INCLUDE_WINDOWFUNCS     include WindowFuncs in output list
     626             :  *      PVC_RECURSE_WINDOWFUNCS     recurse into WindowFunc arguments
     627             :  *      neither flag                throw error if WindowFunc found
     628             :  *    Vars within a WindowFunc's expression are included in the result only
     629             :  *    when PVC_RECURSE_WINDOWFUNCS is specified.
     630             :  *
     631             :  *    PlaceHolderVars are handled according to these bits in 'flags':
     632             :  *      PVC_INCLUDE_PLACEHOLDERS    include PlaceHolderVars in output list
     633             :  *      PVC_RECURSE_PLACEHOLDERS    recurse into PlaceHolderVar arguments
     634             :  *      neither flag                throw error if PlaceHolderVar found
     635             :  *    Vars within a PHV's expression are included in the result only
     636             :  *    when PVC_RECURSE_PLACEHOLDERS is specified.
     637             :  *
     638             :  *    GroupingFuncs are treated exactly like Aggrefs, and so do not need
     639             :  *    their own flag bits.
     640             :  *
     641             :  *    CurrentOfExpr nodes are ignored in all cases.
     642             :  *
     643             :  *    Upper-level vars (with varlevelsup > 0) should not be seen here,
     644             :  *    likewise for upper-level Aggrefs and PlaceHolderVars.
     645             :  *
     646             :  *    Returns list of nodes found.  Note the nodes themselves are not
     647             :  *    copied, only referenced.
     648             :  *
     649             :  * Does not examine subqueries, therefore must only be used after reduction
     650             :  * of sublinks to subplans!
     651             :  */
     652             : List *
     653      661040 : pull_var_clause(Node *node, int flags)
     654             : {
     655             :     pull_var_clause_context context;
     656             : 
     657             :     /* Assert that caller has not specified inconsistent flags */
     658             :     Assert((flags & (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES))
     659             :            != (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES));
     660             :     Assert((flags & (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS))
     661             :            != (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS));
     662             :     Assert((flags & (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS))
     663             :            != (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS));
     664             : 
     665      661040 :     context.varlist = NIL;
     666      661040 :     context.flags = flags;
     667             : 
     668      661040 :     pull_var_clause_walker(node, &context);
     669      661040 :     return context.varlist;
     670             : }
     671             : 
     672             : static bool
     673     4017710 : pull_var_clause_walker(Node *node, pull_var_clause_context *context)
     674             : {
     675     4017710 :     if (node == NULL)
     676      167632 :         return false;
     677     3850078 :     if (IsA(node, Var))
     678             :     {
     679     1486360 :         if (((Var *) node)->varlevelsup != 0)
     680           0 :             elog(ERROR, "Upper-level Var found where not expected");
     681     1486360 :         context->varlist = lappend(context->varlist, node);
     682     1486360 :         return false;
     683             :     }
     684     2363718 :     else if (IsA(node, Aggref))
     685             :     {
     686       88522 :         if (((Aggref *) node)->agglevelsup != 0)
     687           0 :             elog(ERROR, "Upper-level Aggref found where not expected");
     688       88522 :         if (context->flags & PVC_INCLUDE_AGGREGATES)
     689             :         {
     690        4798 :             context->varlist = lappend(context->varlist, node);
     691             :             /* we do NOT descend into the contained expression */
     692        4798 :             return false;
     693             :         }
     694       83724 :         else if (context->flags & PVC_RECURSE_AGGREGATES)
     695             :         {
     696             :             /* fall through to recurse into the aggregate's arguments */
     697             :         }
     698             :         else
     699           0 :             elog(ERROR, "Aggref found where not expected");
     700             :     }
     701     2275196 :     else if (IsA(node, GroupingFunc))
     702             :     {
     703         646 :         if (((GroupingFunc *) node)->agglevelsup != 0)
     704           0 :             elog(ERROR, "Upper-level GROUPING found where not expected");
     705         646 :         if (context->flags & PVC_INCLUDE_AGGREGATES)
     706             :         {
     707           4 :             context->varlist = lappend(context->varlist, node);
     708             :             /* we do NOT descend into the contained expression */
     709           4 :             return false;
     710             :         }
     711         642 :         else if (context->flags & PVC_RECURSE_AGGREGATES)
     712             :         {
     713             :             /* fall through to recurse into the GroupingFunc's arguments */
     714             :         }
     715             :         else
     716           0 :             elog(ERROR, "GROUPING found where not expected");
     717             :     }
     718     2274550 :     else if (IsA(node, WindowFunc))
     719             :     {
     720             :         /* WindowFuncs have no levelsup field to check ... */
     721        6496 :         if (context->flags & PVC_INCLUDE_WINDOWFUNCS)
     722             :         {
     723          12 :             context->varlist = lappend(context->varlist, node);
     724             :             /* we do NOT descend into the contained expressions */
     725          12 :             return false;
     726             :         }
     727        6484 :         else if (context->flags & PVC_RECURSE_WINDOWFUNCS)
     728             :         {
     729             :             /* fall through to recurse into the windowfunc's arguments */
     730             :         }
     731             :         else
     732           0 :             elog(ERROR, "WindowFunc found where not expected");
     733             :     }
     734     2268054 :     else if (IsA(node, PlaceHolderVar))
     735             :     {
     736        3152 :         if (((PlaceHolderVar *) node)->phlevelsup != 0)
     737           0 :             elog(ERROR, "Upper-level PlaceHolderVar found where not expected");
     738        3152 :         if (context->flags & PVC_INCLUDE_PLACEHOLDERS)
     739             :         {
     740        2718 :             context->varlist = lappend(context->varlist, node);
     741             :             /* we do NOT descend into the contained expression */
     742        2718 :             return false;
     743             :         }
     744         434 :         else if (context->flags & PVC_RECURSE_PLACEHOLDERS)
     745             :         {
     746             :             /* fall through to recurse into the placeholder's expression */
     747             :         }
     748             :         else
     749           0 :             elog(ERROR, "PlaceHolderVar found where not expected");
     750             :     }
     751     2356186 :     return expression_tree_walker(node, pull_var_clause_walker, context);
     752             : }
     753             : 
     754             : 
     755             : /*
     756             :  * flatten_join_alias_vars
     757             :  *    Replace Vars that reference JOIN outputs with references to the original
     758             :  *    relation variables instead.  This allows quals involving such vars to be
     759             :  *    pushed down.  Whole-row Vars that reference JOIN relations are expanded
     760             :  *    into RowExpr constructs that name the individual output Vars.  This
     761             :  *    is necessary since we will not scan the JOIN as a base relation, which
     762             :  *    is the only way that the executor can directly handle whole-row Vars.
     763             :  *
     764             :  * This also adjusts relid sets found in some expression node types to
     765             :  * substitute the contained base+OJ rels for any join relid.
     766             :  *
     767             :  * If a JOIN contains sub-selects that have been flattened, its join alias
     768             :  * entries might now be arbitrary expressions, not just Vars.  This affects
     769             :  * this function in two important ways.  First, we might find ourselves
     770             :  * inserting SubLink expressions into subqueries, and we must make sure that
     771             :  * their Query.hasSubLinks fields get set to true if so.  If there are any
     772             :  * SubLinks in the join alias lists, the outer Query should already have
     773             :  * hasSubLinks = true, so this is only relevant to un-flattened subqueries.
     774             :  * Second, we have to preserve any varnullingrels info attached to the
     775             :  * alias Vars we're replacing.  If the replacement expression is a Var or
     776             :  * PlaceHolderVar or constructed from those, we can just add the
     777             :  * varnullingrels bits to the existing nullingrels field(s); otherwise
     778             :  * we have to add a PlaceHolderVar wrapper.
     779             :  *
     780             :  * NOTE: this is also used by the parser, to expand join alias Vars before
     781             :  * checking GROUP BY validity.  For that use-case, root will be NULL, which
     782             :  * is why we have to pass the Query separately.  We need the root itself only
     783             :  * for making PlaceHolderVars.  We can avoid making PlaceHolderVars in the
     784             :  * parser's usage because it won't be dealing with arbitrary expressions:
     785             :  * so long as adjust_standard_join_alias_expression can handle everything
     786             :  * the parser would make as a join alias expression, we're OK.
     787             :  */
     788             : Node *
     789      205968 : flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
     790             : {
     791             :     flatten_join_alias_vars_context context;
     792             : 
     793             :     /*
     794             :      * We do not expect this to be applied to the whole Query, only to
     795             :      * expressions or LATERAL subqueries.  Hence, if the top node is a Query,
     796             :      * it's okay to immediately increment sublevels_up.
     797             :      */
     798             :     Assert(node != (Node *) query);
     799             : 
     800      205968 :     context.root = root;
     801      205968 :     context.query = query;
     802      205968 :     context.sublevels_up = 0;
     803             :     /* flag whether join aliases could possibly contain SubLinks */
     804      205968 :     context.possible_sublink = query->hasSubLinks;
     805             :     /* if hasSubLinks is already true, no need to work hard */
     806      205968 :     context.inserted_sublink = query->hasSubLinks;
     807             : 
     808      205968 :     return flatten_join_alias_vars_mutator(node, &context);
     809             : }
     810             : 
     811             : static Node *
     812     2808802 : flatten_join_alias_vars_mutator(Node *node,
     813             :                                 flatten_join_alias_vars_context *context)
     814             : {
     815     2808802 :     if (node == NULL)
     816      247266 :         return NULL;
     817     2561536 :     if (IsA(node, Var))
     818             :     {
     819      778684 :         Var        *var = (Var *) node;
     820             :         RangeTblEntry *rte;
     821             :         Node       *newvar;
     822             : 
     823             :         /* No change unless Var belongs to a JOIN of the target level */
     824      778684 :         if (var->varlevelsup != context->sublevels_up)
     825       45556 :             return node;        /* no need to copy, really */
     826      733128 :         rte = rt_fetch(var->varno, context->query->rtable);
     827      733128 :         if (rte->rtekind != RTE_JOIN)
     828      732642 :             return node;
     829         486 :         if (var->varattno == InvalidAttrNumber)
     830             :         {
     831             :             /* Must expand whole-row reference */
     832             :             RowExpr    *rowexpr;
     833           6 :             List       *fields = NIL;
     834           6 :             List       *colnames = NIL;
     835             :             ListCell   *lv;
     836             :             ListCell   *ln;
     837             : 
     838             :             Assert(list_length(rte->joinaliasvars) == list_length(rte->eref->colnames));
     839          48 :             forboth(lv, rte->joinaliasvars, ln, rte->eref->colnames)
     840             :             {
     841          42 :                 newvar = (Node *) lfirst(lv);
     842             :                 /* Ignore dropped columns */
     843          42 :                 if (newvar == NULL)
     844           0 :                     continue;
     845          42 :                 newvar = copyObject(newvar);
     846             : 
     847             :                 /*
     848             :                  * If we are expanding an alias carried down from an upper
     849             :                  * query, must adjust its varlevelsup fields.
     850             :                  */
     851          42 :                 if (context->sublevels_up != 0)
     852           0 :                     IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
     853             :                 /* Preserve original Var's location, if possible */
     854          42 :                 if (IsA(newvar, Var))
     855          42 :                     ((Var *) newvar)->location = var->location;
     856             :                 /* Recurse in case join input is itself a join */
     857             :                 /* (also takes care of setting inserted_sublink if needed) */
     858          42 :                 newvar = flatten_join_alias_vars_mutator(newvar, context);
     859          42 :                 fields = lappend(fields, newvar);
     860             :                 /* We need the names of non-dropped columns, too */
     861          42 :                 colnames = lappend(colnames, copyObject((Node *) lfirst(ln)));
     862             :             }
     863           6 :             rowexpr = makeNode(RowExpr);
     864           6 :             rowexpr->args = fields;
     865           6 :             rowexpr->row_typeid = var->vartype;
     866           6 :             rowexpr->row_format = COERCE_IMPLICIT_CAST;
     867             :             /* vartype will always be RECORDOID, so we always need colnames */
     868           6 :             rowexpr->colnames = colnames;
     869           6 :             rowexpr->location = var->location;
     870             : 
     871             :             /* Lastly, add any varnullingrels to the replacement expression */
     872           6 :             return add_nullingrels_if_needed(context->root, (Node *) rowexpr,
     873             :                                              var);
     874             :         }
     875             : 
     876             :         /* Expand join alias reference */
     877             :         Assert(var->varattno > 0);
     878         480 :         newvar = (Node *) list_nth(rte->joinaliasvars, var->varattno - 1);
     879             :         Assert(newvar != NULL);
     880         480 :         newvar = copyObject(newvar);
     881             : 
     882             :         /*
     883             :          * If we are expanding an alias carried down from an upper query, must
     884             :          * adjust its varlevelsup fields.
     885             :          */
     886         480 :         if (context->sublevels_up != 0)
     887           0 :             IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
     888             : 
     889             :         /* Preserve original Var's location, if possible */
     890         480 :         if (IsA(newvar, Var))
     891           0 :             ((Var *) newvar)->location = var->location;
     892             : 
     893             :         /* Recurse in case join input is itself a join */
     894         480 :         newvar = flatten_join_alias_vars_mutator(newvar, context);
     895             : 
     896             :         /* Detect if we are adding a sublink to query */
     897         480 :         if (context->possible_sublink && !context->inserted_sublink)
     898           0 :             context->inserted_sublink = checkExprHasSubLink(newvar);
     899             : 
     900             :         /* Lastly, add any varnullingrels to the replacement expression */
     901         480 :         return add_nullingrels_if_needed(context->root, newvar, var);
     902             :     }
     903     1782852 :     if (IsA(node, PlaceHolderVar))
     904             :     {
     905             :         /* Copy the PlaceHolderVar node with correct mutation of subnodes */
     906             :         PlaceHolderVar *phv;
     907             : 
     908        1834 :         phv = (PlaceHolderVar *) expression_tree_mutator(node,
     909             :                                                          flatten_join_alias_vars_mutator,
     910             :                                                          context);
     911             :         /* now fix PlaceHolderVar's relid sets */
     912        1834 :         if (phv->phlevelsup == context->sublevels_up)
     913             :         {
     914        1738 :             phv->phrels = alias_relid_set(context->query,
     915             :                                           phv->phrels);
     916             :             /* we *don't* change phnullingrels */
     917             :         }
     918        1834 :         return (Node *) phv;
     919             :     }
     920             : 
     921     1781018 :     if (IsA(node, Query))
     922             :     {
     923             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
     924             :         Query      *newnode;
     925             :         bool        save_inserted_sublink;
     926             : 
     927       13684 :         context->sublevels_up++;
     928       13684 :         save_inserted_sublink = context->inserted_sublink;
     929       13684 :         context->inserted_sublink = ((Query *) node)->hasSubLinks;
     930       13684 :         newnode = query_tree_mutator((Query *) node,
     931             :                                      flatten_join_alias_vars_mutator,
     932             :                                      context,
     933             :                                      QTW_IGNORE_JOINALIASES);
     934       13684 :         newnode->hasSubLinks |= context->inserted_sublink;
     935       13684 :         context->inserted_sublink = save_inserted_sublink;
     936       13684 :         context->sublevels_up--;
     937       13684 :         return (Node *) newnode;
     938             :     }
     939             :     /* Already-planned tree not supported */
     940             :     Assert(!IsA(node, SubPlan));
     941             :     Assert(!IsA(node, AlternativeSubPlan));
     942             :     /* Shouldn't need to handle these planner auxiliary nodes here */
     943             :     Assert(!IsA(node, SpecialJoinInfo));
     944             :     Assert(!IsA(node, PlaceHolderInfo));
     945             :     Assert(!IsA(node, MinMaxAggInfo));
     946             : 
     947     1767334 :     return expression_tree_mutator(node, flatten_join_alias_vars_mutator, context);
     948             : }
     949             : 
     950             : /*
     951             :  * flatten_group_exprs
     952             :  *    Replace Vars that reference GROUP outputs with the underlying grouping
     953             :  *    expressions.
     954             :  *
     955             :  * We have to preserve any varnullingrels info attached to the group Vars we're
     956             :  * replacing.  If the replacement expression is a Var or PlaceHolderVar or
     957             :  * constructed from those, we can just add the varnullingrels bits to the
     958             :  * existing nullingrels field(s); otherwise we have to add a PlaceHolderVar
     959             :  * wrapper.
     960             :  *
     961             :  * NOTE: this is also used by ruleutils.c, to deparse one query parsetree back
     962             :  * to source text.  For that use-case, root will be NULL, which is why we have
     963             :  * to pass the Query separately.  We need the root itself only for preserving
     964             :  * varnullingrels.  We can avoid preserving varnullingrels in the ruleutils.c's
     965             :  * usage because it does not make any difference to the deparsed source text.
     966             :  */
     967             : Node *
     968        9252 : flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
     969             : {
     970             :     flatten_join_alias_vars_context context;
     971             : 
     972             :     /*
     973             :      * We do not expect this to be applied to the whole Query, only to
     974             :      * expressions or LATERAL subqueries.  Hence, if the top node is a Query,
     975             :      * it's okay to immediately increment sublevels_up.
     976             :      */
     977             :     Assert(node != (Node *) query);
     978             : 
     979        9252 :     context.root = root;
     980        9252 :     context.query = query;
     981        9252 :     context.sublevels_up = 0;
     982             :     /* flag whether grouping expressions could possibly contain SubLinks */
     983        9252 :     context.possible_sublink = query->hasSubLinks;
     984             :     /* if hasSubLinks is already true, no need to work hard */
     985        9252 :     context.inserted_sublink = query->hasSubLinks;
     986             : 
     987        9252 :     return flatten_group_exprs_mutator(node, &context);
     988             : }
     989             : 
     990             : static Node *
     991       60222 : flatten_group_exprs_mutator(Node *node,
     992             :                             flatten_join_alias_vars_context *context)
     993             : {
     994       60222 :     if (node == NULL)
     995       10524 :         return NULL;
     996       49698 :     if (IsA(node, Var))
     997             :     {
     998        9586 :         Var        *var = (Var *) node;
     999             :         RangeTblEntry *rte;
    1000             :         Node       *newvar;
    1001             : 
    1002             :         /* No change unless Var belongs to the GROUP of the target level */
    1003        9586 :         if (var->varlevelsup != context->sublevels_up)
    1004           0 :             return node;        /* no need to copy, really */
    1005        9586 :         rte = rt_fetch(var->varno, context->query->rtable);
    1006        9586 :         if (rte->rtekind != RTE_GROUP)
    1007         298 :             return node;
    1008             : 
    1009             :         /* Expand group exprs reference */
    1010             :         Assert(var->varattno > 0);
    1011        9288 :         newvar = (Node *) list_nth(rte->groupexprs, var->varattno - 1);
    1012             :         Assert(newvar != NULL);
    1013        9288 :         newvar = copyObject(newvar);
    1014             : 
    1015             :         /*
    1016             :          * If we are expanding an expr carried down from an upper query, must
    1017             :          * adjust its varlevelsup fields.
    1018             :          */
    1019        9288 :         if (context->sublevels_up != 0)
    1020           0 :             IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
    1021             : 
    1022             :         /* Preserve original Var's location, if possible */
    1023        9288 :         if (IsA(newvar, Var))
    1024        7556 :             ((Var *) newvar)->location = var->location;
    1025             : 
    1026             :         /* Detect if we are adding a sublink to query */
    1027        9288 :         if (context->possible_sublink && !context->inserted_sublink)
    1028           0 :             context->inserted_sublink = checkExprHasSubLink(newvar);
    1029             : 
    1030             :         /* Lastly, add any varnullingrels to the replacement expression */
    1031        9288 :         return mark_nullable_by_grouping(context->root, newvar, var);
    1032             :     }
    1033             : 
    1034       40112 :     if (IsA(node, Aggref))
    1035             :     {
    1036        6114 :         Aggref     *agg = (Aggref *) node;
    1037             : 
    1038        6114 :         if ((int) agg->agglevelsup == context->sublevels_up)
    1039             :         {
    1040             :             /*
    1041             :              * If we find an aggregate call of the original level, do not
    1042             :              * recurse into its normal arguments, ORDER BY arguments, or
    1043             :              * filter; there are no grouped vars there.  But we should check
    1044             :              * direct arguments as though they weren't in an aggregate.
    1045             :              */
    1046        6114 :             agg = copyObject(agg);
    1047        6114 :             agg->aggdirectargs = (List *)
    1048        6114 :                 flatten_group_exprs_mutator((Node *) agg->aggdirectargs, context);
    1049             : 
    1050        6114 :             return (Node *) agg;
    1051             :         }
    1052             : 
    1053             :         /*
    1054             :          * We can skip recursing into aggregates of higher levels altogether,
    1055             :          * since they could not possibly contain Vars of concern to us (see
    1056             :          * transformAggregateCall).  We do need to look at aggregates of lower
    1057             :          * levels, however.
    1058             :          */
    1059           0 :         if ((int) agg->agglevelsup > context->sublevels_up)
    1060           0 :             return node;
    1061             :     }
    1062             : 
    1063       33998 :     if (IsA(node, GroupingFunc))
    1064             :     {
    1065         356 :         GroupingFunc *grp = (GroupingFunc *) node;
    1066             : 
    1067             :         /*
    1068             :          * If we find a GroupingFunc node of the original or higher level, do
    1069             :          * not recurse into its arguments; there are no grouped vars there.
    1070             :          */
    1071         356 :         if ((int) grp->agglevelsup >= context->sublevels_up)
    1072         356 :             return node;
    1073             :     }
    1074             : 
    1075       33642 :     if (IsA(node, Query))
    1076             :     {
    1077             :         /* Recurse into RTE subquery or not-yet-planned sublink subquery */
    1078             :         Query      *newnode;
    1079             :         bool        save_inserted_sublink;
    1080             : 
    1081           0 :         context->sublevels_up++;
    1082           0 :         save_inserted_sublink = context->inserted_sublink;
    1083           0 :         context->inserted_sublink = ((Query *) node)->hasSubLinks;
    1084           0 :         newnode = query_tree_mutator((Query *) node,
    1085             :                                      flatten_group_exprs_mutator,
    1086             :                                      context,
    1087             :                                      QTW_IGNORE_GROUPEXPRS);
    1088           0 :         newnode->hasSubLinks |= context->inserted_sublink;
    1089           0 :         context->inserted_sublink = save_inserted_sublink;
    1090           0 :         context->sublevels_up--;
    1091           0 :         return (Node *) newnode;
    1092             :     }
    1093             : 
    1094       33642 :     return expression_tree_mutator(node, flatten_group_exprs_mutator,
    1095             :                                    context);
    1096             : }
    1097             : 
    1098             : /*
    1099             :  * Add oldvar's varnullingrels, if any, to a flattened grouping expression.
    1100             :  * The newnode has been copied, so we can modify it freely.
    1101             :  */
    1102             : static Node *
    1103        9288 : mark_nullable_by_grouping(PlannerInfo *root, Node *newnode, Var *oldvar)
    1104             : {
    1105             :     Relids      relids;
    1106             : 
    1107        9288 :     if (root == NULL)
    1108         642 :         return newnode;
    1109        8646 :     if (oldvar->varnullingrels == NULL)
    1110        6948 :         return newnode;         /* nothing to do */
    1111             : 
    1112             :     Assert(bms_equal(oldvar->varnullingrels,
    1113             :                      bms_make_singleton(root->group_rtindex)));
    1114             : 
    1115        1698 :     relids = pull_varnos_of_level(root, newnode, oldvar->varlevelsup);
    1116             : 
    1117        1698 :     if (!bms_is_empty(relids))
    1118             :     {
    1119             :         /*
    1120             :          * If the newnode is not variable-free, we set the nullingrels of Vars
    1121             :          * or PHVs that are contained in the expression.  This is not really
    1122             :          * 'correct' in theory, because it is the whole expression that can be
    1123             :          * nullable by grouping sets, not its individual vars.  But it works
    1124             :          * in practice, because what we need is that the expression can be
    1125             :          * somehow distinguished from the same expression in ECs, and marking
    1126             :          * its vars is sufficient for this purpose.
    1127             :          */
    1128        1656 :         newnode = add_nulling_relids(newnode,
    1129             :                                      relids,
    1130        1656 :                                      oldvar->varnullingrels);
    1131             :     }
    1132             :     else                        /* variable-free? */
    1133             :     {
    1134             :         /*
    1135             :          * If the newnode is variable-free and does not contain volatile
    1136             :          * functions or set-returning functions, it can be treated as a member
    1137             :          * of EC that is redundant.  So wrap it in a new PlaceHolderVar to
    1138             :          * carry the nullingrels.  Otherwise we do not bother to make any
    1139             :          * changes.
    1140             :          *
    1141             :          * Aggregate functions and window functions are not allowed in
    1142             :          * grouping expressions.
    1143             :          */
    1144             :         Assert(!contain_agg_clause(newnode));
    1145             :         Assert(!contain_window_function(newnode));
    1146             : 
    1147          42 :         if (!contain_volatile_functions(newnode) &&
    1148          42 :             !expression_returns_set(newnode))
    1149             :         {
    1150             :             PlaceHolderVar *newphv;
    1151             :             Relids      phrels;
    1152             : 
    1153          24 :             phrels = get_relids_in_jointree((Node *) root->parse->jointree,
    1154             :                                             true, false);
    1155             :             Assert(!bms_is_empty(phrels));
    1156             : 
    1157          24 :             newphv = make_placeholder_expr(root, (Expr *) newnode, phrels);
    1158             :             /* newphv has zero phlevelsup and NULL phnullingrels; fix it */
    1159          24 :             newphv->phlevelsup = oldvar->varlevelsup;
    1160          24 :             newphv->phnullingrels = bms_copy(oldvar->varnullingrels);
    1161          24 :             newnode = (Node *) newphv;
    1162             :         }
    1163             :     }
    1164             : 
    1165        1698 :     return newnode;
    1166             : }
    1167             : 
    1168             : /*
    1169             :  * Add oldvar's varnullingrels, if any, to a flattened join alias expression.
    1170             :  * The newnode has been copied, so we can modify it freely.
    1171             :  */
    1172             : static Node *
    1173         486 : add_nullingrels_if_needed(PlannerInfo *root, Node *newnode, Var *oldvar)
    1174             : {
    1175         486 :     if (oldvar->varnullingrels == NULL)
    1176         342 :         return newnode;         /* nothing to do */
    1177             :     /* If possible, do it by adding to existing nullingrel fields */
    1178         144 :     if (is_standard_join_alias_expression(newnode, oldvar))
    1179         132 :         adjust_standard_join_alias_expression(newnode, oldvar);
    1180          12 :     else if (root)
    1181             :     {
    1182             :         /*
    1183             :          * We can insert a PlaceHolderVar to carry the nullingrels.  However,
    1184             :          * deciding where to evaluate the PHV is slightly tricky.  We first
    1185             :          * try to evaluate it at the natural semantic level of the new
    1186             :          * expression; but if that expression is variable-free, fall back to
    1187             :          * evaluating it at the join that the oldvar is an alias Var for.
    1188             :          */
    1189             :         PlaceHolderVar *newphv;
    1190          12 :         Index       levelsup = oldvar->varlevelsup;
    1191          12 :         Relids      phrels = pull_varnos_of_level(root, newnode, levelsup);
    1192             : 
    1193          12 :         if (bms_is_empty(phrels))   /* variable-free? */
    1194             :         {
    1195          12 :             if (levelsup != 0)  /* this won't work otherwise */
    1196           0 :                 elog(ERROR, "unsupported join alias expression");
    1197          12 :             phrels = get_relids_for_join(root->parse, oldvar->varno);
    1198             :             /* If it's an outer join, eval below not above the join */
    1199          12 :             phrels = bms_del_member(phrels, oldvar->varno);
    1200             :             Assert(!bms_is_empty(phrels));
    1201             :         }
    1202          12 :         newphv = make_placeholder_expr(root, (Expr *) newnode, phrels);
    1203             :         /* newphv has zero phlevelsup and NULL phnullingrels; fix it */
    1204          12 :         newphv->phlevelsup = levelsup;
    1205          12 :         newphv->phnullingrels = bms_copy(oldvar->varnullingrels);
    1206          12 :         newnode = (Node *) newphv;
    1207             :     }
    1208             :     else
    1209             :     {
    1210             :         /* ooops, we're missing support for something the parser can make */
    1211           0 :         elog(ERROR, "unsupported join alias expression");
    1212             :     }
    1213         144 :     return newnode;
    1214             : }
    1215             : 
    1216             : /*
    1217             :  * Check to see if we can insert nullingrels into this join alias expression
    1218             :  * without use of a separate PlaceHolderVar.
    1219             :  *
    1220             :  * This will handle Vars, PlaceHolderVars, and implicit-coercion and COALESCE
    1221             :  * expressions built from those.  This coverage needs to handle anything
    1222             :  * that the parser would put into joinaliasvars.
    1223             :  */
    1224             : static bool
    1225         444 : is_standard_join_alias_expression(Node *newnode, Var *oldvar)
    1226             : {
    1227         444 :     if (newnode == NULL)
    1228           0 :         return false;
    1229         444 :     if (IsA(newnode, Var) &&
    1230         264 :         ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
    1231         264 :         return true;
    1232         180 :     else if (IsA(newnode, PlaceHolderVar) &&
    1233           0 :              ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
    1234           0 :         return true;
    1235         180 :     else if (IsA(newnode, FuncExpr))
    1236             :     {
    1237          24 :         FuncExpr   *fexpr = (FuncExpr *) newnode;
    1238             : 
    1239             :         /*
    1240             :          * We need to assume that the function wouldn't produce non-NULL from
    1241             :          * NULL, which is reasonable for implicit coercions but otherwise not
    1242             :          * so much.  (Looking at its strictness is likely overkill, and anyway
    1243             :          * it would cause us to fail if someone forgot to mark an implicit
    1244             :          * coercion as strict.)
    1245             :          */
    1246          24 :         if (fexpr->funcformat != COERCE_IMPLICIT_CAST ||
    1247          24 :             fexpr->args == NIL)
    1248           0 :             return false;
    1249             : 
    1250             :         /*
    1251             :          * Examine only the first argument --- coercions might have additional
    1252             :          * arguments that are constants.
    1253             :          */
    1254          24 :         return is_standard_join_alias_expression(linitial(fexpr->args), oldvar);
    1255             :     }
    1256         156 :     else if (IsA(newnode, RelabelType))
    1257             :     {
    1258          12 :         RelabelType *relabel = (RelabelType *) newnode;
    1259             : 
    1260             :         /* This definitely won't produce non-NULL from NULL */
    1261          12 :         return is_standard_join_alias_expression((Node *) relabel->arg, oldvar);
    1262             :     }
    1263         144 :     else if (IsA(newnode, CoerceViaIO))
    1264             :     {
    1265           0 :         CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
    1266             : 
    1267             :         /* This definitely won't produce non-NULL from NULL */
    1268           0 :         return is_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
    1269             :     }
    1270         144 :     else if (IsA(newnode, ArrayCoerceExpr))
    1271             :     {
    1272           0 :         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
    1273             : 
    1274             :         /* This definitely won't produce non-NULL from NULL (at array level) */
    1275           0 :         return is_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
    1276             :     }
    1277         144 :     else if (IsA(newnode, CoalesceExpr))
    1278             :     {
    1279         132 :         CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
    1280             :         ListCell   *lc;
    1281             : 
    1282             :         Assert(cexpr->args != NIL);
    1283         396 :         foreach(lc, cexpr->args)
    1284             :         {
    1285         264 :             if (!is_standard_join_alias_expression(lfirst(lc), oldvar))
    1286           0 :                 return false;
    1287             :         }
    1288         132 :         return true;
    1289             :     }
    1290             :     else
    1291          12 :         return false;
    1292             : }
    1293             : 
    1294             : /*
    1295             :  * Insert nullingrels into an expression accepted by
    1296             :  * is_standard_join_alias_expression.
    1297             :  */
    1298             : static void
    1299         420 : adjust_standard_join_alias_expression(Node *newnode, Var *oldvar)
    1300             : {
    1301         420 :     if (IsA(newnode, Var) &&
    1302         264 :         ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
    1303         264 :     {
    1304         264 :         Var        *newvar = (Var *) newnode;
    1305             : 
    1306         264 :         newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
    1307         264 :                                                  oldvar->varnullingrels);
    1308             :     }
    1309         156 :     else if (IsA(newnode, PlaceHolderVar) &&
    1310           0 :              ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
    1311           0 :     {
    1312           0 :         PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
    1313             : 
    1314           0 :         newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
    1315           0 :                                                 oldvar->varnullingrels);
    1316             :     }
    1317         156 :     else if (IsA(newnode, FuncExpr))
    1318             :     {
    1319          12 :         FuncExpr   *fexpr = (FuncExpr *) newnode;
    1320             : 
    1321          12 :         adjust_standard_join_alias_expression(linitial(fexpr->args), oldvar);
    1322             :     }
    1323         144 :     else if (IsA(newnode, RelabelType))
    1324             :     {
    1325          12 :         RelabelType *relabel = (RelabelType *) newnode;
    1326             : 
    1327          12 :         adjust_standard_join_alias_expression((Node *) relabel->arg, oldvar);
    1328             :     }
    1329         132 :     else if (IsA(newnode, CoerceViaIO))
    1330             :     {
    1331           0 :         CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
    1332             : 
    1333           0 :         adjust_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
    1334             :     }
    1335         132 :     else if (IsA(newnode, ArrayCoerceExpr))
    1336             :     {
    1337           0 :         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
    1338             : 
    1339           0 :         adjust_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
    1340             :     }
    1341         132 :     else if (IsA(newnode, CoalesceExpr))
    1342             :     {
    1343         132 :         CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
    1344             :         ListCell   *lc;
    1345             : 
    1346             :         Assert(cexpr->args != NIL);
    1347         396 :         foreach(lc, cexpr->args)
    1348             :         {
    1349         264 :             adjust_standard_join_alias_expression(lfirst(lc), oldvar);
    1350             :         }
    1351             :     }
    1352             :     else
    1353             :         Assert(false);
    1354         420 : }
    1355             : 
    1356             : /*
    1357             :  * alias_relid_set: in a set of RT indexes, replace joins by their
    1358             :  * underlying base+OJ relids
    1359             :  */
    1360             : static Relids
    1361        1738 : alias_relid_set(Query *query, Relids relids)
    1362             : {
    1363        1738 :     Relids      result = NULL;
    1364             :     int         rtindex;
    1365             : 
    1366        1738 :     rtindex = -1;
    1367        4308 :     while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
    1368             :     {
    1369        2570 :         RangeTblEntry *rte = rt_fetch(rtindex, query->rtable);
    1370             : 
    1371        2570 :         if (rte->rtekind == RTE_JOIN)
    1372         310 :             result = bms_join(result, get_relids_for_join(query, rtindex));
    1373             :         else
    1374        2260 :             result = bms_add_member(result, rtindex);
    1375             :     }
    1376        1738 :     return result;
    1377             : }

Generated by: LCOV version 1.14