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