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-2021, 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 {
34 	Relids		varnos;
35 	PlannerInfo *root;
36 	int			sublevels_up;
37 } pull_varnos_context;
38 
39 typedef struct
40 {
41 	Bitmapset  *varattnos;
42 	Index		varno;
43 } pull_varattnos_context;
44 
45 typedef struct
46 {
47 	List	   *vars;
48 	int			sublevels_up;
49 } pull_vars_context;
50 
51 typedef struct
52 {
53 	int			var_location;
54 	int			sublevels_up;
55 } locate_var_of_level_context;
56 
57 typedef struct
58 {
59 	List	   *varlist;
60 	int			flags;
61 } pull_var_clause_context;
62 
63 typedef struct
64 {
65 	Query	   *query;			/* outer Query */
66 	int			sublevels_up;
67 	bool		possible_sublink;	/* could aliases include a SubLink? */
68 	bool		inserted_sublink;	/* have we inserted a SubLink? */
69 } flatten_join_alias_vars_context;
70 
71 static bool pull_varnos_walker(Node *node,
72 							   pull_varnos_context *context);
73 static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context);
74 static bool pull_vars_walker(Node *node, pull_vars_context *context);
75 static bool contain_var_clause_walker(Node *node, void *context);
76 static bool contain_vars_of_level_walker(Node *node, int *sublevels_up);
77 static bool locate_var_of_level_walker(Node *node,
78 									   locate_var_of_level_context *context);
79 static bool pull_var_clause_walker(Node *node,
80 								   pull_var_clause_context *context);
81 static Node *flatten_join_alias_vars_mutator(Node *node,
82 											 flatten_join_alias_vars_context *context);
83 static Relids alias_relid_set(Query *query, Relids relids);
84 
85 
86 /*
87  * pull_varnos
88  *		Create a set of all the distinct varnos present in a parsetree.
89  *		Only varnos that reference level-zero rtable entries are considered.
90  *
91  * NOTE: this is used on not-yet-planned expressions.  It may therefore find
92  * bare SubLinks, and if so it needs to recurse into them to look for uplevel
93  * references to the desired rtable level!	But when we find a completed
94  * SubPlan, we only need to look at the parameters passed to the subplan.
95  */
96 Relids
pull_varnos(PlannerInfo * root,Node * node)97 pull_varnos(PlannerInfo *root, Node *node)
98 {
99 	pull_varnos_context context;
100 
101 	context.varnos = NULL;
102 	context.root = root;
103 	context.sublevels_up = 0;
104 
105 	/*
106 	 * Must be prepared to start with a Query or a bare expression tree; if
107 	 * it's a Query, we don't want to increment sublevels_up.
108 	 */
109 	query_or_expression_tree_walker(node,
110 									pull_varnos_walker,
111 									(void *) &context,
112 									0);
113 
114 	return context.varnos;
115 }
116 
117 /*
118  * pull_varnos_of_level
119  *		Create a set of all the distinct varnos present in a parsetree.
120  *		Only Vars of the specified level are considered.
121  */
122 Relids
pull_varnos_of_level(PlannerInfo * root,Node * node,int levelsup)123 pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
124 {
125 	pull_varnos_context context;
126 
127 	context.varnos = NULL;
128 	context.root = root;
129 	context.sublevels_up = levelsup;
130 
131 	/*
132 	 * Must be prepared to start with a Query or a bare expression tree; if
133 	 * it's a Query, we don't want to increment sublevels_up.
134 	 */
135 	query_or_expression_tree_walker(node,
136 									pull_varnos_walker,
137 									(void *) &context,
138 									0);
139 
140 	return context.varnos;
141 }
142 
143 static bool
pull_varnos_walker(Node * node,pull_varnos_context * context)144 pull_varnos_walker(Node *node, pull_varnos_context *context)
145 {
146 	if (node == NULL)
147 		return false;
148 	if (IsA(node, Var))
149 	{
150 		Var		   *var = (Var *) node;
151 
152 		if (var->varlevelsup == context->sublevels_up)
153 			context->varnos = bms_add_member(context->varnos, var->varno);
154 		return false;
155 	}
156 	if (IsA(node, CurrentOfExpr))
157 	{
158 		CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
159 
160 		if (context->sublevels_up == 0)
161 			context->varnos = bms_add_member(context->varnos, cexpr->cvarno);
162 		return false;
163 	}
164 	if (IsA(node, PlaceHolderVar))
165 	{
166 		PlaceHolderVar *phv = (PlaceHolderVar *) node;
167 
168 		/*
169 		 * If a PlaceHolderVar is not of the target query level, ignore it,
170 		 * instead recursing into its expression to see if it contains any
171 		 * vars that are of the target level.
172 		 */
173 		if (phv->phlevelsup == context->sublevels_up)
174 		{
175 			/*
176 			 * Ideally, the PHV's contribution to context->varnos is its
177 			 * ph_eval_at set.  However, this code can be invoked before
178 			 * that's been computed.  If we cannot find a PlaceHolderInfo,
179 			 * fall back to the conservative assumption that the PHV will be
180 			 * evaluated at its syntactic level (phv->phrels).
181 			 *
182 			 * There is a second hazard: this code is also used to examine
183 			 * qual clauses during deconstruct_jointree, when we may have a
184 			 * PlaceHolderInfo but its ph_eval_at value is not yet final, so
185 			 * that theoretically we could obtain a relid set that's smaller
186 			 * than we'd see later on.  That should never happen though,
187 			 * because we deconstruct the jointree working upwards.  Any outer
188 			 * join that forces delay of evaluation of a given qual clause
189 			 * will be processed before we examine that clause here, so the
190 			 * ph_eval_at value should have been updated to include it.
191 			 *
192 			 * Another problem is that a PlaceHolderVar can appear in quals or
193 			 * tlists that have been translated for use in a child appendrel.
194 			 * Typically such a PHV is a parameter expression sourced by some
195 			 * other relation, so that the translation from parent appendrel
196 			 * to child doesn't change its phrels, and we should still take
197 			 * ph_eval_at at face value.  But in corner cases, the PHV's
198 			 * original phrels can include the parent appendrel itself, in
199 			 * which case the translated PHV will have the child appendrel in
200 			 * phrels, and we must translate ph_eval_at to match.
201 			 */
202 			PlaceHolderInfo *phinfo = NULL;
203 
204 			if (phv->phlevelsup == 0)
205 			{
206 				ListCell   *lc;
207 
208 				foreach(lc, context->root->placeholder_list)
209 				{
210 					phinfo = (PlaceHolderInfo *) lfirst(lc);
211 					if (phinfo->phid == phv->phid)
212 						break;
213 					phinfo = NULL;
214 				}
215 			}
216 			if (phinfo == NULL)
217 			{
218 				/* No PlaceHolderInfo yet, use phrels */
219 				context->varnos = bms_add_members(context->varnos,
220 												  phv->phrels);
221 			}
222 			else if (bms_equal(phv->phrels, phinfo->ph_var->phrels))
223 			{
224 				/* Normal case: use ph_eval_at */
225 				context->varnos = bms_add_members(context->varnos,
226 												  phinfo->ph_eval_at);
227 			}
228 			else
229 			{
230 				/* Translated PlaceHolderVar: translate ph_eval_at to match */
231 				Relids		newevalat,
232 							delta;
233 
234 				/* remove what was removed from phv->phrels ... */
235 				delta = bms_difference(phinfo->ph_var->phrels, phv->phrels);
236 				newevalat = bms_difference(phinfo->ph_eval_at, delta);
237 				/* ... then if that was in fact part of ph_eval_at ... */
238 				if (!bms_equal(newevalat, phinfo->ph_eval_at))
239 				{
240 					/* ... add what was added */
241 					delta = bms_difference(phv->phrels, phinfo->ph_var->phrels);
242 					newevalat = bms_join(newevalat, delta);
243 				}
244 				context->varnos = bms_join(context->varnos,
245 										   newevalat);
246 			}
247 			return false;		/* don't recurse into expression */
248 		}
249 	}
250 	else if (IsA(node, Query))
251 	{
252 		/* Recurse into RTE subquery or not-yet-planned sublink subquery */
253 		bool		result;
254 
255 		context->sublevels_up++;
256 		result = query_tree_walker((Query *) node, pull_varnos_walker,
257 								   (void *) context, 0);
258 		context->sublevels_up--;
259 		return result;
260 	}
261 	return expression_tree_walker(node, pull_varnos_walker,
262 								  (void *) context);
263 }
264 
265 
266 /*
267  * pull_varattnos
268  *		Find all the distinct attribute numbers present in an expression tree,
269  *		and add them to the initial contents of *varattnos.
270  *		Only Vars of the given varno and rtable level zero are considered.
271  *
272  * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
273  * we can include system attributes (e.g., OID) in the bitmap representation.
274  *
275  * Currently, this does not support unplanned subqueries; that is not needed
276  * for current uses.  It will handle already-planned SubPlan nodes, though,
277  * looking into only the "testexpr" and the "args" list.  (The subplan cannot
278  * contain any other references to Vars of the current level.)
279  */
280 void
pull_varattnos(Node * node,Index varno,Bitmapset ** varattnos)281 pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
282 {
283 	pull_varattnos_context context;
284 
285 	context.varattnos = *varattnos;
286 	context.varno = varno;
287 
288 	(void) pull_varattnos_walker(node, &context);
289 
290 	*varattnos = context.varattnos;
291 }
292 
293 static bool
pull_varattnos_walker(Node * node,pull_varattnos_context * context)294 pull_varattnos_walker(Node *node, pull_varattnos_context *context)
295 {
296 	if (node == NULL)
297 		return false;
298 	if (IsA(node, Var))
299 	{
300 		Var		   *var = (Var *) node;
301 
302 		if (var->varno == context->varno && var->varlevelsup == 0)
303 			context->varattnos =
304 				bms_add_member(context->varattnos,
305 							   var->varattno - FirstLowInvalidHeapAttributeNumber);
306 		return false;
307 	}
308 
309 	/* Should not find an unplanned subquery */
310 	Assert(!IsA(node, Query));
311 
312 	return expression_tree_walker(node, pull_varattnos_walker,
313 								  (void *) context);
314 }
315 
316 
317 /*
318  * pull_vars_of_level
319  *		Create a list of all Vars (and PlaceHolderVars) referencing the
320  *		specified query level in the given parsetree.
321  *
322  * Caution: the Vars are not copied, only linked into the list.
323  */
324 List *
pull_vars_of_level(Node * node,int levelsup)325 pull_vars_of_level(Node *node, int levelsup)
326 {
327 	pull_vars_context context;
328 
329 	context.vars = NIL;
330 	context.sublevels_up = levelsup;
331 
332 	/*
333 	 * Must be prepared to start with a Query or a bare expression tree; if
334 	 * it's a Query, we don't want to increment sublevels_up.
335 	 */
336 	query_or_expression_tree_walker(node,
337 									pull_vars_walker,
338 									(void *) &context,
339 									0);
340 
341 	return context.vars;
342 }
343 
344 static bool
pull_vars_walker(Node * node,pull_vars_context * context)345 pull_vars_walker(Node *node, pull_vars_context *context)
346 {
347 	if (node == NULL)
348 		return false;
349 	if (IsA(node, Var))
350 	{
351 		Var		   *var = (Var *) node;
352 
353 		if (var->varlevelsup == context->sublevels_up)
354 			context->vars = lappend(context->vars, var);
355 		return false;
356 	}
357 	if (IsA(node, PlaceHolderVar))
358 	{
359 		PlaceHolderVar *phv = (PlaceHolderVar *) node;
360 
361 		if (phv->phlevelsup == context->sublevels_up)
362 			context->vars = lappend(context->vars, phv);
363 		/* we don't want to look into the contained expression */
364 		return false;
365 	}
366 	if (IsA(node, Query))
367 	{
368 		/* Recurse into RTE subquery or not-yet-planned sublink subquery */
369 		bool		result;
370 
371 		context->sublevels_up++;
372 		result = query_tree_walker((Query *) node, pull_vars_walker,
373 								   (void *) context, 0);
374 		context->sublevels_up--;
375 		return result;
376 	}
377 	return expression_tree_walker(node, pull_vars_walker,
378 								  (void *) context);
379 }
380 
381 
382 /*
383  * contain_var_clause
384  *	  Recursively scan a clause to discover whether it contains any Var nodes
385  *	  (of the current query level).
386  *
387  *	  Returns true if any varnode found.
388  *
389  * Does not examine subqueries, therefore must only be used after reduction
390  * of sublinks to subplans!
391  */
392 bool
contain_var_clause(Node * node)393 contain_var_clause(Node *node)
394 {
395 	return contain_var_clause_walker(node, NULL);
396 }
397 
398 static bool
contain_var_clause_walker(Node * node,void * context)399 contain_var_clause_walker(Node *node, void *context)
400 {
401 	if (node == NULL)
402 		return false;
403 	if (IsA(node, Var))
404 	{
405 		if (((Var *) node)->varlevelsup == 0)
406 			return true;		/* abort the tree traversal and return true */
407 		return false;
408 	}
409 	if (IsA(node, CurrentOfExpr))
410 		return true;
411 	if (IsA(node, PlaceHolderVar))
412 	{
413 		if (((PlaceHolderVar *) node)->phlevelsup == 0)
414 			return true;		/* abort the tree traversal and return true */
415 		/* else fall through to check the contained expr */
416 	}
417 	return expression_tree_walker(node, contain_var_clause_walker, context);
418 }
419 
420 
421 /*
422  * contain_vars_of_level
423  *	  Recursively scan a clause to discover whether it contains any Var nodes
424  *	  of the specified query level.
425  *
426  *	  Returns true if any such Var found.
427  *
428  * Will recurse into sublinks.  Also, may be invoked directly on a Query.
429  */
430 bool
contain_vars_of_level(Node * node,int levelsup)431 contain_vars_of_level(Node *node, int levelsup)
432 {
433 	int			sublevels_up = levelsup;
434 
435 	return query_or_expression_tree_walker(node,
436 										   contain_vars_of_level_walker,
437 										   (void *) &sublevels_up,
438 										   0);
439 }
440 
441 static bool
contain_vars_of_level_walker(Node * node,int * sublevels_up)442 contain_vars_of_level_walker(Node *node, int *sublevels_up)
443 {
444 	if (node == NULL)
445 		return false;
446 	if (IsA(node, Var))
447 	{
448 		if (((Var *) node)->varlevelsup == *sublevels_up)
449 			return true;		/* abort tree traversal and return true */
450 		return false;
451 	}
452 	if (IsA(node, CurrentOfExpr))
453 	{
454 		if (*sublevels_up == 0)
455 			return true;
456 		return false;
457 	}
458 	if (IsA(node, PlaceHolderVar))
459 	{
460 		if (((PlaceHolderVar *) node)->phlevelsup == *sublevels_up)
461 			return true;		/* abort the tree traversal and return true */
462 		/* else fall through to check the contained expr */
463 	}
464 	if (IsA(node, Query))
465 	{
466 		/* Recurse into subselects */
467 		bool		result;
468 
469 		(*sublevels_up)++;
470 		result = query_tree_walker((Query *) node,
471 								   contain_vars_of_level_walker,
472 								   (void *) sublevels_up,
473 								   0);
474 		(*sublevels_up)--;
475 		return result;
476 	}
477 	return expression_tree_walker(node,
478 								  contain_vars_of_level_walker,
479 								  (void *) sublevels_up);
480 }
481 
482 
483 /*
484  * locate_var_of_level
485  *	  Find the parse location of any Var of the specified query level.
486  *
487  * Returns -1 if no such Var is in the querytree, or if they all have
488  * unknown parse location.  (The former case is probably caller error,
489  * but we don't bother to distinguish it from the latter case.)
490  *
491  * Will recurse into sublinks.  Also, may be invoked directly on a Query.
492  *
493  * Note: it might seem appropriate to merge this functionality into
494  * contain_vars_of_level, but that would complicate that function's API.
495  * Currently, the only uses of this function are for error reporting,
496  * and so shaving cycles probably isn't very important.
497  */
498 int
locate_var_of_level(Node * node,int levelsup)499 locate_var_of_level(Node *node, int levelsup)
500 {
501 	locate_var_of_level_context context;
502 
503 	context.var_location = -1;	/* in case we find nothing */
504 	context.sublevels_up = levelsup;
505 
506 	(void) query_or_expression_tree_walker(node,
507 										   locate_var_of_level_walker,
508 										   (void *) &context,
509 										   0);
510 
511 	return context.var_location;
512 }
513 
514 static bool
locate_var_of_level_walker(Node * node,locate_var_of_level_context * context)515 locate_var_of_level_walker(Node *node,
516 						   locate_var_of_level_context *context)
517 {
518 	if (node == NULL)
519 		return false;
520 	if (IsA(node, Var))
521 	{
522 		Var		   *var = (Var *) node;
523 
524 		if (var->varlevelsup == context->sublevels_up &&
525 			var->location >= 0)
526 		{
527 			context->var_location = var->location;
528 			return true;		/* abort tree traversal and return true */
529 		}
530 		return false;
531 	}
532 	if (IsA(node, CurrentOfExpr))
533 	{
534 		/* since CurrentOfExpr doesn't carry location, nothing we can do */
535 		return false;
536 	}
537 	/* No extra code needed for PlaceHolderVar; just look in contained expr */
538 	if (IsA(node, Query))
539 	{
540 		/* Recurse into subselects */
541 		bool		result;
542 
543 		context->sublevels_up++;
544 		result = query_tree_walker((Query *) node,
545 								   locate_var_of_level_walker,
546 								   (void *) context,
547 								   0);
548 		context->sublevels_up--;
549 		return result;
550 	}
551 	return expression_tree_walker(node,
552 								  locate_var_of_level_walker,
553 								  (void *) context);
554 }
555 
556 
557 /*
558  * pull_var_clause
559  *	  Recursively pulls all Var nodes from an expression clause.
560  *
561  *	  Aggrefs are handled according to these bits in 'flags':
562  *		PVC_INCLUDE_AGGREGATES		include Aggrefs in output list
563  *		PVC_RECURSE_AGGREGATES		recurse into Aggref arguments
564  *		neither flag				throw error if Aggref found
565  *	  Vars within an Aggref's expression are included in the result only
566  *	  when PVC_RECURSE_AGGREGATES is specified.
567  *
568  *	  WindowFuncs are handled according to these bits in 'flags':
569  *		PVC_INCLUDE_WINDOWFUNCS		include WindowFuncs in output list
570  *		PVC_RECURSE_WINDOWFUNCS		recurse into WindowFunc arguments
571  *		neither flag				throw error if WindowFunc found
572  *	  Vars within a WindowFunc's expression are included in the result only
573  *	  when PVC_RECURSE_WINDOWFUNCS is specified.
574  *
575  *	  PlaceHolderVars are handled according to these bits in 'flags':
576  *		PVC_INCLUDE_PLACEHOLDERS	include PlaceHolderVars in output list
577  *		PVC_RECURSE_PLACEHOLDERS	recurse into PlaceHolderVar arguments
578  *		neither flag				throw error if PlaceHolderVar found
579  *	  Vars within a PHV's expression are included in the result only
580  *	  when PVC_RECURSE_PLACEHOLDERS is specified.
581  *
582  *	  GroupingFuncs are treated mostly like Aggrefs, and so do not need
583  *	  their own flag bits.
584  *
585  *	  CurrentOfExpr nodes are ignored in all cases.
586  *
587  *	  Upper-level vars (with varlevelsup > 0) should not be seen here,
588  *	  likewise for upper-level Aggrefs and PlaceHolderVars.
589  *
590  *	  Returns list of nodes found.  Note the nodes themselves are not
591  *	  copied, only referenced.
592  *
593  * Does not examine subqueries, therefore must only be used after reduction
594  * of sublinks to subplans!
595  */
596 List *
pull_var_clause(Node * node,int flags)597 pull_var_clause(Node *node, int flags)
598 {
599 	pull_var_clause_context context;
600 
601 	/* Assert that caller has not specified inconsistent flags */
602 	Assert((flags & (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES))
603 		   != (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES));
604 	Assert((flags & (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS))
605 		   != (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS));
606 	Assert((flags & (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS))
607 		   != (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS));
608 
609 	context.varlist = NIL;
610 	context.flags = flags;
611 
612 	pull_var_clause_walker(node, &context);
613 	return context.varlist;
614 }
615 
616 static bool
pull_var_clause_walker(Node * node,pull_var_clause_context * context)617 pull_var_clause_walker(Node *node, pull_var_clause_context *context)
618 {
619 	if (node == NULL)
620 		return false;
621 	if (IsA(node, Var))
622 	{
623 		if (((Var *) node)->varlevelsup != 0)
624 			elog(ERROR, "Upper-level Var found where not expected");
625 		context->varlist = lappend(context->varlist, node);
626 		return false;
627 	}
628 	else if (IsA(node, Aggref))
629 	{
630 		if (((Aggref *) node)->agglevelsup != 0)
631 			elog(ERROR, "Upper-level Aggref found where not expected");
632 		if (context->flags & PVC_INCLUDE_AGGREGATES)
633 		{
634 			context->varlist = lappend(context->varlist, node);
635 			/* we do NOT descend into the contained expression */
636 			return false;
637 		}
638 		else if (context->flags & PVC_RECURSE_AGGREGATES)
639 		{
640 			/* fall through to recurse into the aggregate's arguments */
641 		}
642 		else
643 			elog(ERROR, "Aggref found where not expected");
644 	}
645 	else if (IsA(node, GroupingFunc))
646 	{
647 		if (((GroupingFunc *) node)->agglevelsup != 0)
648 			elog(ERROR, "Upper-level GROUPING found where not expected");
649 		if (context->flags & PVC_INCLUDE_AGGREGATES)
650 		{
651 			context->varlist = lappend(context->varlist, node);
652 			/* we do NOT descend into the contained expression */
653 			return false;
654 		}
655 		else if (context->flags & PVC_RECURSE_AGGREGATES)
656 		{
657 			/*
658 			 * We do NOT descend into the contained expression, even if the
659 			 * caller asked for it, because we never actually evaluate it -
660 			 * the result is driven entirely off the associated GROUP BY
661 			 * clause, so we never need to extract the actual Vars here.
662 			 */
663 			return false;
664 		}
665 		else
666 			elog(ERROR, "GROUPING found where not expected");
667 	}
668 	else if (IsA(node, WindowFunc))
669 	{
670 		/* WindowFuncs have no levelsup field to check ... */
671 		if (context->flags & PVC_INCLUDE_WINDOWFUNCS)
672 		{
673 			context->varlist = lappend(context->varlist, node);
674 			/* we do NOT descend into the contained expressions */
675 			return false;
676 		}
677 		else if (context->flags & PVC_RECURSE_WINDOWFUNCS)
678 		{
679 			/* fall through to recurse into the windowfunc's arguments */
680 		}
681 		else
682 			elog(ERROR, "WindowFunc found where not expected");
683 	}
684 	else if (IsA(node, PlaceHolderVar))
685 	{
686 		if (((PlaceHolderVar *) node)->phlevelsup != 0)
687 			elog(ERROR, "Upper-level PlaceHolderVar found where not expected");
688 		if (context->flags & PVC_INCLUDE_PLACEHOLDERS)
689 		{
690 			context->varlist = lappend(context->varlist, node);
691 			/* we do NOT descend into the contained expression */
692 			return false;
693 		}
694 		else if (context->flags & PVC_RECURSE_PLACEHOLDERS)
695 		{
696 			/* fall through to recurse into the placeholder's expression */
697 		}
698 		else
699 			elog(ERROR, "PlaceHolderVar found where not expected");
700 	}
701 	return expression_tree_walker(node, pull_var_clause_walker,
702 								  (void *) context);
703 }
704 
705 
706 /*
707  * flatten_join_alias_vars
708  *	  Replace Vars that reference JOIN outputs with references to the original
709  *	  relation variables instead.  This allows quals involving such vars to be
710  *	  pushed down.  Whole-row Vars that reference JOIN relations are expanded
711  *	  into RowExpr constructs that name the individual output Vars.  This
712  *	  is necessary since we will not scan the JOIN as a base relation, which
713  *	  is the only way that the executor can directly handle whole-row Vars.
714  *
715  * This also adjusts relid sets found in some expression node types to
716  * substitute the contained base rels for any join relid.
717  *
718  * If a JOIN contains sub-selects that have been flattened, its join alias
719  * entries might now be arbitrary expressions, not just Vars.  This affects
720  * this function in one important way: we might find ourselves inserting
721  * SubLink expressions into subqueries, and we must make sure that their
722  * Query.hasSubLinks fields get set to true if so.  If there are any
723  * SubLinks in the join alias lists, the outer Query should already have
724  * hasSubLinks = true, so this is only relevant to un-flattened subqueries.
725  *
726  * NOTE: this is used on not-yet-planned expressions.  We do not expect it
727  * to be applied directly to the whole Query, so if we see a Query to start
728  * with, we do want to increment sublevels_up (this occurs for LATERAL
729  * subqueries).
730  */
731 Node *
flatten_join_alias_vars(Query * query,Node * node)732 flatten_join_alias_vars(Query *query, Node *node)
733 {
734 	flatten_join_alias_vars_context context;
735 
736 	context.query = query;
737 	context.sublevels_up = 0;
738 	/* flag whether join aliases could possibly contain SubLinks */
739 	context.possible_sublink = query->hasSubLinks;
740 	/* if hasSubLinks is already true, no need to work hard */
741 	context.inserted_sublink = query->hasSubLinks;
742 
743 	return flatten_join_alias_vars_mutator(node, &context);
744 }
745 
746 static Node *
flatten_join_alias_vars_mutator(Node * node,flatten_join_alias_vars_context * context)747 flatten_join_alias_vars_mutator(Node *node,
748 								flatten_join_alias_vars_context *context)
749 {
750 	if (node == NULL)
751 		return NULL;
752 	if (IsA(node, Var))
753 	{
754 		Var		   *var = (Var *) node;
755 		RangeTblEntry *rte;
756 		Node	   *newvar;
757 
758 		/* No change unless Var belongs to a JOIN of the target level */
759 		if (var->varlevelsup != context->sublevels_up)
760 			return node;		/* no need to copy, really */
761 		rte = rt_fetch(var->varno, context->query->rtable);
762 		if (rte->rtekind != RTE_JOIN)
763 			return node;
764 		if (var->varattno == InvalidAttrNumber)
765 		{
766 			/* Must expand whole-row reference */
767 			RowExpr    *rowexpr;
768 			List	   *fields = NIL;
769 			List	   *colnames = NIL;
770 			AttrNumber	attnum;
771 			ListCell   *lv;
772 			ListCell   *ln;
773 
774 			attnum = 0;
775 			Assert(list_length(rte->joinaliasvars) == list_length(rte->eref->colnames));
776 			forboth(lv, rte->joinaliasvars, ln, rte->eref->colnames)
777 			{
778 				newvar = (Node *) lfirst(lv);
779 				attnum++;
780 				/* Ignore dropped columns */
781 				if (newvar == NULL)
782 					continue;
783 				newvar = copyObject(newvar);
784 
785 				/*
786 				 * If we are expanding an alias carried down from an upper
787 				 * query, must adjust its varlevelsup fields.
788 				 */
789 				if (context->sublevels_up != 0)
790 					IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
791 				/* Preserve original Var's location, if possible */
792 				if (IsA(newvar, Var))
793 					((Var *) newvar)->location = var->location;
794 				/* Recurse in case join input is itself a join */
795 				/* (also takes care of setting inserted_sublink if needed) */
796 				newvar = flatten_join_alias_vars_mutator(newvar, context);
797 				fields = lappend(fields, newvar);
798 				/* We need the names of non-dropped columns, too */
799 				colnames = lappend(colnames, copyObject((Node *) lfirst(ln)));
800 			}
801 			rowexpr = makeNode(RowExpr);
802 			rowexpr->args = fields;
803 			rowexpr->row_typeid = var->vartype;
804 			rowexpr->row_format = COERCE_IMPLICIT_CAST;
805 			rowexpr->colnames = colnames;
806 			rowexpr->location = var->location;
807 
808 			return (Node *) rowexpr;
809 		}
810 
811 		/* Expand join alias reference */
812 		Assert(var->varattno > 0);
813 		newvar = (Node *) list_nth(rte->joinaliasvars, var->varattno - 1);
814 		Assert(newvar != NULL);
815 		newvar = copyObject(newvar);
816 
817 		/*
818 		 * If we are expanding an alias carried down from an upper query, must
819 		 * adjust its varlevelsup fields.
820 		 */
821 		if (context->sublevels_up != 0)
822 			IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
823 
824 		/* Preserve original Var's location, if possible */
825 		if (IsA(newvar, Var))
826 			((Var *) newvar)->location = var->location;
827 
828 		/* Recurse in case join input is itself a join */
829 		newvar = flatten_join_alias_vars_mutator(newvar, context);
830 
831 		/* Detect if we are adding a sublink to query */
832 		if (context->possible_sublink && !context->inserted_sublink)
833 			context->inserted_sublink = checkExprHasSubLink(newvar);
834 
835 		return newvar;
836 	}
837 	if (IsA(node, PlaceHolderVar))
838 	{
839 		/* Copy the PlaceHolderVar node with correct mutation of subnodes */
840 		PlaceHolderVar *phv;
841 
842 		phv = (PlaceHolderVar *) expression_tree_mutator(node,
843 														 flatten_join_alias_vars_mutator,
844 														 (void *) context);
845 		/* now fix PlaceHolderVar's relid sets */
846 		if (phv->phlevelsup == context->sublevels_up)
847 		{
848 			phv->phrels = alias_relid_set(context->query,
849 										  phv->phrels);
850 		}
851 		return (Node *) phv;
852 	}
853 
854 	if (IsA(node, Query))
855 	{
856 		/* Recurse into RTE subquery or not-yet-planned sublink subquery */
857 		Query	   *newnode;
858 		bool		save_inserted_sublink;
859 
860 		context->sublevels_up++;
861 		save_inserted_sublink = context->inserted_sublink;
862 		context->inserted_sublink = ((Query *) node)->hasSubLinks;
863 		newnode = query_tree_mutator((Query *) node,
864 									 flatten_join_alias_vars_mutator,
865 									 (void *) context,
866 									 QTW_IGNORE_JOINALIASES);
867 		newnode->hasSubLinks |= context->inserted_sublink;
868 		context->inserted_sublink = save_inserted_sublink;
869 		context->sublevels_up--;
870 		return (Node *) newnode;
871 	}
872 	/* Already-planned tree not supported */
873 	Assert(!IsA(node, SubPlan));
874 	/* Shouldn't need to handle these planner auxiliary nodes here */
875 	Assert(!IsA(node, SpecialJoinInfo));
876 	Assert(!IsA(node, PlaceHolderInfo));
877 	Assert(!IsA(node, MinMaxAggInfo));
878 
879 	return expression_tree_mutator(node, flatten_join_alias_vars_mutator,
880 								   (void *) context);
881 }
882 
883 /*
884  * alias_relid_set: in a set of RT indexes, replace joins by their
885  * underlying base relids
886  */
887 static Relids
alias_relid_set(Query * query,Relids relids)888 alias_relid_set(Query *query, Relids relids)
889 {
890 	Relids		result = NULL;
891 	int			rtindex;
892 
893 	rtindex = -1;
894 	while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
895 	{
896 		RangeTblEntry *rte = rt_fetch(rtindex, query->rtable);
897 
898 		if (rte->rtekind == RTE_JOIN)
899 			result = bms_join(result, get_relids_for_join(query, rtindex));
900 		else
901 			result = bms_add_member(result, rtindex);
902 	}
903 	return result;
904 }
905