PostgreSQL Source Code  git master
var.c
Go to the documentation of this file.
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-2023, 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/optimizer.h"
26 #include "optimizer/placeholder.h"
27 #include "optimizer/prep.h"
28 #include "parser/parsetree.h"
29 #include "rewrite/rewriteManip.h"
30 
31 
32 typedef struct
33 {
38 
39 typedef struct
40 {
44 
45 typedef struct
46 {
50 
51 typedef struct
52 {
56 
57 typedef struct
58 {
60  int flags;
62 
63 typedef struct
64 {
65  PlannerInfo *root; /* could be NULL! */
66  Query *query; /* outer Query */
68  bool possible_sublink; /* could aliases include a SubLink? */
69  bool inserted_sublink; /* have we inserted a SubLink? */
71 
72 static bool pull_varnos_walker(Node *node,
73  pull_varnos_context *context);
74 static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context);
75 static bool pull_vars_walker(Node *node, pull_vars_context *context);
76 static bool contain_var_clause_walker(Node *node, void *context);
77 static bool contain_vars_of_level_walker(Node *node, int *sublevels_up);
78 static bool locate_var_of_level_walker(Node *node,
80 static bool pull_var_clause_walker(Node *node,
81  pull_var_clause_context *context);
84 static Node *add_nullingrels_if_needed(PlannerInfo *root, Node *newnode,
85  Var *oldvar);
86 static bool is_standard_join_alias_expression(Node *newnode, Var *oldvar);
87 static void adjust_standard_join_alias_expression(Node *newnode, Var *oldvar);
88 static Relids alias_relid_set(Query *query, Relids relids);
89 
90 
91 /*
92  * pull_varnos
93  * Create a set of all the distinct varnos present in a parsetree.
94  * Only varnos that reference level-zero rtable entries are considered.
95  *
96  * The result includes outer-join relids mentioned in Var.varnullingrels and
97  * PlaceHolderVar.phnullingrels fields in the parsetree.
98  *
99  * "root" can be passed as NULL if it is not necessary to process
100  * PlaceHolderVars.
101  *
102  * NOTE: this is used on not-yet-planned expressions. It may therefore find
103  * bare SubLinks, and if so it needs to recurse into them to look for uplevel
104  * references to the desired rtable level! But when we find a completed
105  * SubPlan, we only need to look at the parameters passed to the subplan.
106  */
107 Relids
109 {
110  pull_varnos_context context;
111 
112  context.varnos = NULL;
113  context.root = root;
114  context.sublevels_up = 0;
115 
116  /*
117  * Must be prepared to start with a Query or a bare expression tree; if
118  * it's a Query, we don't want to increment sublevels_up.
119  */
122  (void *) &context,
123  0);
124 
125  return context.varnos;
126 }
127 
128 /*
129  * pull_varnos_of_level
130  * Create a set of all the distinct varnos present in a parsetree.
131  * Only Vars of the specified level are considered.
132  */
133 Relids
134 pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
135 {
136  pull_varnos_context context;
137 
138  context.varnos = NULL;
139  context.root = root;
140  context.sublevels_up = levelsup;
141 
142  /*
143  * Must be prepared to start with a Query or a bare expression tree; if
144  * it's a Query, we don't want to increment sublevels_up.
145  */
148  (void *) &context,
149  0);
150 
151  return context.varnos;
152 }
153 
154 static bool
156 {
157  if (node == NULL)
158  return false;
159  if (IsA(node, Var))
160  {
161  Var *var = (Var *) node;
162 
163  if (var->varlevelsup == context->sublevels_up)
164  {
165  context->varnos = bms_add_member(context->varnos, var->varno);
166  context->varnos = bms_add_members(context->varnos,
167  var->varnullingrels);
168  }
169  return false;
170  }
171  if (IsA(node, CurrentOfExpr))
172  {
173  CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
174 
175  if (context->sublevels_up == 0)
176  context->varnos = bms_add_member(context->varnos, cexpr->cvarno);
177  return false;
178  }
179  if (IsA(node, PlaceHolderVar))
180  {
181  PlaceHolderVar *phv = (PlaceHolderVar *) node;
182 
183  /*
184  * If a PlaceHolderVar is not of the target query level, ignore it,
185  * instead recursing into its expression to see if it contains any
186  * vars that are of the target level. We'll also do that when the
187  * caller doesn't pass a "root" pointer. (We probably shouldn't see
188  * PlaceHolderVars at all in such cases, but if we do, this is a
189  * reasonable behavior.)
190  */
191  if (phv->phlevelsup == context->sublevels_up &&
192  context->root != NULL)
193  {
194  /*
195  * Ideally, the PHV's contribution to context->varnos is its
196  * ph_eval_at set. However, this code can be invoked before
197  * that's been computed. If we cannot find a PlaceHolderInfo,
198  * fall back to the conservative assumption that the PHV will be
199  * evaluated at its syntactic level (phv->phrels).
200  *
201  * There is a second hazard: this code is also used to examine
202  * qual clauses during deconstruct_jointree, when we may have a
203  * PlaceHolderInfo but its ph_eval_at value is not yet final, so
204  * that theoretically we could obtain a relid set that's smaller
205  * than we'd see later on. That should never happen though,
206  * because we deconstruct the jointree working upwards. Any outer
207  * join that forces delay of evaluation of a given qual clause
208  * will be processed before we examine that clause here, so the
209  * ph_eval_at value should have been updated to include it.
210  *
211  * Another problem is that a PlaceHolderVar can appear in quals or
212  * tlists that have been translated for use in a child appendrel.
213  * Typically such a PHV is a parameter expression sourced by some
214  * other relation, so that the translation from parent appendrel
215  * to child doesn't change its phrels, and we should still take
216  * ph_eval_at at face value. But in corner cases, the PHV's
217  * original phrels can include the parent appendrel itself, in
218  * which case the translated PHV will have the child appendrel in
219  * phrels, and we must translate ph_eval_at to match.
220  */
221  PlaceHolderInfo *phinfo = NULL;
222 
223  if (phv->phlevelsup == 0)
224  {
225  if (phv->phid < context->root->placeholder_array_size)
226  phinfo = context->root->placeholder_array[phv->phid];
227  }
228  if (phinfo == NULL)
229  {
230  /* No PlaceHolderInfo yet, use phrels */
231  context->varnos = bms_add_members(context->varnos,
232  phv->phrels);
233  }
234  else if (bms_equal(phv->phrels, phinfo->ph_var->phrels))
235  {
236  /* Normal case: use ph_eval_at */
237  context->varnos = bms_add_members(context->varnos,
238  phinfo->ph_eval_at);
239  }
240  else
241  {
242  /* Translated PlaceHolderVar: translate ph_eval_at to match */
243  Relids newevalat,
244  delta;
245 
246  /* remove what was removed from phv->phrels ... */
247  delta = bms_difference(phinfo->ph_var->phrels, phv->phrels);
248  newevalat = bms_difference(phinfo->ph_eval_at, delta);
249  /* ... then if that was in fact part of ph_eval_at ... */
250  if (!bms_equal(newevalat, phinfo->ph_eval_at))
251  {
252  /* ... add what was added */
253  delta = bms_difference(phv->phrels, phinfo->ph_var->phrels);
254  newevalat = bms_join(newevalat, delta);
255  }
256  context->varnos = bms_join(context->varnos,
257  newevalat);
258  }
259 
260  /*
261  * In all three cases, include phnullingrels in the result. We
262  * don't worry about possibly needing to translate it, because
263  * appendrels only translate varnos of baserels, not outer joins.
264  */
265  context->varnos = bms_add_members(context->varnos,
266  phv->phnullingrels);
267  return false; /* don't recurse into expression */
268  }
269  }
270  else if (IsA(node, Query))
271  {
272  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
273  bool result;
274 
275  context->sublevels_up++;
276  result = query_tree_walker((Query *) node, pull_varnos_walker,
277  (void *) context, 0);
278  context->sublevels_up--;
279  return result;
280  }
282  (void *) context);
283 }
284 
285 
286 /*
287  * pull_varattnos
288  * Find all the distinct attribute numbers present in an expression tree,
289  * and add them to the initial contents of *varattnos.
290  * Only Vars of the given varno and rtable level zero are considered.
291  *
292  * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
293  * we can include system attributes (e.g., OID) in the bitmap representation.
294  *
295  * Currently, this does not support unplanned subqueries; that is not needed
296  * for current uses. It will handle already-planned SubPlan nodes, though,
297  * looking into only the "testexpr" and the "args" list. (The subplan cannot
298  * contain any other references to Vars of the current level.)
299  */
300 void
301 pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
302 {
303  pull_varattnos_context context;
304 
305  context.varattnos = *varattnos;
306  context.varno = varno;
307 
308  (void) pull_varattnos_walker(node, &context);
309 
310  *varattnos = context.varattnos;
311 }
312 
313 static bool
315 {
316  if (node == NULL)
317  return false;
318  if (IsA(node, Var))
319  {
320  Var *var = (Var *) node;
321 
322  if (var->varno == context->varno && var->varlevelsup == 0)
323  context->varattnos =
324  bms_add_member(context->varattnos,
326  return false;
327  }
328 
329  /* Should not find an unplanned subquery */
330  Assert(!IsA(node, Query));
331 
333  (void *) context);
334 }
335 
336 
337 /*
338  * pull_vars_of_level
339  * Create a list of all Vars (and PlaceHolderVars) referencing the
340  * specified query level in the given parsetree.
341  *
342  * Caution: the Vars are not copied, only linked into the list.
343  */
344 List *
345 pull_vars_of_level(Node *node, int levelsup)
346 {
347  pull_vars_context context;
348 
349  context.vars = NIL;
350  context.sublevels_up = levelsup;
351 
352  /*
353  * Must be prepared to start with a Query or a bare expression tree; if
354  * it's a Query, we don't want to increment sublevels_up.
355  */
358  (void *) &context,
359  0);
360 
361  return context.vars;
362 }
363 
364 static bool
366 {
367  if (node == NULL)
368  return false;
369  if (IsA(node, Var))
370  {
371  Var *var = (Var *) node;
372 
373  if (var->varlevelsup == context->sublevels_up)
374  context->vars = lappend(context->vars, var);
375  return false;
376  }
377  if (IsA(node, PlaceHolderVar))
378  {
379  PlaceHolderVar *phv = (PlaceHolderVar *) node;
380 
381  if (phv->phlevelsup == context->sublevels_up)
382  context->vars = lappend(context->vars, phv);
383  /* we don't want to look into the contained expression */
384  return false;
385  }
386  if (IsA(node, Query))
387  {
388  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
389  bool result;
390 
391  context->sublevels_up++;
392  result = query_tree_walker((Query *) node, pull_vars_walker,
393  (void *) context, 0);
394  context->sublevels_up--;
395  return result;
396  }
398  (void *) context);
399 }
400 
401 
402 /*
403  * contain_var_clause
404  * Recursively scan a clause to discover whether it contains any Var nodes
405  * (of the current query level).
406  *
407  * Returns true if any varnode found.
408  *
409  * Does not examine subqueries, therefore must only be used after reduction
410  * of sublinks to subplans!
411  */
412 bool
414 {
415  return contain_var_clause_walker(node, NULL);
416 }
417 
418 static bool
419 contain_var_clause_walker(Node *node, void *context)
420 {
421  if (node == NULL)
422  return false;
423  if (IsA(node, Var))
424  {
425  if (((Var *) node)->varlevelsup == 0)
426  return true; /* abort the tree traversal and return true */
427  return false;
428  }
429  if (IsA(node, CurrentOfExpr))
430  return true;
431  if (IsA(node, PlaceHolderVar))
432  {
433  if (((PlaceHolderVar *) node)->phlevelsup == 0)
434  return true; /* abort the tree traversal and return true */
435  /* else fall through to check the contained expr */
436  }
437  return expression_tree_walker(node, contain_var_clause_walker, context);
438 }
439 
440 
441 /*
442  * contain_vars_of_level
443  * Recursively scan a clause to discover whether it contains any Var nodes
444  * of the specified query level.
445  *
446  * Returns true if any such Var found.
447  *
448  * Will recurse into sublinks. Also, may be invoked directly on a Query.
449  */
450 bool
451 contain_vars_of_level(Node *node, int levelsup)
452 {
453  int sublevels_up = levelsup;
454 
457  (void *) &sublevels_up,
458  0);
459 }
460 
461 static bool
462 contain_vars_of_level_walker(Node *node, int *sublevels_up)
463 {
464  if (node == NULL)
465  return false;
466  if (IsA(node, Var))
467  {
468  if (((Var *) node)->varlevelsup == *sublevels_up)
469  return true; /* abort tree traversal and return true */
470  return false;
471  }
472  if (IsA(node, CurrentOfExpr))
473  {
474  if (*sublevels_up == 0)
475  return true;
476  return false;
477  }
478  if (IsA(node, PlaceHolderVar))
479  {
480  if (((PlaceHolderVar *) node)->phlevelsup == *sublevels_up)
481  return true; /* abort the tree traversal and return true */
482  /* else fall through to check the contained expr */
483  }
484  if (IsA(node, Query))
485  {
486  /* Recurse into subselects */
487  bool result;
488 
489  (*sublevels_up)++;
490  result = query_tree_walker((Query *) node,
492  (void *) sublevels_up,
493  0);
494  (*sublevels_up)--;
495  return result;
496  }
497  return expression_tree_walker(node,
499  (void *) sublevels_up);
500 }
501 
502 
503 /*
504  * locate_var_of_level
505  * Find the parse location of any Var of the specified query level.
506  *
507  * Returns -1 if no such Var is in the querytree, or if they all have
508  * unknown parse location. (The former case is probably caller error,
509  * but we don't bother to distinguish it from the latter case.)
510  *
511  * Will recurse into sublinks. Also, may be invoked directly on a Query.
512  *
513  * Note: it might seem appropriate to merge this functionality into
514  * contain_vars_of_level, but that would complicate that function's API.
515  * Currently, the only uses of this function are for error reporting,
516  * and so shaving cycles probably isn't very important.
517  */
518 int
519 locate_var_of_level(Node *node, int levelsup)
520 {
522 
523  context.var_location = -1; /* in case we find nothing */
524  context.sublevels_up = levelsup;
525 
528  (void *) &context,
529  0);
530 
531  return context.var_location;
532 }
533 
534 static bool
537 {
538  if (node == NULL)
539  return false;
540  if (IsA(node, Var))
541  {
542  Var *var = (Var *) node;
543 
544  if (var->varlevelsup == context->sublevels_up &&
545  var->location >= 0)
546  {
547  context->var_location = var->location;
548  return true; /* abort tree traversal and return true */
549  }
550  return false;
551  }
552  if (IsA(node, CurrentOfExpr))
553  {
554  /* since CurrentOfExpr doesn't carry location, nothing we can do */
555  return false;
556  }
557  /* No extra code needed for PlaceHolderVar; just look in contained expr */
558  if (IsA(node, Query))
559  {
560  /* Recurse into subselects */
561  bool result;
562 
563  context->sublevels_up++;
564  result = query_tree_walker((Query *) node,
566  (void *) context,
567  0);
568  context->sublevels_up--;
569  return result;
570  }
571  return expression_tree_walker(node,
573  (void *) context);
574 }
575 
576 
577 /*
578  * pull_var_clause
579  * Recursively pulls all Var nodes from an expression clause.
580  *
581  * Aggrefs are handled according to these bits in 'flags':
582  * PVC_INCLUDE_AGGREGATES include Aggrefs in output list
583  * PVC_RECURSE_AGGREGATES recurse into Aggref arguments
584  * neither flag throw error if Aggref found
585  * Vars within an Aggref's expression are included in the result only
586  * when PVC_RECURSE_AGGREGATES is specified.
587  *
588  * WindowFuncs are handled according to these bits in 'flags':
589  * PVC_INCLUDE_WINDOWFUNCS include WindowFuncs in output list
590  * PVC_RECURSE_WINDOWFUNCS recurse into WindowFunc arguments
591  * neither flag throw error if WindowFunc found
592  * Vars within a WindowFunc's expression are included in the result only
593  * when PVC_RECURSE_WINDOWFUNCS is specified.
594  *
595  * PlaceHolderVars are handled according to these bits in 'flags':
596  * PVC_INCLUDE_PLACEHOLDERS include PlaceHolderVars in output list
597  * PVC_RECURSE_PLACEHOLDERS recurse into PlaceHolderVar arguments
598  * neither flag throw error if PlaceHolderVar found
599  * Vars within a PHV's expression are included in the result only
600  * when PVC_RECURSE_PLACEHOLDERS is specified.
601  *
602  * GroupingFuncs are treated exactly like Aggrefs, and so do not need
603  * their own flag bits.
604  *
605  * CurrentOfExpr nodes are ignored in all cases.
606  *
607  * Upper-level vars (with varlevelsup > 0) should not be seen here,
608  * likewise for upper-level Aggrefs and PlaceHolderVars.
609  *
610  * Returns list of nodes found. Note the nodes themselves are not
611  * copied, only referenced.
612  *
613  * Does not examine subqueries, therefore must only be used after reduction
614  * of sublinks to subplans!
615  */
616 List *
617 pull_var_clause(Node *node, int flags)
618 {
619  pull_var_clause_context context;
620 
621  /* Assert that caller has not specified inconsistent flags */
628 
629  context.varlist = NIL;
630  context.flags = flags;
631 
632  pull_var_clause_walker(node, &context);
633  return context.varlist;
634 }
635 
636 static bool
638 {
639  if (node == NULL)
640  return false;
641  if (IsA(node, Var))
642  {
643  if (((Var *) node)->varlevelsup != 0)
644  elog(ERROR, "Upper-level Var found where not expected");
645  context->varlist = lappend(context->varlist, node);
646  return false;
647  }
648  else if (IsA(node, Aggref))
649  {
650  if (((Aggref *) node)->agglevelsup != 0)
651  elog(ERROR, "Upper-level Aggref found where not expected");
652  if (context->flags & PVC_INCLUDE_AGGREGATES)
653  {
654  context->varlist = lappend(context->varlist, node);
655  /* we do NOT descend into the contained expression */
656  return false;
657  }
658  else if (context->flags & PVC_RECURSE_AGGREGATES)
659  {
660  /* fall through to recurse into the aggregate's arguments */
661  }
662  else
663  elog(ERROR, "Aggref found where not expected");
664  }
665  else if (IsA(node, GroupingFunc))
666  {
667  if (((GroupingFunc *) node)->agglevelsup != 0)
668  elog(ERROR, "Upper-level GROUPING found where not expected");
669  if (context->flags & PVC_INCLUDE_AGGREGATES)
670  {
671  context->varlist = lappend(context->varlist, node);
672  /* we do NOT descend into the contained expression */
673  return false;
674  }
675  else if (context->flags & PVC_RECURSE_AGGREGATES)
676  {
677  /* fall through to recurse into the GroupingFunc's arguments */
678  }
679  else
680  elog(ERROR, "GROUPING found where not expected");
681  }
682  else if (IsA(node, WindowFunc))
683  {
684  /* WindowFuncs have no levelsup field to check ... */
685  if (context->flags & PVC_INCLUDE_WINDOWFUNCS)
686  {
687  context->varlist = lappend(context->varlist, node);
688  /* we do NOT descend into the contained expressions */
689  return false;
690  }
691  else if (context->flags & PVC_RECURSE_WINDOWFUNCS)
692  {
693  /* fall through to recurse into the windowfunc's arguments */
694  }
695  else
696  elog(ERROR, "WindowFunc found where not expected");
697  }
698  else if (IsA(node, PlaceHolderVar))
699  {
700  if (((PlaceHolderVar *) node)->phlevelsup != 0)
701  elog(ERROR, "Upper-level PlaceHolderVar found where not expected");
702  if (context->flags & PVC_INCLUDE_PLACEHOLDERS)
703  {
704  context->varlist = lappend(context->varlist, node);
705  /* we do NOT descend into the contained expression */
706  return false;
707  }
708  else if (context->flags & PVC_RECURSE_PLACEHOLDERS)
709  {
710  /* fall through to recurse into the placeholder's expression */
711  }
712  else
713  elog(ERROR, "PlaceHolderVar found where not expected");
714  }
716  (void *) context);
717 }
718 
719 
720 /*
721  * flatten_join_alias_vars
722  * Replace Vars that reference JOIN outputs with references to the original
723  * relation variables instead. This allows quals involving such vars to be
724  * pushed down. Whole-row Vars that reference JOIN relations are expanded
725  * into RowExpr constructs that name the individual output Vars. This
726  * is necessary since we will not scan the JOIN as a base relation, which
727  * is the only way that the executor can directly handle whole-row Vars.
728  *
729  * This also adjusts relid sets found in some expression node types to
730  * substitute the contained base+OJ rels for any join relid.
731  *
732  * If a JOIN contains sub-selects that have been flattened, its join alias
733  * entries might now be arbitrary expressions, not just Vars. This affects
734  * this function in two important ways. First, we might find ourselves
735  * inserting SubLink expressions into subqueries, and we must make sure that
736  * their Query.hasSubLinks fields get set to true if so. If there are any
737  * SubLinks in the join alias lists, the outer Query should already have
738  * hasSubLinks = true, so this is only relevant to un-flattened subqueries.
739  * Second, we have to preserve any varnullingrels info attached to the
740  * alias Vars we're replacing. If the replacement expression is a Var or
741  * PlaceHolderVar or constructed from those, we can just add the
742  * varnullingrels bits to the existing nullingrels field(s); otherwise
743  * we have to add a PlaceHolderVar wrapper.
744  *
745  * NOTE: this is also used by the parser, to expand join alias Vars before
746  * checking GROUP BY validity. For that use-case, root will be NULL, which
747  * is why we have to pass the Query separately. We need the root itself only
748  * for making PlaceHolderVars. We can avoid making PlaceHolderVars in the
749  * parser's usage because it won't be dealing with arbitrary expressions:
750  * so long as adjust_standard_join_alias_expression can handle everything
751  * the parser would make as a join alias expression, we're OK.
752  */
753 Node *
755 {
757 
758  /*
759  * We do not expect this to be applied to the whole Query, only to
760  * expressions or LATERAL subqueries. Hence, if the top node is a Query,
761  * it's okay to immediately increment sublevels_up.
762  */
763  Assert(node != (Node *) query);
764 
765  context.root = root;
766  context.query = query;
767  context.sublevels_up = 0;
768  /* flag whether join aliases could possibly contain SubLinks */
769  context.possible_sublink = query->hasSubLinks;
770  /* if hasSubLinks is already true, no need to work hard */
771  context.inserted_sublink = query->hasSubLinks;
772 
773  return flatten_join_alias_vars_mutator(node, &context);
774 }
775 
776 static Node *
779 {
780  if (node == NULL)
781  return NULL;
782  if (IsA(node, Var))
783  {
784  Var *var = (Var *) node;
785  RangeTblEntry *rte;
786  Node *newvar;
787 
788  /* No change unless Var belongs to a JOIN of the target level */
789  if (var->varlevelsup != context->sublevels_up)
790  return node; /* no need to copy, really */
791  rte = rt_fetch(var->varno, context->query->rtable);
792  if (rte->rtekind != RTE_JOIN)
793  return node;
794  if (var->varattno == InvalidAttrNumber)
795  {
796  /* Must expand whole-row reference */
797  RowExpr *rowexpr;
798  List *fields = NIL;
799  List *colnames = NIL;
800  ListCell *lv;
801  ListCell *ln;
802 
804  forboth(lv, rte->joinaliasvars, ln, rte->eref->colnames)
805  {
806  newvar = (Node *) lfirst(lv);
807  /* Ignore dropped columns */
808  if (newvar == NULL)
809  continue;
810  newvar = copyObject(newvar);
811 
812  /*
813  * If we are expanding an alias carried down from an upper
814  * query, must adjust its varlevelsup fields.
815  */
816  if (context->sublevels_up != 0)
817  IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
818  /* Preserve original Var's location, if possible */
819  if (IsA(newvar, Var))
820  ((Var *) newvar)->location = var->location;
821  /* Recurse in case join input is itself a join */
822  /* (also takes care of setting inserted_sublink if needed) */
823  newvar = flatten_join_alias_vars_mutator(newvar, context);
824  fields = lappend(fields, newvar);
825  /* We need the names of non-dropped columns, too */
826  colnames = lappend(colnames, copyObject((Node *) lfirst(ln)));
827  }
828  rowexpr = makeNode(RowExpr);
829  rowexpr->args = fields;
830  rowexpr->row_typeid = var->vartype;
831  rowexpr->row_format = COERCE_IMPLICIT_CAST;
832  /* vartype will always be RECORDOID, so we always need colnames */
833  rowexpr->colnames = colnames;
834  rowexpr->location = var->location;
835 
836  /* Lastly, add any varnullingrels to the replacement expression */
837  return add_nullingrels_if_needed(context->root, (Node *) rowexpr,
838  var);
839  }
840 
841  /* Expand join alias reference */
842  Assert(var->varattno > 0);
843  newvar = (Node *) list_nth(rte->joinaliasvars, var->varattno - 1);
844  Assert(newvar != NULL);
845  newvar = copyObject(newvar);
846 
847  /*
848  * If we are expanding an alias carried down from an upper query, must
849  * adjust its varlevelsup fields.
850  */
851  if (context->sublevels_up != 0)
852  IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
853 
854  /* Preserve original Var's location, if possible */
855  if (IsA(newvar, Var))
856  ((Var *) newvar)->location = var->location;
857 
858  /* Recurse in case join input is itself a join */
859  newvar = flatten_join_alias_vars_mutator(newvar, context);
860 
861  /* Detect if we are adding a sublink to query */
862  if (context->possible_sublink && !context->inserted_sublink)
863  context->inserted_sublink = checkExprHasSubLink(newvar);
864 
865  /* Lastly, add any varnullingrels to the replacement expression */
866  return add_nullingrels_if_needed(context->root, newvar, var);
867  }
868  if (IsA(node, PlaceHolderVar))
869  {
870  /* Copy the PlaceHolderVar node with correct mutation of subnodes */
871  PlaceHolderVar *phv;
872 
875  (void *) context);
876  /* now fix PlaceHolderVar's relid sets */
877  if (phv->phlevelsup == context->sublevels_up)
878  {
879  phv->phrels = alias_relid_set(context->query,
880  phv->phrels);
881  /* we *don't* change phnullingrels */
882  }
883  return (Node *) phv;
884  }
885 
886  if (IsA(node, Query))
887  {
888  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
889  Query *newnode;
890  bool save_inserted_sublink;
891 
892  context->sublevels_up++;
893  save_inserted_sublink = context->inserted_sublink;
894  context->inserted_sublink = ((Query *) node)->hasSubLinks;
895  newnode = query_tree_mutator((Query *) node,
897  (void *) context,
899  newnode->hasSubLinks |= context->inserted_sublink;
900  context->inserted_sublink = save_inserted_sublink;
901  context->sublevels_up--;
902  return (Node *) newnode;
903  }
904  /* Already-planned tree not supported */
905  Assert(!IsA(node, SubPlan));
906  /* Shouldn't need to handle these planner auxiliary nodes here */
907  Assert(!IsA(node, SpecialJoinInfo));
908  Assert(!IsA(node, PlaceHolderInfo));
909  Assert(!IsA(node, MinMaxAggInfo));
910 
912  (void *) context);
913 }
914 
915 /*
916  * Add oldvar's varnullingrels, if any, to a flattened join alias expression.
917  * The newnode has been copied, so we can modify it freely.
918  */
919 static Node *
921 {
922  if (oldvar->varnullingrels == NULL)
923  return newnode; /* nothing to do */
924  /* If possible, do it by adding to existing nullingrel fields */
925  if (is_standard_join_alias_expression(newnode, oldvar))
926  adjust_standard_join_alias_expression(newnode, oldvar);
927  else if (root)
928  {
929  /*
930  * We can insert a PlaceHolderVar to carry the nullingrels. However,
931  * deciding where to evaluate the PHV is slightly tricky. We first
932  * try to evaluate it at the natural semantic level of the new
933  * expression; but if that expression is variable-free, fall back to
934  * evaluating it at the join that the oldvar is an alias Var for.
935  */
936  PlaceHolderVar *newphv;
937  Index levelsup = oldvar->varlevelsup;
938  Relids phrels = pull_varnos_of_level(root, newnode, levelsup);
939 
940  if (bms_is_empty(phrels)) /* variable-free? */
941  {
942  if (levelsup != 0) /* this won't work otherwise */
943  elog(ERROR, "unsupported join alias expression");
944  phrels = get_relids_for_join(root->parse, oldvar->varno);
945  /* If it's an outer join, eval below not above the join */
946  phrels = bms_del_member(phrels, oldvar->varno);
947  Assert(!bms_is_empty(phrels));
948  }
949  newphv = make_placeholder_expr(root, (Expr *) newnode, phrels);
950  /* newphv has zero phlevelsup and NULL phnullingrels; fix it */
951  newphv->phlevelsup = levelsup;
952  newphv->phnullingrels = bms_copy(oldvar->varnullingrels);
953  newnode = (Node *) newphv;
954  }
955  else
956  {
957  /* ooops, we're missing support for something the parser can make */
958  elog(ERROR, "unsupported join alias expression");
959  }
960  return newnode;
961 }
962 
963 /*
964  * Check to see if we can insert nullingrels into this join alias expression
965  * without use of a separate PlaceHolderVar.
966  *
967  * This will handle Vars, PlaceHolderVars, and implicit-coercion and COALESCE
968  * expressions built from those. This coverage needs to handle anything
969  * that the parser would put into joinaliasvars.
970  */
971 static bool
973 {
974  if (newnode == NULL)
975  return false;
976  if (IsA(newnode, Var) &&
977  ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
978  return true;
979  else if (IsA(newnode, PlaceHolderVar) &&
980  ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
981  return true;
982  else if (IsA(newnode, FuncExpr))
983  {
984  FuncExpr *fexpr = (FuncExpr *) newnode;
985 
986  /*
987  * We need to assume that the function wouldn't produce non-NULL from
988  * NULL, which is reasonable for implicit coercions but otherwise not
989  * so much. (Looking at its strictness is likely overkill, and anyway
990  * it would cause us to fail if someone forgot to mark an implicit
991  * coercion as strict.)
992  */
993  if (fexpr->funcformat != COERCE_IMPLICIT_CAST ||
994  fexpr->args == NIL)
995  return false;
996 
997  /*
998  * Examine only the first argument --- coercions might have additional
999  * arguments that are constants.
1000  */
1001  return is_standard_join_alias_expression(linitial(fexpr->args), oldvar);
1002  }
1003  else if (IsA(newnode, RelabelType))
1004  {
1005  RelabelType *relabel = (RelabelType *) newnode;
1006 
1007  /* This definitely won't produce non-NULL from NULL */
1008  return is_standard_join_alias_expression((Node *) relabel->arg, oldvar);
1009  }
1010  else if (IsA(newnode, CoerceViaIO))
1011  {
1012  CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
1013 
1014  /* This definitely won't produce non-NULL from NULL */
1015  return is_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
1016  }
1017  else if (IsA(newnode, ArrayCoerceExpr))
1018  {
1019  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
1020 
1021  /* This definitely won't produce non-NULL from NULL (at array level) */
1022  return is_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
1023  }
1024  else if (IsA(newnode, CoalesceExpr))
1025  {
1026  CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
1027  ListCell *lc;
1028 
1029  Assert(cexpr->args != NIL);
1030  foreach(lc, cexpr->args)
1031  {
1032  if (!is_standard_join_alias_expression(lfirst(lc), oldvar))
1033  return false;
1034  }
1035  return true;
1036  }
1037  else
1038  return false;
1039 }
1040 
1041 /*
1042  * Insert nullingrels into an expression accepted by
1043  * is_standard_join_alias_expression.
1044  */
1045 static void
1047 {
1048  if (IsA(newnode, Var) &&
1049  ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
1050  {
1051  Var *newvar = (Var *) newnode;
1052 
1053  newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
1054  oldvar->varnullingrels);
1055  }
1056  else if (IsA(newnode, PlaceHolderVar) &&
1057  ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
1058  {
1059  PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
1060 
1061  newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
1062  oldvar->varnullingrels);
1063  }
1064  else if (IsA(newnode, FuncExpr))
1065  {
1066  FuncExpr *fexpr = (FuncExpr *) newnode;
1067 
1069  }
1070  else if (IsA(newnode, RelabelType))
1071  {
1072  RelabelType *relabel = (RelabelType *) newnode;
1073 
1074  adjust_standard_join_alias_expression((Node *) relabel->arg, oldvar);
1075  }
1076  else if (IsA(newnode, CoerceViaIO))
1077  {
1078  CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
1079 
1080  adjust_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
1081  }
1082  else if (IsA(newnode, ArrayCoerceExpr))
1083  {
1084  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
1085 
1086  adjust_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
1087  }
1088  else if (IsA(newnode, CoalesceExpr))
1089  {
1090  CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
1091  ListCell *lc;
1092 
1093  Assert(cexpr->args != NIL);
1094  foreach(lc, cexpr->args)
1095  {
1097  }
1098  }
1099  else
1100  Assert(false);
1101 }
1102 
1103 /*
1104  * alias_relid_set: in a set of RT indexes, replace joins by their
1105  * underlying base+OJ relids
1106  */
1107 static Relids
1109 {
1110  Relids result = NULL;
1111  int rtindex;
1112 
1113  rtindex = -1;
1114  while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
1115  {
1116  RangeTblEntry *rte = rt_fetch(rtindex, query->rtable);
1117 
1118  if (rte->rtekind == RTE_JOIN)
1119  result = bms_join(result, get_relids_for_join(query, rtindex));
1120  else
1121  result = bms_add_member(result, rtindex);
1122  }
1123  return result;
1124 }
#define InvalidAttrNumber
Definition: attnum.h:23
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:953
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:292
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:776
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
unsigned int Index
Definition: c.h:598
#define ERROR
Definition: elog.h:39
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:153
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define query_or_expression_tree_walker(n, w, c, f)
Definition: nodeFuncs.h:169
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define query_tree_mutator(q, m, c, f)
Definition: nodeFuncs.h:158
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:25
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define copyObject(obj)
Definition: nodes.h:244
#define makeNode(_type_)
Definition: nodes.h:176
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:184
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:188
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:186
#define PVC_INCLUDE_WINDOWFUNCS
Definition: optimizer.h:185
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:187
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:183
@ RTE_JOIN
Definition: parsenodes.h:1015
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
#define linitial(l)
Definition: pg_list.h:178
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
PlaceHolderVar * make_placeholder_expr(PlannerInfo *root, Expr *expr, Relids phrels)
Definition: placeholder.c:54
Relids get_relids_for_join(Query *query, int joinrelid)
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:660
bool checkExprHasSubLink(Node *node)
Definition: rewriteManip.c:295
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:836
List * colnames
Definition: primnodes.h:43
List * args
Definition: primnodes.h:1410
Expr * arg
Definition: primnodes.h:1127
List * args
Definition: primnodes.h:692
Definition: pg_list.h:54
Definition: nodes.h:129
Relids ph_eval_at
Definition: pathnodes.h:3022
PlaceHolderVar * ph_var
Definition: pathnodes.h:3019
Relids phnullingrels
Definition: pathnodes.h:2736
Index phlevelsup
Definition: pathnodes.h:2742
Query * parse
Definition: pathnodes.h:202
List * rtable
Definition: parsenodes.h:175
Alias * eref
Definition: parsenodes.h:1199
List * joinaliasvars
Definition: parsenodes.h:1128
RTEKind rtekind
Definition: parsenodes.h:1032
Expr * arg
Definition: primnodes.h:1104
int location
Definition: primnodes.h:1353
List * args
Definition: primnodes.h:1329
Definition: primnodes.h:223
AttrNumber varattno
Definition: primnodes.h:235
int varno
Definition: primnodes.h:230
Index varlevelsup
Definition: primnodes.h:255
int location
Definition: primnodes.h:268
PlannerInfo * root
Definition: var.c:65
Bitmapset * varattnos
Definition: var.c:41
PlannerInfo * root
Definition: var.c:35
int sublevels_up
Definition: var.c:36
Relids varnos
Definition: var.c:34
int sublevels_up
Definition: var.c:48
List * vars
Definition: var.c:47
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context)
Definition: var.c:314
List * pull_vars_of_level(Node *node, int levelsup)
Definition: var.c:345
static Node * add_nullingrels_if_needed(PlannerInfo *root, Node *newnode, Var *oldvar)
Definition: var.c:920
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:451
List * pull_var_clause(Node *node, int flags)
Definition: var.c:617
static Node * flatten_join_alias_vars_mutator(Node *node, flatten_join_alias_vars_context *context)
Definition: var.c:777
bool contain_var_clause(Node *node)
Definition: var.c:413
Relids pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
Definition: var.c:134
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108
static bool pull_varnos_walker(Node *node, pull_varnos_context *context)
Definition: var.c:155
static bool pull_var_clause_walker(Node *node, pull_var_clause_context *context)
Definition: var.c:637
static Relids alias_relid_set(Query *query, Relids relids)
Definition: var.c:1108
static bool contain_vars_of_level_walker(Node *node, int *sublevels_up)
Definition: var.c:462
static bool is_standard_join_alias_expression(Node *newnode, Var *oldvar)
Definition: var.c:972
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition: var.c:754
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:301
static void adjust_standard_join_alias_expression(Node *newnode, Var *oldvar)
Definition: var.c:1046
static bool locate_var_of_level_walker(Node *node, locate_var_of_level_context *context)
Definition: var.c:535
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:519
static bool contain_var_clause_walker(Node *node, void *context)
Definition: var.c:419
static bool pull_vars_walker(Node *node, pull_vars_context *context)
Definition: var.c:365