1 /*-------------------------------------------------------------------------
2  *
3  * subselect.c
4  *	  Planning routines for subselects.
5  *
6  * This module deals with SubLinks and CTEs, but not subquery RTEs (i.e.,
7  * not sub-SELECT-in-FROM cases).
8  *
9  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  * IDENTIFICATION
13  *	  src/backend/optimizer/plan/subselect.c
14  *
15  *-------------------------------------------------------------------------
16  */
17 #include "postgres.h"
18 
19 #include "access/htup_details.h"
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/cost.h"
28 #include "optimizer/paramassign.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/prep.h"
33 #include "optimizer/subselect.h"
34 #include "optimizer/var.h"
35 #include "parser/parse_relation.h"
36 #include "rewrite/rewriteManip.h"
37 #include "utils/builtins.h"
38 #include "utils/lsyscache.h"
39 #include "utils/syscache.h"
40 
41 
42 typedef struct convert_testexpr_context
43 {
44 	PlannerInfo *root;
45 	List	   *subst_nodes;	/* Nodes to substitute for Params */
46 } convert_testexpr_context;
47 
48 typedef struct process_sublinks_context
49 {
50 	PlannerInfo *root;
51 	bool		isTopQual;
52 } process_sublinks_context;
53 
54 typedef struct finalize_primnode_context
55 {
56 	PlannerInfo *root;
57 	Bitmapset  *paramids;		/* Non-local PARAM_EXEC paramids found */
58 } finalize_primnode_context;
59 
60 
61 static Node *build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
62 			  List *plan_params,
63 			  SubLinkType subLinkType, int subLinkId,
64 			  Node *testexpr, List *testexpr_paramids,
65 			  bool unknownEqFalse);
66 static List *generate_subquery_params(PlannerInfo *root, List *tlist,
67 						 List **paramIds);
68 static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
69 					   Index varno);
70 static Node *convert_testexpr(PlannerInfo *root,
71 				 Node *testexpr,
72 				 List *subst_nodes);
73 static Node *convert_testexpr_mutator(Node *node,
74 						 convert_testexpr_context *context);
75 static bool subplan_is_hashable(Plan *plan);
76 static bool testexpr_is_hashable(Node *testexpr, List *param_ids);
77 static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids);
78 static bool hash_ok_operator(OpExpr *expr);
79 static bool simplify_EXISTS_query(PlannerInfo *root, Query *query);
80 static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
81 					  Node **testexpr, List **paramIds);
82 static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
83 static Node *process_sublinks_mutator(Node *node,
84 						 process_sublinks_context *context);
85 static Bitmapset *finalize_plan(PlannerInfo *root,
86 			  Plan *plan,
87 			  int gather_param,
88 			  Bitmapset *valid_params,
89 			  Bitmapset *scan_params);
90 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
91 static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context);
92 
93 
94 /*
95  * Assign a (nonnegative) PARAM_EXEC ID for a special parameter (one that
96  * is not actually used to carry a value at runtime).  Such parameters are
97  * used for special runtime signaling purposes, such as connecting a
98  * recursive union node to its worktable scan node or forcing plan
99  * re-evaluation within the EvalPlanQual mechanism.  No actual Param node
100  * exists with this ID, however.
101  *
102  * XXX deprecated: use assign_special_exec_param directly, instead.  We are
103  * keeping this in v11 and below only to avoid API breaks.
104  */
105 int
SS_assign_special_param(PlannerInfo * root)106 SS_assign_special_param(PlannerInfo *root)
107 {
108 	return assign_special_exec_param(root);
109 }
110 
111 /*
112  * Get the datatype/typmod/collation of the first column of the plan's output.
113  *
114  * This information is stored for ARRAY_SUBLINK execution and for
115  * exprType()/exprTypmod()/exprCollation(), which have no way to get at the
116  * plan associated with a SubPlan node.  We really only need the info for
117  * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it
118  * always.
119  */
120 static void
get_first_col_type(Plan * plan,Oid * coltype,int32 * coltypmod,Oid * colcollation)121 get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
122 				   Oid *colcollation)
123 {
124 	/* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
125 	if (plan->targetlist)
126 	{
127 		TargetEntry *tent = linitial_node(TargetEntry, plan->targetlist);
128 
129 		if (!tent->resjunk)
130 		{
131 			*coltype = exprType((Node *) tent->expr);
132 			*coltypmod = exprTypmod((Node *) tent->expr);
133 			*colcollation = exprCollation((Node *) tent->expr);
134 			return;
135 		}
136 	}
137 	*coltype = VOIDOID;
138 	*coltypmod = -1;
139 	*colcollation = InvalidOid;
140 }
141 
142 /*
143  * Convert a SubLink (as created by the parser) into a SubPlan.
144  *
145  * We are given the SubLink's contained query, type, ID, and testexpr.  We are
146  * also told if this expression appears at top level of a WHERE/HAVING qual.
147  *
148  * Note: we assume that the testexpr has been AND/OR flattened (actually,
149  * it's been through eval_const_expressions), but not converted to
150  * implicit-AND form; and any SubLinks in it should already have been
151  * converted to SubPlans.  The subquery is as yet untouched, however.
152  *
153  * The result is whatever we need to substitute in place of the SubLink node
154  * in the executable expression.  If we're going to do the subplan as a
155  * regular subplan, this will be the constructed SubPlan node.  If we're going
156  * to do the subplan as an InitPlan, the SubPlan node instead goes into
157  * root->init_plans, and what we return here is an expression tree
158  * representing the InitPlan's result: usually just a Param node representing
159  * a single scalar result, but possibly a row comparison tree containing
160  * multiple Param nodes, or for a MULTIEXPR subquery a simple NULL constant
161  * (since the real output Params are elsewhere in the tree, and the MULTIEXPR
162  * subquery itself is in a resjunk tlist entry whose value is uninteresting).
163  */
164 static Node *
make_subplan(PlannerInfo * root,Query * orig_subquery,SubLinkType subLinkType,int subLinkId,Node * testexpr,bool isTopQual)165 make_subplan(PlannerInfo *root, Query *orig_subquery,
166 			 SubLinkType subLinkType, int subLinkId,
167 			 Node *testexpr, bool isTopQual)
168 {
169 	Query	   *subquery;
170 	bool		simple_exists = false;
171 	double		tuple_fraction;
172 	PlannerInfo *subroot;
173 	RelOptInfo *final_rel;
174 	Path	   *best_path;
175 	Plan	   *plan;
176 	List	   *plan_params;
177 	Node	   *result;
178 
179 	/*
180 	 * Copy the source Query node.  This is a quick and dirty kluge to resolve
181 	 * the fact that the parser can generate trees with multiple links to the
182 	 * same sub-Query node, but the planner wants to scribble on the Query.
183 	 * Try to clean this up when we do querytree redesign...
184 	 */
185 	subquery = copyObject(orig_subquery);
186 
187 	/*
188 	 * If it's an EXISTS subplan, we might be able to simplify it.
189 	 */
190 	if (subLinkType == EXISTS_SUBLINK)
191 		simple_exists = simplify_EXISTS_query(root, subquery);
192 
193 	/*
194 	 * For an EXISTS subplan, tell lower-level planner to expect that only the
195 	 * first tuple will be retrieved.  For ALL and ANY subplans, we will be
196 	 * able to stop evaluating if the test condition fails or matches, so very
197 	 * often not all the tuples will be retrieved; for lack of a better idea,
198 	 * specify 50% retrieval.  For EXPR, MULTIEXPR, and ROWCOMPARE subplans,
199 	 * use default behavior (we're only expecting one row out, anyway).
200 	 *
201 	 * NOTE: if you change these numbers, also change cost_subplan() in
202 	 * path/costsize.c.
203 	 *
204 	 * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
205 	 * its output.  In that case it would've been better to specify full
206 	 * retrieval.  At present, however, we can only check hashability after
207 	 * we've made the subplan :-(.  (Determining whether it'll fit in work_mem
208 	 * is the really hard part.)  Therefore, we don't want to be too
209 	 * optimistic about the percentage of tuples retrieved, for fear of
210 	 * selecting a plan that's bad for the materialization case.
211 	 */
212 	if (subLinkType == EXISTS_SUBLINK)
213 		tuple_fraction = 1.0;	/* just like a LIMIT 1 */
214 	else if (subLinkType == ALL_SUBLINK ||
215 			 subLinkType == ANY_SUBLINK)
216 		tuple_fraction = 0.5;	/* 50% */
217 	else
218 		tuple_fraction = 0.0;	/* default behavior */
219 
220 	/* plan_params should not be in use in current query level */
221 	Assert(root->plan_params == NIL);
222 
223 	/* Generate Paths for the subquery */
224 	subroot = subquery_planner(root->glob, subquery,
225 							   root,
226 							   false, tuple_fraction);
227 
228 	/* Isolate the params needed by this specific subplan */
229 	plan_params = root->plan_params;
230 	root->plan_params = NIL;
231 
232 	/*
233 	 * Select best Path and turn it into a Plan.  At least for now, there
234 	 * seems no reason to postpone doing that.
235 	 */
236 	final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
237 	best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
238 
239 	plan = create_plan(subroot, best_path);
240 
241 	/* And convert to SubPlan or InitPlan format. */
242 	result = build_subplan(root, plan, subroot, plan_params,
243 						   subLinkType, subLinkId,
244 						   testexpr, NIL, isTopQual);
245 
246 	/*
247 	 * If it's a correlated EXISTS with an unimportant targetlist, we might be
248 	 * able to transform it to the equivalent of an IN and then implement it
249 	 * by hashing.  We don't have enough information yet to tell which way is
250 	 * likely to be better (it depends on the expected number of executions of
251 	 * the EXISTS qual, and we are much too early in planning the outer query
252 	 * to be able to guess that).  So we generate both plans, if possible, and
253 	 * leave it to the executor to decide which to use.
254 	 */
255 	if (simple_exists && IsA(result, SubPlan))
256 	{
257 		Node	   *newtestexpr;
258 		List	   *paramIds;
259 
260 		/* Make a second copy of the original subquery */
261 		subquery = copyObject(orig_subquery);
262 		/* and re-simplify */
263 		simple_exists = simplify_EXISTS_query(root, subquery);
264 		Assert(simple_exists);
265 		/* See if it can be converted to an ANY query */
266 		subquery = convert_EXISTS_to_ANY(root, subquery,
267 										 &newtestexpr, &paramIds);
268 		if (subquery)
269 		{
270 			/* Generate Paths for the ANY subquery; we'll need all rows */
271 			subroot = subquery_planner(root->glob, subquery,
272 									   root,
273 									   false, 0.0);
274 
275 			/* Isolate the params needed by this specific subplan */
276 			plan_params = root->plan_params;
277 			root->plan_params = NIL;
278 
279 			/* Select best Path and turn it into a Plan */
280 			final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
281 			best_path = final_rel->cheapest_total_path;
282 
283 			plan = create_plan(subroot, best_path);
284 
285 			/* Now we can check if it'll fit in work_mem */
286 			/* XXX can we check this at the Path stage? */
287 			if (subplan_is_hashable(plan))
288 			{
289 				SubPlan    *hashplan;
290 				AlternativeSubPlan *asplan;
291 
292 				/* OK, convert to SubPlan format. */
293 				hashplan = castNode(SubPlan,
294 									build_subplan(root, plan, subroot,
295 												  plan_params,
296 												  ANY_SUBLINK, 0,
297 												  newtestexpr,
298 												  paramIds,
299 												  true));
300 				/* Check we got what we expected */
301 				Assert(hashplan->parParam == NIL);
302 				Assert(hashplan->useHashTable);
303 
304 				/* Leave it to the executor to decide which plan to use */
305 				asplan = makeNode(AlternativeSubPlan);
306 				asplan->subplans = list_make2(result, hashplan);
307 				result = (Node *) asplan;
308 			}
309 		}
310 	}
311 
312 	return result;
313 }
314 
315 /*
316  * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
317  *
318  * Returns either the SubPlan, or a replacement expression if we decide to
319  * make it an InitPlan, as explained in the comments for make_subplan.
320  */
321 static Node *
build_subplan(PlannerInfo * root,Plan * plan,PlannerInfo * subroot,List * plan_params,SubLinkType subLinkType,int subLinkId,Node * testexpr,List * testexpr_paramids,bool unknownEqFalse)322 build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
323 			  List *plan_params,
324 			  SubLinkType subLinkType, int subLinkId,
325 			  Node *testexpr, List *testexpr_paramids,
326 			  bool unknownEqFalse)
327 {
328 	Node	   *result;
329 	SubPlan    *splan;
330 	bool		isInitPlan;
331 	ListCell   *lc;
332 
333 	/*
334 	 * Initialize the SubPlan node.  Note plan_id, plan_name, and cost fields
335 	 * are set further down.
336 	 */
337 	splan = makeNode(SubPlan);
338 	splan->subLinkType = subLinkType;
339 	splan->testexpr = NULL;
340 	splan->paramIds = NIL;
341 	get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
342 					   &splan->firstColCollation);
343 	splan->useHashTable = false;
344 	splan->unknownEqFalse = unknownEqFalse;
345 	splan->parallel_safe = plan->parallel_safe;
346 	splan->setParam = NIL;
347 	splan->parParam = NIL;
348 	splan->args = NIL;
349 
350 	/*
351 	 * Make parParam and args lists of param IDs and expressions that current
352 	 * query level will pass to this child plan.
353 	 */
354 	foreach(lc, plan_params)
355 	{
356 		PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
357 		Node	   *arg = pitem->item;
358 
359 		/*
360 		 * The Var, PlaceHolderVar, or Aggref has already been adjusted to
361 		 * have the correct varlevelsup, phlevelsup, or agglevelsup.
362 		 *
363 		 * If it's a PlaceHolderVar or Aggref, its arguments might contain
364 		 * SubLinks, which have not yet been processed (see the comments for
365 		 * SS_replace_correlation_vars).  Do that now.
366 		 */
367 		if (IsA(arg, PlaceHolderVar) ||
368 			IsA(arg, Aggref))
369 			arg = SS_process_sublinks(root, arg, false);
370 
371 		splan->parParam = lappend_int(splan->parParam, pitem->paramId);
372 		splan->args = lappend(splan->args, arg);
373 	}
374 
375 	/*
376 	 * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
377 	 * ROWCOMPARE, or MULTIEXPR types can be used as initPlans.  For EXISTS,
378 	 * EXPR, or ARRAY, we return a Param referring to the result of evaluating
379 	 * the initPlan.  For ROWCOMPARE, we must modify the testexpr tree to
380 	 * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
381 	 * by the parser, and then return that tree.  For MULTIEXPR, we return a
382 	 * null constant: the resjunk targetlist item containing the SubLink does
383 	 * not need to return anything useful, since the referencing Params are
384 	 * elsewhere.
385 	 */
386 	if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
387 	{
388 		Param	   *prm;
389 
390 		Assert(testexpr == NULL);
391 		prm = generate_new_exec_param(root, BOOLOID, -1, InvalidOid);
392 		splan->setParam = list_make1_int(prm->paramid);
393 		isInitPlan = true;
394 		result = (Node *) prm;
395 	}
396 	else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
397 	{
398 		TargetEntry *te = linitial(plan->targetlist);
399 		Param	   *prm;
400 
401 		Assert(!te->resjunk);
402 		Assert(testexpr == NULL);
403 		prm = generate_new_exec_param(root,
404 									  exprType((Node *) te->expr),
405 									  exprTypmod((Node *) te->expr),
406 									  exprCollation((Node *) te->expr));
407 		splan->setParam = list_make1_int(prm->paramid);
408 		isInitPlan = true;
409 		result = (Node *) prm;
410 	}
411 	else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
412 	{
413 		TargetEntry *te = linitial(plan->targetlist);
414 		Oid			arraytype;
415 		Param	   *prm;
416 
417 		Assert(!te->resjunk);
418 		Assert(testexpr == NULL);
419 		arraytype = get_promoted_array_type(exprType((Node *) te->expr));
420 		if (!OidIsValid(arraytype))
421 			elog(ERROR, "could not find array type for datatype %s",
422 				 format_type_be(exprType((Node *) te->expr)));
423 		prm = generate_new_exec_param(root,
424 									  arraytype,
425 									  exprTypmod((Node *) te->expr),
426 									  exprCollation((Node *) te->expr));
427 		splan->setParam = list_make1_int(prm->paramid);
428 		isInitPlan = true;
429 		result = (Node *) prm;
430 	}
431 	else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
432 	{
433 		/* Adjust the Params */
434 		List	   *params;
435 
436 		Assert(testexpr != NULL);
437 		params = generate_subquery_params(root,
438 										  plan->targetlist,
439 										  &splan->paramIds);
440 		result = convert_testexpr(root,
441 								  testexpr,
442 								  params);
443 		splan->setParam = list_copy(splan->paramIds);
444 		isInitPlan = true;
445 
446 		/*
447 		 * The executable expression is returned to become part of the outer
448 		 * plan's expression tree; it is not kept in the initplan node.
449 		 */
450 	}
451 	else if (subLinkType == MULTIEXPR_SUBLINK)
452 	{
453 		/*
454 		 * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
455 		 * for each output column.
456 		 */
457 		List	   *params;
458 
459 		Assert(testexpr == NULL);
460 		params = generate_subquery_params(root,
461 										  plan->targetlist,
462 										  &splan->setParam);
463 
464 		/*
465 		 * Save the list of replacement Params in the n'th cell of
466 		 * root->multiexpr_params; setrefs.c will use it to replace
467 		 * PARAM_MULTIEXPR Params.
468 		 */
469 		while (list_length(root->multiexpr_params) < subLinkId)
470 			root->multiexpr_params = lappend(root->multiexpr_params, NIL);
471 		lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
472 		Assert(lfirst(lc) == NIL);
473 		lfirst(lc) = params;
474 
475 		/* It can be an initplan if there are no parParams. */
476 		if (splan->parParam == NIL)
477 		{
478 			isInitPlan = true;
479 			result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
480 		}
481 		else
482 		{
483 			isInitPlan = false;
484 			result = (Node *) splan;
485 		}
486 	}
487 	else
488 	{
489 		/*
490 		 * Adjust the Params in the testexpr, unless caller already took care
491 		 * of it (as indicated by passing a list of Param IDs).
492 		 */
493 		if (testexpr && testexpr_paramids == NIL)
494 		{
495 			List	   *params;
496 
497 			params = generate_subquery_params(root,
498 											  plan->targetlist,
499 											  &splan->paramIds);
500 			splan->testexpr = convert_testexpr(root,
501 											   testexpr,
502 											   params);
503 		}
504 		else
505 		{
506 			splan->testexpr = testexpr;
507 			splan->paramIds = testexpr_paramids;
508 		}
509 
510 		/*
511 		 * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
512 		 * initPlans, even when they are uncorrelated or undirect correlated,
513 		 * because we need to scan the output of the subplan for each outer
514 		 * tuple.  But if it's a not-direct-correlated IN (= ANY) test, we
515 		 * might be able to use a hashtable to avoid comparing all the tuples.
516 		 */
517 		if (subLinkType == ANY_SUBLINK &&
518 			splan->parParam == NIL &&
519 			subplan_is_hashable(plan) &&
520 			testexpr_is_hashable(splan->testexpr, splan->paramIds))
521 			splan->useHashTable = true;
522 
523 		/*
524 		 * Otherwise, we have the option to tack a Material node onto the top
525 		 * of the subplan, to reduce the cost of reading it repeatedly.  This
526 		 * is pointless for a direct-correlated subplan, since we'd have to
527 		 * recompute its results each time anyway.  For uncorrelated/undirect
528 		 * correlated subplans, we add Material unless the subplan's top plan
529 		 * node would materialize its output anyway.  Also, if enable_material
530 		 * is false, then the user does not want us to materialize anything
531 		 * unnecessarily, so we don't.
532 		 */
533 		else if (splan->parParam == NIL && enable_material &&
534 				 !ExecMaterializesOutput(nodeTag(plan)))
535 			plan = materialize_finished_plan(plan);
536 
537 		result = (Node *) splan;
538 		isInitPlan = false;
539 	}
540 
541 	/*
542 	 * Add the subplan and its PlannerInfo to the global lists.
543 	 */
544 	root->glob->subplans = lappend(root->glob->subplans, plan);
545 	root->glob->subroots = lappend(root->glob->subroots, subroot);
546 	splan->plan_id = list_length(root->glob->subplans);
547 
548 	if (isInitPlan)
549 		root->init_plans = lappend(root->init_plans, splan);
550 
551 	/*
552 	 * A parameterless subplan (not initplan) should be prepared to handle
553 	 * REWIND efficiently.  If it has direct parameters then there's no point
554 	 * since it'll be reset on each scan anyway; and if it's an initplan then
555 	 * there's no point since it won't get re-run without parameter changes
556 	 * anyway.  The input of a hashed subplan doesn't need REWIND either.
557 	 */
558 	if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
559 		root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
560 												   splan->plan_id);
561 
562 	/* Label the subplan for EXPLAIN purposes */
563 	splan->plan_name = palloc(32 + 12 * list_length(splan->setParam));
564 	sprintf(splan->plan_name, "%s %d",
565 			isInitPlan ? "InitPlan" : "SubPlan",
566 			splan->plan_id);
567 	if (splan->setParam)
568 	{
569 		char	   *ptr = splan->plan_name + strlen(splan->plan_name);
570 
571 		ptr += sprintf(ptr, " (returns ");
572 		foreach(lc, splan->setParam)
573 		{
574 			ptr += sprintf(ptr, "$%d%s",
575 						   lfirst_int(lc),
576 						   lnext(lc) ? "," : ")");
577 		}
578 	}
579 
580 	/* Lastly, fill in the cost estimates for use later */
581 	cost_subplan(root, splan, plan);
582 
583 	return result;
584 }
585 
586 /*
587  * generate_subquery_params: build a list of Params representing the output
588  * columns of a sublink's sub-select, given the sub-select's targetlist.
589  *
590  * We also return an integer list of the paramids of the Params.
591  */
592 static List *
generate_subquery_params(PlannerInfo * root,List * tlist,List ** paramIds)593 generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
594 {
595 	List	   *result;
596 	List	   *ids;
597 	ListCell   *lc;
598 
599 	result = ids = NIL;
600 	foreach(lc, tlist)
601 	{
602 		TargetEntry *tent = (TargetEntry *) lfirst(lc);
603 		Param	   *param;
604 
605 		if (tent->resjunk)
606 			continue;
607 
608 		param = generate_new_exec_param(root,
609 										exprType((Node *) tent->expr),
610 										exprTypmod((Node *) tent->expr),
611 										exprCollation((Node *) tent->expr));
612 		result = lappend(result, param);
613 		ids = lappend_int(ids, param->paramid);
614 	}
615 
616 	*paramIds = ids;
617 	return result;
618 }
619 
620 /*
621  * generate_subquery_vars: build a list of Vars representing the output
622  * columns of a sublink's sub-select, given the sub-select's targetlist.
623  * The Vars have the specified varno (RTE index).
624  */
625 static List *
generate_subquery_vars(PlannerInfo * root,List * tlist,Index varno)626 generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
627 {
628 	List	   *result;
629 	ListCell   *lc;
630 
631 	result = NIL;
632 	foreach(lc, tlist)
633 	{
634 		TargetEntry *tent = (TargetEntry *) lfirst(lc);
635 		Var		   *var;
636 
637 		if (tent->resjunk)
638 			continue;
639 
640 		var = makeVarFromTargetEntry(varno, tent);
641 		result = lappend(result, var);
642 	}
643 
644 	return result;
645 }
646 
647 /*
648  * convert_testexpr: convert the testexpr given by the parser into
649  * actually executable form.  This entails replacing PARAM_SUBLINK Params
650  * with Params or Vars representing the results of the sub-select.  The
651  * nodes to be substituted are passed in as the List result from
652  * generate_subquery_params or generate_subquery_vars.
653  */
654 static Node *
convert_testexpr(PlannerInfo * root,Node * testexpr,List * subst_nodes)655 convert_testexpr(PlannerInfo *root,
656 				 Node *testexpr,
657 				 List *subst_nodes)
658 {
659 	convert_testexpr_context context;
660 
661 	context.root = root;
662 	context.subst_nodes = subst_nodes;
663 	return convert_testexpr_mutator(testexpr, &context);
664 }
665 
666 static Node *
convert_testexpr_mutator(Node * node,convert_testexpr_context * context)667 convert_testexpr_mutator(Node *node,
668 						 convert_testexpr_context *context)
669 {
670 	if (node == NULL)
671 		return NULL;
672 	if (IsA(node, Param))
673 	{
674 		Param	   *param = (Param *) node;
675 
676 		if (param->paramkind == PARAM_SUBLINK)
677 		{
678 			if (param->paramid <= 0 ||
679 				param->paramid > list_length(context->subst_nodes))
680 				elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
681 
682 			/*
683 			 * We copy the list item to avoid having doubly-linked
684 			 * substructure in the modified parse tree.  This is probably
685 			 * unnecessary when it's a Param, but be safe.
686 			 */
687 			return (Node *) copyObject(list_nth(context->subst_nodes,
688 												param->paramid - 1));
689 		}
690 	}
691 	if (IsA(node, SubLink))
692 	{
693 		/*
694 		 * If we come across a nested SubLink, it is neither necessary nor
695 		 * correct to recurse into it: any PARAM_SUBLINKs we might find inside
696 		 * belong to the inner SubLink not the outer. So just return it as-is.
697 		 *
698 		 * This reasoning depends on the assumption that nothing will pull
699 		 * subexpressions into or out of the testexpr field of a SubLink, at
700 		 * least not without replacing PARAM_SUBLINKs first.  If we did want
701 		 * to do that we'd need to rethink the parser-output representation
702 		 * altogether, since currently PARAM_SUBLINKs are only unique per
703 		 * SubLink not globally across the query.  The whole point of
704 		 * replacing them with Vars or PARAM_EXEC nodes is to make them
705 		 * globally unique before they escape from the SubLink's testexpr.
706 		 *
707 		 * Note: this can't happen when called during SS_process_sublinks,
708 		 * because that recursively processes inner SubLinks first.  It can
709 		 * happen when called from convert_ANY_sublink_to_join, though.
710 		 */
711 		return node;
712 	}
713 	return expression_tree_mutator(node,
714 								   convert_testexpr_mutator,
715 								   (void *) context);
716 }
717 
718 /*
719  * subplan_is_hashable: can we implement an ANY subplan by hashing?
720  */
721 static bool
subplan_is_hashable(Plan * plan)722 subplan_is_hashable(Plan *plan)
723 {
724 	double		subquery_size;
725 
726 	/*
727 	 * The estimated size of the subquery result must fit in work_mem. (Note:
728 	 * we use heap tuple overhead here even though the tuples will actually be
729 	 * stored as MinimalTuples; this provides some fudge factor for hashtable
730 	 * overhead.)
731 	 */
732 	subquery_size = plan->plan_rows *
733 		(MAXALIGN(plan->plan_width) + MAXALIGN(SizeofHeapTupleHeader));
734 	if (subquery_size > work_mem * 1024L)
735 		return false;
736 
737 	return true;
738 }
739 
740 /*
741  * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
742  *
743  * To identify LHS vs RHS of the hash expression, we must be given the
744  * list of output Param IDs of the SubLink's subquery.
745  */
746 static bool
testexpr_is_hashable(Node * testexpr,List * param_ids)747 testexpr_is_hashable(Node *testexpr, List *param_ids)
748 {
749 	/*
750 	 * The testexpr must be a single OpExpr, or an AND-clause containing only
751 	 * OpExprs, each of which satisfy test_opexpr_is_hashable().
752 	 */
753 	if (testexpr && IsA(testexpr, OpExpr))
754 	{
755 		if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
756 			return true;
757 	}
758 	else if (and_clause(testexpr))
759 	{
760 		ListCell   *l;
761 
762 		foreach(l, ((BoolExpr *) testexpr)->args)
763 		{
764 			Node	   *andarg = (Node *) lfirst(l);
765 
766 			if (!IsA(andarg, OpExpr))
767 				return false;
768 			if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
769 				return false;
770 		}
771 		return true;
772 	}
773 
774 	return false;
775 }
776 
777 static bool
test_opexpr_is_hashable(OpExpr * testexpr,List * param_ids)778 test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
779 {
780 	/*
781 	 * The combining operator must be hashable and strict.  The need for
782 	 * hashability is obvious, since we want to use hashing.  Without
783 	 * strictness, behavior in the presence of nulls is too unpredictable.  We
784 	 * actually must assume even more than plain strictness: it can't yield
785 	 * NULL for non-null inputs, either (see nodeSubplan.c).  However, hash
786 	 * indexes and hash joins assume that too.
787 	 */
788 	if (!hash_ok_operator(testexpr))
789 		return false;
790 
791 	/*
792 	 * The left and right inputs must belong to the outer and inner queries
793 	 * respectively; hence Params that will be supplied by the subquery must
794 	 * not appear in the LHS, and Vars of the outer query must not appear in
795 	 * the RHS.  (Ordinarily, this must be true because of the way that the
796 	 * parser builds an ANY SubLink's testexpr ... but inlining of functions
797 	 * could have changed the expression's structure, so we have to check.
798 	 * Such cases do not occur often enough to be worth trying to optimize, so
799 	 * we don't worry about trying to commute the clause or anything like
800 	 * that; we just need to be sure not to build an invalid plan.)
801 	 */
802 	if (list_length(testexpr->args) != 2)
803 		return false;
804 	if (contain_exec_param((Node *) linitial(testexpr->args), param_ids))
805 		return false;
806 	if (contain_var_clause((Node *) lsecond(testexpr->args)))
807 		return false;
808 	return true;
809 }
810 
811 /*
812  * Check expression is hashable + strict
813  *
814  * We could use op_hashjoinable() and op_strict(), but do it like this to
815  * avoid a redundant cache lookup.
816  */
817 static bool
hash_ok_operator(OpExpr * expr)818 hash_ok_operator(OpExpr *expr)
819 {
820 	Oid			opid = expr->opno;
821 
822 	/* quick out if not a binary operator */
823 	if (list_length(expr->args) != 2)
824 		return false;
825 	if (opid == ARRAY_EQ_OP)
826 	{
827 		/* array_eq is strict, but must check input type to ensure hashable */
828 		/* XXX record_eq will need same treatment when it becomes hashable */
829 		Node	   *leftarg = linitial(expr->args);
830 
831 		return op_hashjoinable(opid, exprType(leftarg));
832 	}
833 	else
834 	{
835 		/* else must look up the operator properties */
836 		HeapTuple	tup;
837 		Form_pg_operator optup;
838 
839 		tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
840 		if (!HeapTupleIsValid(tup))
841 			elog(ERROR, "cache lookup failed for operator %u", opid);
842 		optup = (Form_pg_operator) GETSTRUCT(tup);
843 		if (!optup->oprcanhash || !func_strict(optup->oprcode))
844 		{
845 			ReleaseSysCache(tup);
846 			return false;
847 		}
848 		ReleaseSysCache(tup);
849 		return true;
850 	}
851 }
852 
853 
854 /*
855  * SS_process_ctes: process a query's WITH list
856  *
857  * We plan each interesting WITH item and convert it to an initplan.
858  * A side effect is to fill in root->cte_plan_ids with a list that
859  * parallels root->parse->cteList and provides the subplan ID for
860  * each CTE's initplan.
861  */
862 void
SS_process_ctes(PlannerInfo * root)863 SS_process_ctes(PlannerInfo *root)
864 {
865 	ListCell   *lc;
866 
867 	Assert(root->cte_plan_ids == NIL);
868 
869 	foreach(lc, root->parse->cteList)
870 	{
871 		CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
872 		CmdType		cmdType = ((Query *) cte->ctequery)->commandType;
873 		Query	   *subquery;
874 		PlannerInfo *subroot;
875 		RelOptInfo *final_rel;
876 		Path	   *best_path;
877 		Plan	   *plan;
878 		SubPlan    *splan;
879 		int			paramid;
880 
881 		/*
882 		 * Ignore SELECT CTEs that are not actually referenced anywhere.
883 		 */
884 		if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
885 		{
886 			/* Make a dummy entry in cte_plan_ids */
887 			root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
888 			continue;
889 		}
890 
891 		/*
892 		 * Copy the source Query node.  Probably not necessary, but let's keep
893 		 * this similar to make_subplan.
894 		 */
895 		subquery = (Query *) copyObject(cte->ctequery);
896 
897 		/* plan_params should not be in use in current query level */
898 		Assert(root->plan_params == NIL);
899 
900 		/*
901 		 * Generate Paths for the CTE query.  Always plan for full retrieval
902 		 * --- we don't have enough info to predict otherwise.
903 		 */
904 		subroot = subquery_planner(root->glob, subquery,
905 								   root,
906 								   cte->cterecursive, 0.0);
907 
908 		/*
909 		 * Since the current query level doesn't yet contain any RTEs, it
910 		 * should not be possible for the CTE to have requested parameters of
911 		 * this level.
912 		 */
913 		if (root->plan_params)
914 			elog(ERROR, "unexpected outer reference in CTE query");
915 
916 		/*
917 		 * Select best Path and turn it into a Plan.  At least for now, there
918 		 * seems no reason to postpone doing that.
919 		 */
920 		final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
921 		best_path = final_rel->cheapest_total_path;
922 
923 		plan = create_plan(subroot, best_path);
924 
925 		/*
926 		 * Make a SubPlan node for it.  This is just enough unlike
927 		 * build_subplan that we can't share code.
928 		 *
929 		 * Note plan_id, plan_name, and cost fields are set further down.
930 		 */
931 		splan = makeNode(SubPlan);
932 		splan->subLinkType = CTE_SUBLINK;
933 		splan->testexpr = NULL;
934 		splan->paramIds = NIL;
935 		get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
936 						   &splan->firstColCollation);
937 		splan->useHashTable = false;
938 		splan->unknownEqFalse = false;
939 
940 		/*
941 		 * CTE scans are not considered for parallelism (cf
942 		 * set_rel_consider_parallel), and even if they were, initPlans aren't
943 		 * parallel-safe.
944 		 */
945 		splan->parallel_safe = false;
946 		splan->setParam = NIL;
947 		splan->parParam = NIL;
948 		splan->args = NIL;
949 
950 		/*
951 		 * The node can't have any inputs (since it's an initplan), so the
952 		 * parParam and args lists remain empty.  (It could contain references
953 		 * to earlier CTEs' output param IDs, but CTE outputs are not
954 		 * propagated via the args list.)
955 		 */
956 
957 		/*
958 		 * Assign a param ID to represent the CTE's output.  No ordinary
959 		 * "evaluation" of this param slot ever happens, but we use the param
960 		 * ID for setParam/chgParam signaling just as if the CTE plan were
961 		 * returning a simple scalar output.  (Also, the executor abuses the
962 		 * ParamExecData slot for this param ID for communication among
963 		 * multiple CteScan nodes that might be scanning this CTE.)
964 		 */
965 		paramid = assign_special_exec_param(root);
966 		splan->setParam = list_make1_int(paramid);
967 
968 		/*
969 		 * Add the subplan and its PlannerInfo to the global lists.
970 		 */
971 		root->glob->subplans = lappend(root->glob->subplans, plan);
972 		root->glob->subroots = lappend(root->glob->subroots, subroot);
973 		splan->plan_id = list_length(root->glob->subplans);
974 
975 		root->init_plans = lappend(root->init_plans, splan);
976 
977 		root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
978 
979 		/* Label the subplan for EXPLAIN purposes */
980 		splan->plan_name = psprintf("CTE %s", cte->ctename);
981 
982 		/* Lastly, fill in the cost estimates for use later */
983 		cost_subplan(root, splan, plan);
984 	}
985 }
986 
987 /*
988  * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join
989  *
990  * The caller has found an ANY SubLink at the top level of one of the query's
991  * qual clauses, but has not checked the properties of the SubLink further.
992  * Decide whether it is appropriate to process this SubLink in join style.
993  * If so, form a JoinExpr and return it.  Return NULL if the SubLink cannot
994  * be converted to a join.
995  *
996  * The only non-obvious input parameter is available_rels: this is the set
997  * of query rels that can safely be referenced in the sublink expression.
998  * (We must restrict this to avoid changing the semantics when a sublink
999  * is present in an outer join's ON qual.)  The conversion must fail if
1000  * the converted qual would reference any but these parent-query relids.
1001  *
1002  * On success, the returned JoinExpr has larg = NULL and rarg = the jointree
1003  * item representing the pulled-up subquery.  The caller must set larg to
1004  * represent the relation(s) on the lefthand side of the new join, and insert
1005  * the JoinExpr into the upper query's jointree at an appropriate place
1006  * (typically, where the lefthand relation(s) had been).  Note that the
1007  * passed-in SubLink must also be removed from its original position in the
1008  * query quals, since the quals of the returned JoinExpr replace it.
1009  * (Notionally, we replace the SubLink with a constant TRUE, then elide the
1010  * redundant constant from the qual.)
1011  *
1012  * On success, the caller is also responsible for recursively applying
1013  * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr.
1014  * (On failure, there is no need to do anything, since pull_up_sublinks will
1015  * be applied when we recursively plan the sub-select.)
1016  *
1017  * Side effects of a successful conversion include adding the SubLink's
1018  * subselect to the query's rangetable, so that it can be referenced in
1019  * the JoinExpr's rarg.
1020  */
1021 JoinExpr *
convert_ANY_sublink_to_join(PlannerInfo * root,SubLink * sublink,Relids available_rels)1022 convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1023 							Relids available_rels)
1024 {
1025 	JoinExpr   *result;
1026 	Query	   *parse = root->parse;
1027 	Query	   *subselect = (Query *) sublink->subselect;
1028 	Relids		upper_varnos;
1029 	int			rtindex;
1030 	RangeTblEntry *rte;
1031 	RangeTblRef *rtr;
1032 	List	   *subquery_vars;
1033 	Node	   *quals;
1034 	ParseState *pstate;
1035 
1036 	Assert(sublink->subLinkType == ANY_SUBLINK);
1037 
1038 	/*
1039 	 * The sub-select must not refer to any Vars of the parent query. (Vars of
1040 	 * higher levels should be okay, though.)
1041 	 */
1042 	if (contain_vars_of_level((Node *) subselect, 1))
1043 		return NULL;
1044 
1045 	/*
1046 	 * The test expression must contain some Vars of the parent query, else
1047 	 * it's not gonna be a join.  (Note that it won't have Vars referring to
1048 	 * the subquery, rather Params.)
1049 	 */
1050 	upper_varnos = pull_varnos(sublink->testexpr);
1051 	if (bms_is_empty(upper_varnos))
1052 		return NULL;
1053 
1054 	/*
1055 	 * However, it can't refer to anything outside available_rels.
1056 	 */
1057 	if (!bms_is_subset(upper_varnos, available_rels))
1058 		return NULL;
1059 
1060 	/*
1061 	 * The combining operators and left-hand expressions mustn't be volatile.
1062 	 */
1063 	if (contain_volatile_functions(sublink->testexpr))
1064 		return NULL;
1065 
1066 	/* Create a dummy ParseState for addRangeTableEntryForSubquery */
1067 	pstate = make_parsestate(NULL);
1068 
1069 	/*
1070 	 * Okay, pull up the sub-select into upper range table.
1071 	 *
1072 	 * We rely here on the assumption that the outer query has no references
1073 	 * to the inner (necessarily true, other than the Vars that we build
1074 	 * below). Therefore this is a lot easier than what pull_up_subqueries has
1075 	 * to go through.
1076 	 */
1077 	rte = addRangeTableEntryForSubquery(pstate,
1078 										subselect,
1079 										makeAlias("ANY_subquery", NIL),
1080 										false,
1081 										false);
1082 	parse->rtable = lappend(parse->rtable, rte);
1083 	rtindex = list_length(parse->rtable);
1084 
1085 	/*
1086 	 * Form a RangeTblRef for the pulled-up sub-select.
1087 	 */
1088 	rtr = makeNode(RangeTblRef);
1089 	rtr->rtindex = rtindex;
1090 
1091 	/*
1092 	 * Build a list of Vars representing the subselect outputs.
1093 	 */
1094 	subquery_vars = generate_subquery_vars(root,
1095 										   subselect->targetList,
1096 										   rtindex);
1097 
1098 	/*
1099 	 * Build the new join's qual expression, replacing Params with these Vars.
1100 	 */
1101 	quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1102 
1103 	/*
1104 	 * And finally, build the JoinExpr node.
1105 	 */
1106 	result = makeNode(JoinExpr);
1107 	result->jointype = JOIN_SEMI;
1108 	result->isNatural = false;
1109 	result->larg = NULL;		/* caller must fill this in */
1110 	result->rarg = (Node *) rtr;
1111 	result->usingClause = NIL;
1112 	result->quals = quals;
1113 	result->alias = NULL;
1114 	result->rtindex = 0;		/* we don't need an RTE for it */
1115 
1116 	return result;
1117 }
1118 
1119 /*
1120  * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join
1121  *
1122  * The API of this function is identical to convert_ANY_sublink_to_join's,
1123  * except that we also support the case where the caller has found NOT EXISTS,
1124  * so we need an additional input parameter "under_not".
1125  */
1126 JoinExpr *
convert_EXISTS_sublink_to_join(PlannerInfo * root,SubLink * sublink,bool under_not,Relids available_rels)1127 convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1128 							   bool under_not, Relids available_rels)
1129 {
1130 	JoinExpr   *result;
1131 	Query	   *parse = root->parse;
1132 	Query	   *subselect = (Query *) sublink->subselect;
1133 	Node	   *whereClause;
1134 	int			rtoffset;
1135 	int			varno;
1136 	Relids		clause_varnos;
1137 	Relids		upper_varnos;
1138 
1139 	Assert(sublink->subLinkType == EXISTS_SUBLINK);
1140 
1141 	/*
1142 	 * Can't flatten if it contains WITH.  (We could arrange to pull up the
1143 	 * WITH into the parent query's cteList, but that risks changing the
1144 	 * semantics, since a WITH ought to be executed once per associated query
1145 	 * call.)  Note that convert_ANY_sublink_to_join doesn't have to reject
1146 	 * this case, since it just produces a subquery RTE that doesn't have to
1147 	 * get flattened into the parent query.
1148 	 */
1149 	if (subselect->cteList)
1150 		return NULL;
1151 
1152 	/*
1153 	 * Copy the subquery so we can modify it safely (see comments in
1154 	 * make_subplan).
1155 	 */
1156 	subselect = copyObject(subselect);
1157 
1158 	/*
1159 	 * See if the subquery can be simplified based on the knowledge that it's
1160 	 * being used in EXISTS().  If we aren't able to get rid of its
1161 	 * targetlist, we have to fail, because the pullup operation leaves us
1162 	 * with noplace to evaluate the targetlist.
1163 	 */
1164 	if (!simplify_EXISTS_query(root, subselect))
1165 		return NULL;
1166 
1167 	/*
1168 	 * The subquery must have a nonempty jointree, else we won't have a join.
1169 	 */
1170 	if (subselect->jointree->fromlist == NIL)
1171 		return NULL;
1172 
1173 	/*
1174 	 * Separate out the WHERE clause.  (We could theoretically also remove
1175 	 * top-level plain JOIN/ON clauses, but it's probably not worth the
1176 	 * trouble.)
1177 	 */
1178 	whereClause = subselect->jointree->quals;
1179 	subselect->jointree->quals = NULL;
1180 
1181 	/*
1182 	 * The rest of the sub-select must not refer to any Vars of the parent
1183 	 * query.  (Vars of higher levels should be okay, though.)
1184 	 */
1185 	if (contain_vars_of_level((Node *) subselect, 1))
1186 		return NULL;
1187 
1188 	/*
1189 	 * On the other hand, the WHERE clause must contain some Vars of the
1190 	 * parent query, else it's not gonna be a join.
1191 	 */
1192 	if (!contain_vars_of_level(whereClause, 1))
1193 		return NULL;
1194 
1195 	/*
1196 	 * We don't risk optimizing if the WHERE clause is volatile, either.
1197 	 */
1198 	if (contain_volatile_functions(whereClause))
1199 		return NULL;
1200 
1201 	/*
1202 	 * Prepare to pull up the sub-select into top range table.
1203 	 *
1204 	 * We rely here on the assumption that the outer query has no references
1205 	 * to the inner (necessarily true). Therefore this is a lot easier than
1206 	 * what pull_up_subqueries has to go through.
1207 	 *
1208 	 * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1209 	 * do.  The machinations of simplify_EXISTS_query ensured that there is
1210 	 * nothing interesting in the subquery except an rtable and jointree, and
1211 	 * even the jointree FromExpr no longer has quals.  So we can just append
1212 	 * the rtable to our own and use the FromExpr in our jointree. But first,
1213 	 * adjust all level-zero varnos in the subquery to account for the rtable
1214 	 * merger.
1215 	 */
1216 	rtoffset = list_length(parse->rtable);
1217 	OffsetVarNodes((Node *) subselect, rtoffset, 0);
1218 	OffsetVarNodes(whereClause, rtoffset, 0);
1219 
1220 	/*
1221 	 * Upper-level vars in subquery will now be one level closer to their
1222 	 * parent than before; in particular, anything that had been level 1
1223 	 * becomes level zero.
1224 	 */
1225 	IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1226 	IncrementVarSublevelsUp(whereClause, -1, 1);
1227 
1228 	/*
1229 	 * Now that the WHERE clause is adjusted to match the parent query
1230 	 * environment, we can easily identify all the level-zero rels it uses.
1231 	 * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1232 	 * not.
1233 	 */
1234 	clause_varnos = pull_varnos(whereClause);
1235 	upper_varnos = NULL;
1236 	while ((varno = bms_first_member(clause_varnos)) >= 0)
1237 	{
1238 		if (varno <= rtoffset)
1239 			upper_varnos = bms_add_member(upper_varnos, varno);
1240 	}
1241 	bms_free(clause_varnos);
1242 	Assert(!bms_is_empty(upper_varnos));
1243 
1244 	/*
1245 	 * Now that we've got the set of upper-level varnos, we can make the last
1246 	 * check: only available_rels can be referenced.
1247 	 */
1248 	if (!bms_is_subset(upper_varnos, available_rels))
1249 		return NULL;
1250 
1251 	/* Now we can attach the modified subquery rtable to the parent */
1252 	parse->rtable = list_concat(parse->rtable, subselect->rtable);
1253 
1254 	/*
1255 	 * And finally, build the JoinExpr node.
1256 	 */
1257 	result = makeNode(JoinExpr);
1258 	result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1259 	result->isNatural = false;
1260 	result->larg = NULL;		/* caller must fill this in */
1261 	/* flatten out the FromExpr node if it's useless */
1262 	if (list_length(subselect->jointree->fromlist) == 1)
1263 		result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1264 	else
1265 		result->rarg = (Node *) subselect->jointree;
1266 	result->usingClause = NIL;
1267 	result->quals = whereClause;
1268 	result->alias = NULL;
1269 	result->rtindex = 0;		/* we don't need an RTE for it */
1270 
1271 	return result;
1272 }
1273 
1274 /*
1275  * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
1276  *
1277  * The only thing that matters about an EXISTS query is whether it returns
1278  * zero or more than zero rows.  Therefore, we can remove certain SQL features
1279  * that won't affect that.  The only part that is really likely to matter in
1280  * typical usage is simplifying the targetlist: it's a common habit to write
1281  * "SELECT * FROM" even though there is no need to evaluate any columns.
1282  *
1283  * Note: by suppressing the targetlist we could cause an observable behavioral
1284  * change, namely that any errors that might occur in evaluating the tlist
1285  * won't occur, nor will other side-effects of volatile functions.  This seems
1286  * unlikely to bother anyone in practice.
1287  *
1288  * Returns TRUE if was able to discard the targetlist, else FALSE.
1289  */
1290 static bool
simplify_EXISTS_query(PlannerInfo * root,Query * query)1291 simplify_EXISTS_query(PlannerInfo *root, Query *query)
1292 {
1293 	/*
1294 	 * We don't try to simplify at all if the query uses set operations,
1295 	 * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1296 	 * UPDATE/SHARE; none of these seem likely in normal usage and their
1297 	 * possible effects are complex.  (Note: we could ignore an "OFFSET 0"
1298 	 * clause, but that traditionally is used as an optimization fence, so we
1299 	 * don't.)
1300 	 */
1301 	if (query->commandType != CMD_SELECT ||
1302 		query->setOperations ||
1303 		query->hasAggs ||
1304 		query->groupingSets ||
1305 		query->hasWindowFuncs ||
1306 		query->hasTargetSRFs ||
1307 		query->hasModifyingCTE ||
1308 		query->havingQual ||
1309 		query->limitOffset ||
1310 		query->rowMarks)
1311 		return false;
1312 
1313 	/*
1314 	 * LIMIT with a constant positive (or NULL) value doesn't affect the
1315 	 * semantics of EXISTS, so let's ignore such clauses.  This is worth doing
1316 	 * because people accustomed to certain other DBMSes may be in the habit
1317 	 * of writing EXISTS(SELECT ... LIMIT 1) as an optimization.  If there's a
1318 	 * LIMIT with anything else as argument, though, we can't simplify.
1319 	 */
1320 	if (query->limitCount)
1321 	{
1322 		/*
1323 		 * The LIMIT clause has not yet been through eval_const_expressions,
1324 		 * so we have to apply that here.  It might seem like this is a waste
1325 		 * of cycles, since the only case plausibly worth worrying about is
1326 		 * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1327 		 * so we have to fold constants or we're not going to recognize it.
1328 		 */
1329 		Node	   *node = eval_const_expressions(root, query->limitCount);
1330 		Const	   *limit;
1331 
1332 		/* Might as well update the query if we simplified the clause. */
1333 		query->limitCount = node;
1334 
1335 		if (!IsA(node, Const))
1336 			return false;
1337 
1338 		limit = (Const *) node;
1339 		Assert(limit->consttype == INT8OID);
1340 		if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1341 			return false;
1342 
1343 		/* Whether or not the targetlist is safe, we can drop the LIMIT. */
1344 		query->limitCount = NULL;
1345 	}
1346 
1347 	/*
1348 	 * Otherwise, we can throw away the targetlist, as well as any GROUP,
1349 	 * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1350 	 * change a nonzero-rows result to zero rows or vice versa.  (Furthermore,
1351 	 * since our parsetree representation of these clauses depends on the
1352 	 * targetlist, we'd better throw them away if we drop the targetlist.)
1353 	 */
1354 	query->targetList = NIL;
1355 	query->groupClause = NIL;
1356 	query->windowClause = NIL;
1357 	query->distinctClause = NIL;
1358 	query->sortClause = NIL;
1359 	query->hasDistinctOn = false;
1360 
1361 	return true;
1362 }
1363 
1364 /*
1365  * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
1366  *
1367  * The subselect is expected to be a fresh copy that we can munge up,
1368  * and to have been successfully passed through simplify_EXISTS_query.
1369  *
1370  * On success, the modified subselect is returned, and we store a suitable
1371  * upper-level test expression at *testexpr, plus a list of the subselect's
1372  * output Params at *paramIds.  (The test expression is already Param-ified
1373  * and hence need not go through convert_testexpr, which is why we have to
1374  * deal with the Param IDs specially.)
1375  *
1376  * On failure, returns NULL.
1377  */
1378 static Query *
convert_EXISTS_to_ANY(PlannerInfo * root,Query * subselect,Node ** testexpr,List ** paramIds)1379 convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
1380 					  Node **testexpr, List **paramIds)
1381 {
1382 	Node	   *whereClause;
1383 	List	   *leftargs,
1384 			   *rightargs,
1385 			   *opids,
1386 			   *opcollations,
1387 			   *newWhere,
1388 			   *tlist,
1389 			   *testlist,
1390 			   *paramids;
1391 	ListCell   *lc,
1392 			   *rc,
1393 			   *oc,
1394 			   *cc;
1395 	AttrNumber	resno;
1396 
1397 	/*
1398 	 * Query must not require a targetlist, since we have to insert a new one.
1399 	 * Caller should have dealt with the case already.
1400 	 */
1401 	Assert(subselect->targetList == NIL);
1402 
1403 	/*
1404 	 * Separate out the WHERE clause.  (We could theoretically also remove
1405 	 * top-level plain JOIN/ON clauses, but it's probably not worth the
1406 	 * trouble.)
1407 	 */
1408 	whereClause = subselect->jointree->quals;
1409 	subselect->jointree->quals = NULL;
1410 
1411 	/*
1412 	 * The rest of the sub-select must not refer to any Vars of the parent
1413 	 * query.  (Vars of higher levels should be okay, though.)
1414 	 *
1415 	 * Note: we need not check for Aggrefs separately because we know the
1416 	 * sub-select is as yet unoptimized; any uplevel Aggref must therefore
1417 	 * contain an uplevel Var reference.  This is not the case below ...
1418 	 */
1419 	if (contain_vars_of_level((Node *) subselect, 1))
1420 		return NULL;
1421 
1422 	/*
1423 	 * We don't risk optimizing if the WHERE clause is volatile, either.
1424 	 */
1425 	if (contain_volatile_functions(whereClause))
1426 		return NULL;
1427 
1428 	/*
1429 	 * Clean up the WHERE clause by doing const-simplification etc on it.
1430 	 * Aside from simplifying the processing we're about to do, this is
1431 	 * important for being able to pull chunks of the WHERE clause up into the
1432 	 * parent query.  Since we are invoked partway through the parent's
1433 	 * preprocess_expression() work, earlier steps of preprocess_expression()
1434 	 * wouldn't get applied to the pulled-up stuff unless we do them here. For
1435 	 * the parts of the WHERE clause that get put back into the child query,
1436 	 * this work is partially duplicative, but it shouldn't hurt.
1437 	 *
1438 	 * Note: we do not run flatten_join_alias_vars.  This is OK because any
1439 	 * parent aliases were flattened already, and we're not going to pull any
1440 	 * child Vars (of any description) into the parent.
1441 	 *
1442 	 * Note: passing the parent's root to eval_const_expressions is
1443 	 * technically wrong, but we can get away with it since only the
1444 	 * boundParams (if any) are used, and those would be the same in a
1445 	 * subroot.
1446 	 */
1447 	whereClause = eval_const_expressions(root, whereClause);
1448 	whereClause = (Node *) canonicalize_qual_ext((Expr *) whereClause, false);
1449 	whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1450 
1451 	/*
1452 	 * We now have a flattened implicit-AND list of clauses, which we try to
1453 	 * break apart into "outervar = innervar" hash clauses. Anything that
1454 	 * can't be broken apart just goes back into the newWhere list.  Note that
1455 	 * we aren't trying hard yet to ensure that we have only outer or only
1456 	 * inner on each side; we'll check that if we get to the end.
1457 	 */
1458 	leftargs = rightargs = opids = opcollations = newWhere = NIL;
1459 	foreach(lc, (List *) whereClause)
1460 	{
1461 		OpExpr	   *expr = (OpExpr *) lfirst(lc);
1462 
1463 		if (IsA(expr, OpExpr) &&
1464 			hash_ok_operator(expr))
1465 		{
1466 			Node	   *leftarg = (Node *) linitial(expr->args);
1467 			Node	   *rightarg = (Node *) lsecond(expr->args);
1468 
1469 			if (contain_vars_of_level(leftarg, 1))
1470 			{
1471 				leftargs = lappend(leftargs, leftarg);
1472 				rightargs = lappend(rightargs, rightarg);
1473 				opids = lappend_oid(opids, expr->opno);
1474 				opcollations = lappend_oid(opcollations, expr->inputcollid);
1475 				continue;
1476 			}
1477 			if (contain_vars_of_level(rightarg, 1))
1478 			{
1479 				/*
1480 				 * We must commute the clause to put the outer var on the
1481 				 * left, because the hashing code in nodeSubplan.c expects
1482 				 * that.  This probably shouldn't ever fail, since hashable
1483 				 * operators ought to have commutators, but be paranoid.
1484 				 */
1485 				expr->opno = get_commutator(expr->opno);
1486 				if (OidIsValid(expr->opno) && hash_ok_operator(expr))
1487 				{
1488 					leftargs = lappend(leftargs, rightarg);
1489 					rightargs = lappend(rightargs, leftarg);
1490 					opids = lappend_oid(opids, expr->opno);
1491 					opcollations = lappend_oid(opcollations, expr->inputcollid);
1492 					continue;
1493 				}
1494 				/* If no commutator, no chance to optimize the WHERE clause */
1495 				return NULL;
1496 			}
1497 		}
1498 		/* Couldn't handle it as a hash clause */
1499 		newWhere = lappend(newWhere, expr);
1500 	}
1501 
1502 	/*
1503 	 * If we didn't find anything we could convert, fail.
1504 	 */
1505 	if (leftargs == NIL)
1506 		return NULL;
1507 
1508 	/*
1509 	 * There mustn't be any parent Vars or Aggs in the stuff that we intend to
1510 	 * put back into the child query.  Note: you might think we don't need to
1511 	 * check for Aggs separately, because an uplevel Agg must contain an
1512 	 * uplevel Var in its argument.  But it is possible that the uplevel Var
1513 	 * got optimized away by eval_const_expressions.  Consider
1514 	 *
1515 	 * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
1516 	 */
1517 	if (contain_vars_of_level((Node *) newWhere, 1) ||
1518 		contain_vars_of_level((Node *) rightargs, 1))
1519 		return NULL;
1520 	if (root->parse->hasAggs &&
1521 		(contain_aggs_of_level((Node *) newWhere, 1) ||
1522 		 contain_aggs_of_level((Node *) rightargs, 1)))
1523 		return NULL;
1524 
1525 	/*
1526 	 * And there can't be any child Vars in the stuff we intend to pull up.
1527 	 * (Note: we'd need to check for child Aggs too, except we know the child
1528 	 * has no aggs at all because of simplify_EXISTS_query's check. The same
1529 	 * goes for window functions.)
1530 	 */
1531 	if (contain_vars_of_level((Node *) leftargs, 0))
1532 		return NULL;
1533 
1534 	/*
1535 	 * Also reject sublinks in the stuff we intend to pull up.  (It might be
1536 	 * possible to support this, but doesn't seem worth the complication.)
1537 	 */
1538 	if (contain_subplans((Node *) leftargs))
1539 		return NULL;
1540 
1541 	/*
1542 	 * Okay, adjust the sublevelsup in the stuff we're pulling up.
1543 	 */
1544 	IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
1545 
1546 	/*
1547 	 * Put back any child-level-only WHERE clauses.
1548 	 */
1549 	if (newWhere)
1550 		subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
1551 
1552 	/*
1553 	 * Build a new targetlist for the child that emits the expressions we
1554 	 * need.  Concurrently, build a testexpr for the parent using Params to
1555 	 * reference the child outputs.  (Since we generate Params directly here,
1556 	 * there will be no need to convert the testexpr in build_subplan.)
1557 	 */
1558 	tlist = testlist = paramids = NIL;
1559 	resno = 1;
1560 	/* there's no "forfour" so we have to chase one of the lists manually */
1561 	cc = list_head(opcollations);
1562 	forthree(lc, leftargs, rc, rightargs, oc, opids)
1563 	{
1564 		Node	   *leftarg = (Node *) lfirst(lc);
1565 		Node	   *rightarg = (Node *) lfirst(rc);
1566 		Oid			opid = lfirst_oid(oc);
1567 		Oid			opcollation = lfirst_oid(cc);
1568 		Param	   *param;
1569 
1570 		cc = lnext(cc);
1571 		param = generate_new_exec_param(root,
1572 										exprType(rightarg),
1573 										exprTypmod(rightarg),
1574 										exprCollation(rightarg));
1575 		tlist = lappend(tlist,
1576 						makeTargetEntry((Expr *) rightarg,
1577 										resno++,
1578 										NULL,
1579 										false));
1580 		testlist = lappend(testlist,
1581 						   make_opclause(opid, BOOLOID, false,
1582 										 (Expr *) leftarg, (Expr *) param,
1583 										 InvalidOid, opcollation));
1584 		paramids = lappend_int(paramids, param->paramid);
1585 	}
1586 
1587 	/* Put everything where it should go, and we're done */
1588 	subselect->targetList = tlist;
1589 	*testexpr = (Node *) make_ands_explicit(testlist);
1590 	*paramIds = paramids;
1591 
1592 	return subselect;
1593 }
1594 
1595 
1596 /*
1597  * Replace correlation vars (uplevel vars) with Params.
1598  *
1599  * Uplevel PlaceHolderVars and aggregates are replaced, too.
1600  *
1601  * Note: it is critical that this runs immediately after SS_process_sublinks.
1602  * Since we do not recurse into the arguments of uplevel PHVs and aggregates,
1603  * they will get copied to the appropriate subplan args list in the parent
1604  * query with uplevel vars not replaced by Params, but only adjusted in level
1605  * (see replace_outer_placeholdervar and replace_outer_agg).  That's exactly
1606  * what we want for the vars of the parent level --- but if a PHV's or
1607  * aggregate's argument contains any further-up variables, they have to be
1608  * replaced with Params in their turn. That will happen when the parent level
1609  * runs SS_replace_correlation_vars.  Therefore it must do so after expanding
1610  * its sublinks to subplans.  And we don't want any steps in between, else
1611  * those steps would never get applied to the argument expressions, either in
1612  * the parent or the child level.
1613  *
1614  * Another fairly tricky thing going on here is the handling of SubLinks in
1615  * the arguments of uplevel PHVs/aggregates.  Those are not touched inside the
1616  * intermediate query level, either.  Instead, SS_process_sublinks recurses on
1617  * them after copying the PHV or Aggref expression into the parent plan level
1618  * (this is actually taken care of in build_subplan).
1619  */
1620 Node *
SS_replace_correlation_vars(PlannerInfo * root,Node * expr)1621 SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
1622 {
1623 	/* No setup needed for tree walk, so away we go */
1624 	return replace_correlation_vars_mutator(expr, root);
1625 }
1626 
1627 static Node *
replace_correlation_vars_mutator(Node * node,PlannerInfo * root)1628 replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
1629 {
1630 	if (node == NULL)
1631 		return NULL;
1632 	if (IsA(node, Var))
1633 	{
1634 		if (((Var *) node)->varlevelsup > 0)
1635 			return (Node *) replace_outer_var(root, (Var *) node);
1636 	}
1637 	if (IsA(node, PlaceHolderVar))
1638 	{
1639 		if (((PlaceHolderVar *) node)->phlevelsup > 0)
1640 			return (Node *) replace_outer_placeholdervar(root,
1641 														 (PlaceHolderVar *) node);
1642 	}
1643 	if (IsA(node, Aggref))
1644 	{
1645 		if (((Aggref *) node)->agglevelsup > 0)
1646 			return (Node *) replace_outer_agg(root, (Aggref *) node);
1647 	}
1648 	if (IsA(node, GroupingFunc))
1649 	{
1650 		if (((GroupingFunc *) node)->agglevelsup > 0)
1651 			return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
1652 	}
1653 	return expression_tree_mutator(node,
1654 								   replace_correlation_vars_mutator,
1655 								   (void *) root);
1656 }
1657 
1658 /*
1659  * Expand SubLinks to SubPlans in the given expression.
1660  *
1661  * The isQual argument tells whether or not this expression is a WHERE/HAVING
1662  * qualifier expression.  If it is, any sublinks appearing at top level need
1663  * not distinguish FALSE from UNKNOWN return values.
1664  */
1665 Node *
SS_process_sublinks(PlannerInfo * root,Node * expr,bool isQual)1666 SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
1667 {
1668 	process_sublinks_context context;
1669 
1670 	context.root = root;
1671 	context.isTopQual = isQual;
1672 	return process_sublinks_mutator(expr, &context);
1673 }
1674 
1675 static Node *
process_sublinks_mutator(Node * node,process_sublinks_context * context)1676 process_sublinks_mutator(Node *node, process_sublinks_context *context)
1677 {
1678 	process_sublinks_context locContext;
1679 
1680 	locContext.root = context->root;
1681 
1682 	if (node == NULL)
1683 		return NULL;
1684 	if (IsA(node, SubLink))
1685 	{
1686 		SubLink    *sublink = (SubLink *) node;
1687 		Node	   *testexpr;
1688 
1689 		/*
1690 		 * First, recursively process the lefthand-side expressions, if any.
1691 		 * They're not top-level anymore.
1692 		 */
1693 		locContext.isTopQual = false;
1694 		testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1695 
1696 		/*
1697 		 * Now build the SubPlan node and make the expr to return.
1698 		 */
1699 		return make_subplan(context->root,
1700 							(Query *) sublink->subselect,
1701 							sublink->subLinkType,
1702 							sublink->subLinkId,
1703 							testexpr,
1704 							context->isTopQual);
1705 	}
1706 
1707 	/*
1708 	 * Don't recurse into the arguments of an outer PHV or aggregate here. Any
1709 	 * SubLinks in the arguments have to be dealt with at the outer query
1710 	 * level; they'll be handled when build_subplan collects the PHV or Aggref
1711 	 * into the arguments to be passed down to the current subplan.
1712 	 */
1713 	if (IsA(node, PlaceHolderVar))
1714 	{
1715 		if (((PlaceHolderVar *) node)->phlevelsup > 0)
1716 			return node;
1717 	}
1718 	else if (IsA(node, Aggref))
1719 	{
1720 		if (((Aggref *) node)->agglevelsup > 0)
1721 			return node;
1722 	}
1723 
1724 	/*
1725 	 * We should never see a SubPlan expression in the input (since this is
1726 	 * the very routine that creates 'em to begin with).  We shouldn't find
1727 	 * ourselves invoked directly on a Query, either.
1728 	 */
1729 	Assert(!IsA(node, SubPlan));
1730 	Assert(!IsA(node, AlternativeSubPlan));
1731 	Assert(!IsA(node, Query));
1732 
1733 	/*
1734 	 * Because make_subplan() could return an AND or OR clause, we have to
1735 	 * take steps to preserve AND/OR flatness of a qual.  We assume the input
1736 	 * has been AND/OR flattened and so we need no recursion here.
1737 	 *
1738 	 * (Due to the coding here, we will not get called on the List subnodes of
1739 	 * an AND; and the input is *not* yet in implicit-AND format.  So no check
1740 	 * is needed for a bare List.)
1741 	 *
1742 	 * Anywhere within the top-level AND/OR clause structure, we can tell
1743 	 * make_subplan() that NULL and FALSE are interchangeable.  So isTopQual
1744 	 * propagates down in both cases.  (Note that this is unlike the meaning
1745 	 * of "top level qual" used in most other places in Postgres.)
1746 	 */
1747 	if (and_clause(node))
1748 	{
1749 		List	   *newargs = NIL;
1750 		ListCell   *l;
1751 
1752 		/* Still at qual top-level */
1753 		locContext.isTopQual = context->isTopQual;
1754 
1755 		foreach(l, ((BoolExpr *) node)->args)
1756 		{
1757 			Node	   *newarg;
1758 
1759 			newarg = process_sublinks_mutator(lfirst(l), &locContext);
1760 			if (and_clause(newarg))
1761 				newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1762 			else
1763 				newargs = lappend(newargs, newarg);
1764 		}
1765 		return (Node *) make_andclause(newargs);
1766 	}
1767 
1768 	if (or_clause(node))
1769 	{
1770 		List	   *newargs = NIL;
1771 		ListCell   *l;
1772 
1773 		/* Still at qual top-level */
1774 		locContext.isTopQual = context->isTopQual;
1775 
1776 		foreach(l, ((BoolExpr *) node)->args)
1777 		{
1778 			Node	   *newarg;
1779 
1780 			newarg = process_sublinks_mutator(lfirst(l), &locContext);
1781 			if (or_clause(newarg))
1782 				newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1783 			else
1784 				newargs = lappend(newargs, newarg);
1785 		}
1786 		return (Node *) make_orclause(newargs);
1787 	}
1788 
1789 	/*
1790 	 * If we recurse down through anything other than an AND or OR node, we
1791 	 * are definitely not at top qual level anymore.
1792 	 */
1793 	locContext.isTopQual = false;
1794 
1795 	return expression_tree_mutator(node,
1796 								   process_sublinks_mutator,
1797 								   (void *) &locContext);
1798 }
1799 
1800 /*
1801  * SS_identify_outer_params - identify the Params available from outer levels
1802  *
1803  * This must be run after SS_replace_correlation_vars and SS_process_sublinks
1804  * processing is complete in a given query level as well as all of its
1805  * descendant levels (which means it's most practical to do it at the end of
1806  * processing the query level).  We compute the set of paramIds that outer
1807  * levels will make available to this level+descendants, and record it in
1808  * root->outer_params for use while computing extParam/allParam sets in final
1809  * plan cleanup.  (We can't just compute it then, because the upper levels'
1810  * plan_params lists are transient and will be gone by then.)
1811  */
1812 void
SS_identify_outer_params(PlannerInfo * root)1813 SS_identify_outer_params(PlannerInfo *root)
1814 {
1815 	Bitmapset  *outer_params;
1816 	PlannerInfo *proot;
1817 	ListCell   *l;
1818 
1819 	/*
1820 	 * If no parameters have been assigned anywhere in the tree, we certainly
1821 	 * don't need to do anything here.
1822 	 */
1823 	if (root->glob->nParamExec == 0)
1824 		return;
1825 
1826 	/*
1827 	 * Scan all query levels above this one to see which parameters are due to
1828 	 * be available from them, either because lower query levels have
1829 	 * requested them (via plan_params) or because they will be available from
1830 	 * initPlans of those levels.
1831 	 */
1832 	outer_params = NULL;
1833 	for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
1834 	{
1835 		/* Include ordinary Var/PHV/Aggref params */
1836 		foreach(l, proot->plan_params)
1837 		{
1838 			PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
1839 
1840 			outer_params = bms_add_member(outer_params, pitem->paramId);
1841 		}
1842 		/* Include any outputs of outer-level initPlans */
1843 		foreach(l, proot->init_plans)
1844 		{
1845 			SubPlan    *initsubplan = (SubPlan *) lfirst(l);
1846 			ListCell   *l2;
1847 
1848 			foreach(l2, initsubplan->setParam)
1849 			{
1850 				outer_params = bms_add_member(outer_params, lfirst_int(l2));
1851 			}
1852 		}
1853 		/* Include worktable ID, if a recursive query is being planned */
1854 		if (proot->wt_param_id >= 0)
1855 			outer_params = bms_add_member(outer_params, proot->wt_param_id);
1856 	}
1857 	root->outer_params = outer_params;
1858 }
1859 
1860 /*
1861  * SS_charge_for_initplans - account for initplans in Path costs & parallelism
1862  *
1863  * If any initPlans have been created in the current query level, they will
1864  * get attached to the Plan tree created from whichever Path we select from
1865  * the given rel.  Increment all that rel's Paths' costs to account for them,
1866  * and make sure the paths get marked as parallel-unsafe, since we can't
1867  * currently transmit initPlans to parallel workers.
1868  *
1869  * This is separate from SS_attach_initplans because we might conditionally
1870  * create more initPlans during create_plan(), depending on which Path we
1871  * select.  However, Paths that would generate such initPlans are expected
1872  * to have included their cost already.
1873  */
1874 void
SS_charge_for_initplans(PlannerInfo * root,RelOptInfo * final_rel)1875 SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
1876 {
1877 	Cost		initplan_cost;
1878 	ListCell   *lc;
1879 
1880 	/* Nothing to do if no initPlans */
1881 	if (root->init_plans == NIL)
1882 		return;
1883 
1884 	/*
1885 	 * Compute the cost increment just once, since it will be the same for all
1886 	 * Paths.  We assume each initPlan gets run once during top plan startup.
1887 	 * This is a conservative overestimate, since in fact an initPlan might be
1888 	 * executed later than plan startup, or even not at all.
1889 	 */
1890 	initplan_cost = 0;
1891 	foreach(lc, root->init_plans)
1892 	{
1893 		SubPlan    *initsubplan = (SubPlan *) lfirst(lc);
1894 
1895 		initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
1896 	}
1897 
1898 	/*
1899 	 * Now adjust the costs and parallel_safe flags.
1900 	 */
1901 	foreach(lc, final_rel->pathlist)
1902 	{
1903 		Path	   *path = (Path *) lfirst(lc);
1904 
1905 		path->startup_cost += initplan_cost;
1906 		path->total_cost += initplan_cost;
1907 		path->parallel_safe = false;
1908 	}
1909 
1910 	/* We needn't do set_cheapest() here, caller will do it */
1911 }
1912 
1913 /*
1914  * SS_attach_initplans - attach initplans to topmost plan node
1915  *
1916  * Attach any initplans created in the current query level to the specified
1917  * plan node, which should normally be the topmost node for the query level.
1918  * (In principle the initPlans could go in any node at or above where they're
1919  * referenced; but there seems no reason to put them any lower than the
1920  * topmost node, so we don't bother to track exactly where they came from.)
1921  * We do not touch the plan node's cost; the initplans should have been
1922  * accounted for in path costing.
1923  */
1924 void
SS_attach_initplans(PlannerInfo * root,Plan * plan)1925 SS_attach_initplans(PlannerInfo *root, Plan *plan)
1926 {
1927 	plan->initPlan = root->init_plans;
1928 }
1929 
1930 /*
1931  * SS_finalize_plan - do final parameter processing for a completed Plan.
1932  *
1933  * This recursively computes the extParam and allParam sets for every Plan
1934  * node in the given plan tree.  (Oh, and RangeTblFunction.funcparams too.)
1935  *
1936  * We assume that SS_finalize_plan has already been run on any initplans or
1937  * subplans the plan tree could reference.
1938  */
1939 void
SS_finalize_plan(PlannerInfo * root,Plan * plan)1940 SS_finalize_plan(PlannerInfo *root, Plan *plan)
1941 {
1942 	/* No setup needed, just recurse through plan tree. */
1943 	(void) finalize_plan(root, plan, -1, root->outer_params, NULL);
1944 }
1945 
1946 /*
1947  * Recursive processing of all nodes in the plan tree
1948  *
1949  * gather_param is the rescan_param of an ancestral Gather/GatherMerge,
1950  * or -1 if there is none.
1951  *
1952  * valid_params is the set of param IDs supplied by outer plan levels
1953  * that are valid to reference in this plan node or its children.
1954  *
1955  * scan_params is a set of param IDs to force scan plan nodes to reference.
1956  * This is for EvalPlanQual support, and is always NULL at the top of the
1957  * recursion.
1958  *
1959  * The return value is the computed allParam set for the given Plan node.
1960  * This is just an internal notational convenience: we can add a child
1961  * plan's allParams to the set of param IDs of interest to this level
1962  * in the same statement that recurses to that child.
1963  *
1964  * Do not scribble on caller's values of valid_params or scan_params!
1965  *
1966  * Note: although we attempt to deal with initPlans anywhere in the tree, the
1967  * logic is not really right.  The problem is that a plan node might return an
1968  * output Param of its initPlan as a targetlist item, in which case it's valid
1969  * for the parent plan level to reference that same Param; the parent's usage
1970  * will be converted into a Var referencing the child plan node by setrefs.c.
1971  * But this function would see the parent's reference as out of scope and
1972  * complain about it.  For now, this does not matter because the planner only
1973  * attaches initPlans to the topmost plan node in a query level, so the case
1974  * doesn't arise.  If we ever merge this processing into setrefs.c, maybe it
1975  * can be handled more cleanly.
1976  */
1977 static Bitmapset *
finalize_plan(PlannerInfo * root,Plan * plan,int gather_param,Bitmapset * valid_params,Bitmapset * scan_params)1978 finalize_plan(PlannerInfo *root, Plan *plan,
1979 			  int gather_param,
1980 			  Bitmapset *valid_params,
1981 			  Bitmapset *scan_params)
1982 {
1983 	finalize_primnode_context context;
1984 	int			locally_added_param;
1985 	Bitmapset  *nestloop_params;
1986 	Bitmapset  *initExtParam;
1987 	Bitmapset  *initSetParam;
1988 	Bitmapset  *child_params;
1989 	ListCell   *l;
1990 
1991 	if (plan == NULL)
1992 		return NULL;
1993 
1994 	context.root = root;
1995 	context.paramids = NULL;	/* initialize set to empty */
1996 	locally_added_param = -1;	/* there isn't one */
1997 	nestloop_params = NULL;		/* there aren't any */
1998 
1999 	/*
2000 	 * Examine any initPlans to determine the set of external params they
2001 	 * reference and the set of output params they supply.  (We assume
2002 	 * SS_finalize_plan was run on them already.)
2003 	 */
2004 	initExtParam = initSetParam = NULL;
2005 	foreach(l, plan->initPlan)
2006 	{
2007 		SubPlan    *initsubplan = (SubPlan *) lfirst(l);
2008 		Plan	   *initplan = planner_subplan_get_plan(root, initsubplan);
2009 		ListCell   *l2;
2010 
2011 		initExtParam = bms_add_members(initExtParam, initplan->extParam);
2012 		foreach(l2, initsubplan->setParam)
2013 		{
2014 			initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2015 		}
2016 	}
2017 
2018 	/* Any setParams are validly referenceable in this node and children */
2019 	if (initSetParam)
2020 		valid_params = bms_union(valid_params, initSetParam);
2021 
2022 	/*
2023 	 * When we call finalize_primnode, context.paramids sets are automatically
2024 	 * merged together.  But when recursing to self, we have to do it the hard
2025 	 * way.  We want the paramids set to include params in subplans as well as
2026 	 * at this level.
2027 	 */
2028 
2029 	/* Find params in targetlist and qual */
2030 	finalize_primnode((Node *) plan->targetlist, &context);
2031 	finalize_primnode((Node *) plan->qual, &context);
2032 
2033 	/*
2034 	 * If it's a parallel-aware scan node, mark it as dependent on the parent
2035 	 * Gather/GatherMerge's rescan Param.
2036 	 */
2037 	if (plan->parallel_aware)
2038 	{
2039 		if (gather_param < 0)
2040 			elog(ERROR, "parallel-aware plan node is not below a Gather");
2041 		context.paramids =
2042 			bms_add_member(context.paramids, gather_param);
2043 	}
2044 
2045 	/* Check additional node-type-specific fields */
2046 	switch (nodeTag(plan))
2047 	{
2048 		case T_Result:
2049 			finalize_primnode(((Result *) plan)->resconstantqual,
2050 							  &context);
2051 			break;
2052 
2053 		case T_SeqScan:
2054 			context.paramids = bms_add_members(context.paramids, scan_params);
2055 			break;
2056 
2057 		case T_SampleScan:
2058 			finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
2059 							  &context);
2060 			context.paramids = bms_add_members(context.paramids, scan_params);
2061 			break;
2062 
2063 		case T_IndexScan:
2064 			finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2065 							  &context);
2066 			finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2067 							  &context);
2068 
2069 			/*
2070 			 * we need not look at indexqualorig, since it will have the same
2071 			 * param references as indexqual.  Likewise, we can ignore
2072 			 * indexorderbyorig.
2073 			 */
2074 			context.paramids = bms_add_members(context.paramids, scan_params);
2075 			break;
2076 
2077 		case T_IndexOnlyScan:
2078 			finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2079 							  &context);
2080 			finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2081 							  &context);
2082 
2083 			/*
2084 			 * we need not look at indextlist, since it cannot contain Params.
2085 			 */
2086 			context.paramids = bms_add_members(context.paramids, scan_params);
2087 			break;
2088 
2089 		case T_BitmapIndexScan:
2090 			finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2091 							  &context);
2092 
2093 			/*
2094 			 * we need not look at indexqualorig, since it will have the same
2095 			 * param references as indexqual.
2096 			 */
2097 			break;
2098 
2099 		case T_BitmapHeapScan:
2100 			finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2101 							  &context);
2102 			context.paramids = bms_add_members(context.paramids, scan_params);
2103 			break;
2104 
2105 		case T_TidScan:
2106 			finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2107 							  &context);
2108 			context.paramids = bms_add_members(context.paramids, scan_params);
2109 			break;
2110 
2111 		case T_SubqueryScan:
2112 			{
2113 				SubqueryScan *sscan = (SubqueryScan *) plan;
2114 				RelOptInfo *rel;
2115 
2116 				/* We must run SS_finalize_plan on the subquery */
2117 				rel = find_base_rel(root, sscan->scan.scanrelid);
2118 				SS_finalize_plan(rel->subroot, sscan->subplan);
2119 
2120 				/* Now we can add its extParams to the parent's params */
2121 				context.paramids = bms_add_members(context.paramids,
2122 												   sscan->subplan->extParam);
2123 				/* We need scan_params too, though */
2124 				context.paramids = bms_add_members(context.paramids,
2125 												   scan_params);
2126 			}
2127 			break;
2128 
2129 		case T_FunctionScan:
2130 			{
2131 				FunctionScan *fscan = (FunctionScan *) plan;
2132 				ListCell   *lc;
2133 
2134 				/*
2135 				 * Call finalize_primnode independently on each function
2136 				 * expression, so that we can record which params are
2137 				 * referenced in each, in order to decide which need
2138 				 * re-evaluating during rescan.
2139 				 */
2140 				foreach(lc, fscan->functions)
2141 				{
2142 					RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2143 					finalize_primnode_context funccontext;
2144 
2145 					funccontext = context;
2146 					funccontext.paramids = NULL;
2147 
2148 					finalize_primnode(rtfunc->funcexpr, &funccontext);
2149 
2150 					/* remember results for execution */
2151 					rtfunc->funcparams = funccontext.paramids;
2152 
2153 					/* add the function's params to the overall set */
2154 					context.paramids = bms_add_members(context.paramids,
2155 													   funccontext.paramids);
2156 				}
2157 
2158 				context.paramids = bms_add_members(context.paramids,
2159 												   scan_params);
2160 			}
2161 			break;
2162 
2163 		case T_TableFuncScan:
2164 			finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
2165 							  &context);
2166 			context.paramids = bms_add_members(context.paramids, scan_params);
2167 			break;
2168 
2169 		case T_ValuesScan:
2170 			finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2171 							  &context);
2172 			context.paramids = bms_add_members(context.paramids, scan_params);
2173 			break;
2174 
2175 		case T_CteScan:
2176 			{
2177 				/*
2178 				 * You might think we should add the node's cteParam to
2179 				 * paramids, but we shouldn't because that param is just a
2180 				 * linkage mechanism for multiple CteScan nodes for the same
2181 				 * CTE; it is never used for changed-param signaling.  What we
2182 				 * have to do instead is to find the referenced CTE plan and
2183 				 * incorporate its external paramids, so that the correct
2184 				 * things will happen if the CTE references outer-level
2185 				 * variables.  See test cases for bug #4902.  (We assume
2186 				 * SS_finalize_plan was run on the CTE plan already.)
2187 				 */
2188 				int			plan_id = ((CteScan *) plan)->ctePlanId;
2189 				Plan	   *cteplan;
2190 
2191 				/* so, do this ... */
2192 				if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2193 					elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2194 						 plan_id);
2195 				cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2196 				context.paramids =
2197 					bms_add_members(context.paramids, cteplan->extParam);
2198 
2199 #ifdef NOT_USED
2200 				/* ... but not this */
2201 				context.paramids =
2202 					bms_add_member(context.paramids,
2203 								   ((CteScan *) plan)->cteParam);
2204 #endif
2205 
2206 				context.paramids = bms_add_members(context.paramids,
2207 												   scan_params);
2208 			}
2209 			break;
2210 
2211 		case T_WorkTableScan:
2212 			context.paramids =
2213 				bms_add_member(context.paramids,
2214 							   ((WorkTableScan *) plan)->wtParam);
2215 			context.paramids = bms_add_members(context.paramids, scan_params);
2216 			break;
2217 
2218 		case T_NamedTuplestoreScan:
2219 			context.paramids = bms_add_members(context.paramids, scan_params);
2220 			break;
2221 
2222 		case T_ForeignScan:
2223 			{
2224 				ForeignScan *fscan = (ForeignScan *) plan;
2225 
2226 				finalize_primnode((Node *) fscan->fdw_exprs,
2227 								  &context);
2228 				finalize_primnode((Node *) fscan->fdw_recheck_quals,
2229 								  &context);
2230 
2231 				/* We assume fdw_scan_tlist cannot contain Params */
2232 				context.paramids = bms_add_members(context.paramids,
2233 												   scan_params);
2234 			}
2235 			break;
2236 
2237 		case T_CustomScan:
2238 			{
2239 				CustomScan *cscan = (CustomScan *) plan;
2240 				ListCell   *lc;
2241 
2242 				finalize_primnode((Node *) cscan->custom_exprs,
2243 								  &context);
2244 				/* We assume custom_scan_tlist cannot contain Params */
2245 				context.paramids =
2246 					bms_add_members(context.paramids, scan_params);
2247 
2248 				/* child nodes if any */
2249 				foreach(lc, cscan->custom_plans)
2250 				{
2251 					context.paramids =
2252 						bms_add_members(context.paramids,
2253 										finalize_plan(root,
2254 													  (Plan *) lfirst(lc),
2255 													  gather_param,
2256 													  valid_params,
2257 													  scan_params));
2258 				}
2259 			}
2260 			break;
2261 
2262 		case T_ModifyTable:
2263 			{
2264 				ModifyTable *mtplan = (ModifyTable *) plan;
2265 				ListCell   *l;
2266 
2267 				/* Force descendant scan nodes to reference epqParam */
2268 				locally_added_param = mtplan->epqParam;
2269 				valid_params = bms_add_member(bms_copy(valid_params),
2270 											  locally_added_param);
2271 				scan_params = bms_add_member(bms_copy(scan_params),
2272 											 locally_added_param);
2273 				finalize_primnode((Node *) mtplan->returningLists,
2274 								  &context);
2275 				finalize_primnode((Node *) mtplan->onConflictSet,
2276 								  &context);
2277 				finalize_primnode((Node *) mtplan->onConflictWhere,
2278 								  &context);
2279 				/* exclRelTlist contains only Vars, doesn't need examination */
2280 				foreach(l, mtplan->plans)
2281 				{
2282 					context.paramids =
2283 						bms_add_members(context.paramids,
2284 										finalize_plan(root,
2285 													  (Plan *) lfirst(l),
2286 													  gather_param,
2287 													  valid_params,
2288 													  scan_params));
2289 				}
2290 			}
2291 			break;
2292 
2293 		case T_Append:
2294 			{
2295 				ListCell   *l;
2296 
2297 				foreach(l, ((Append *) plan)->appendplans)
2298 				{
2299 					context.paramids =
2300 						bms_add_members(context.paramids,
2301 										finalize_plan(root,
2302 													  (Plan *) lfirst(l),
2303 													  gather_param,
2304 													  valid_params,
2305 													  scan_params));
2306 				}
2307 			}
2308 			break;
2309 
2310 		case T_MergeAppend:
2311 			{
2312 				ListCell   *l;
2313 
2314 				foreach(l, ((MergeAppend *) plan)->mergeplans)
2315 				{
2316 					context.paramids =
2317 						bms_add_members(context.paramids,
2318 										finalize_plan(root,
2319 													  (Plan *) lfirst(l),
2320 													  gather_param,
2321 													  valid_params,
2322 													  scan_params));
2323 				}
2324 			}
2325 			break;
2326 
2327 		case T_BitmapAnd:
2328 			{
2329 				ListCell   *l;
2330 
2331 				foreach(l, ((BitmapAnd *) plan)->bitmapplans)
2332 				{
2333 					context.paramids =
2334 						bms_add_members(context.paramids,
2335 										finalize_plan(root,
2336 													  (Plan *) lfirst(l),
2337 													  gather_param,
2338 													  valid_params,
2339 													  scan_params));
2340 				}
2341 			}
2342 			break;
2343 
2344 		case T_BitmapOr:
2345 			{
2346 				ListCell   *l;
2347 
2348 				foreach(l, ((BitmapOr *) plan)->bitmapplans)
2349 				{
2350 					context.paramids =
2351 						bms_add_members(context.paramids,
2352 										finalize_plan(root,
2353 													  (Plan *) lfirst(l),
2354 													  gather_param,
2355 													  valid_params,
2356 													  scan_params));
2357 				}
2358 			}
2359 			break;
2360 
2361 		case T_NestLoop:
2362 			{
2363 				ListCell   *l;
2364 
2365 				finalize_primnode((Node *) ((Join *) plan)->joinqual,
2366 								  &context);
2367 				/* collect set of params that will be passed to right child */
2368 				foreach(l, ((NestLoop *) plan)->nestParams)
2369 				{
2370 					NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
2371 
2372 					nestloop_params = bms_add_member(nestloop_params,
2373 													 nlp->paramno);
2374 				}
2375 			}
2376 			break;
2377 
2378 		case T_MergeJoin:
2379 			finalize_primnode((Node *) ((Join *) plan)->joinqual,
2380 							  &context);
2381 			finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
2382 							  &context);
2383 			break;
2384 
2385 		case T_HashJoin:
2386 			finalize_primnode((Node *) ((Join *) plan)->joinqual,
2387 							  &context);
2388 			finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
2389 							  &context);
2390 			break;
2391 
2392 		case T_Limit:
2393 			finalize_primnode(((Limit *) plan)->limitOffset,
2394 							  &context);
2395 			finalize_primnode(((Limit *) plan)->limitCount,
2396 							  &context);
2397 			break;
2398 
2399 		case T_RecursiveUnion:
2400 			/* child nodes are allowed to reference wtParam */
2401 			locally_added_param = ((RecursiveUnion *) plan)->wtParam;
2402 			valid_params = bms_add_member(bms_copy(valid_params),
2403 										  locally_added_param);
2404 			/* wtParam does *not* get added to scan_params */
2405 			break;
2406 
2407 		case T_LockRows:
2408 			/* Force descendant scan nodes to reference epqParam */
2409 			locally_added_param = ((LockRows *) plan)->epqParam;
2410 			valid_params = bms_add_member(bms_copy(valid_params),
2411 										  locally_added_param);
2412 			scan_params = bms_add_member(bms_copy(scan_params),
2413 										 locally_added_param);
2414 			break;
2415 
2416 		case T_Agg:
2417 			{
2418 				Agg		   *agg = (Agg *) plan;
2419 
2420 				/*
2421 				 * AGG_HASHED plans need to know which Params are referenced
2422 				 * in aggregate calls.  Do a separate scan to identify them.
2423 				 */
2424 				if (agg->aggstrategy == AGG_HASHED)
2425 				{
2426 					finalize_primnode_context aggcontext;
2427 
2428 					aggcontext.root = root;
2429 					aggcontext.paramids = NULL;
2430 					finalize_agg_primnode((Node *) agg->plan.targetlist,
2431 										  &aggcontext);
2432 					finalize_agg_primnode((Node *) agg->plan.qual,
2433 										  &aggcontext);
2434 					agg->aggParams = aggcontext.paramids;
2435 				}
2436 			}
2437 			break;
2438 
2439 		case T_WindowAgg:
2440 			finalize_primnode(((WindowAgg *) plan)->startOffset,
2441 							  &context);
2442 			finalize_primnode(((WindowAgg *) plan)->endOffset,
2443 							  &context);
2444 			break;
2445 
2446 		case T_Gather:
2447 			/* child nodes are allowed to reference rescan_param, if any */
2448 			locally_added_param = ((Gather *) plan)->rescan_param;
2449 			if (locally_added_param >= 0)
2450 			{
2451 				valid_params = bms_add_member(bms_copy(valid_params),
2452 											  locally_added_param);
2453 
2454 				/*
2455 				 * We currently don't support nested Gathers.  The issue so
2456 				 * far as this function is concerned would be how to identify
2457 				 * which child nodes depend on which Gather.
2458 				 */
2459 				Assert(gather_param < 0);
2460 				/* Pass down rescan_param to child parallel-aware nodes */
2461 				gather_param = locally_added_param;
2462 			}
2463 			/* rescan_param does *not* get added to scan_params */
2464 			break;
2465 
2466 		case T_GatherMerge:
2467 			/* child nodes are allowed to reference rescan_param, if any */
2468 			locally_added_param = ((GatherMerge *) plan)->rescan_param;
2469 			if (locally_added_param >= 0)
2470 			{
2471 				valid_params = bms_add_member(bms_copy(valid_params),
2472 											  locally_added_param);
2473 
2474 				/*
2475 				 * We currently don't support nested Gathers.  The issue so
2476 				 * far as this function is concerned would be how to identify
2477 				 * which child nodes depend on which Gather.
2478 				 */
2479 				Assert(gather_param < 0);
2480 				/* Pass down rescan_param to child parallel-aware nodes */
2481 				gather_param = locally_added_param;
2482 			}
2483 			/* rescan_param does *not* get added to scan_params */
2484 			break;
2485 
2486 		case T_ProjectSet:
2487 		case T_Hash:
2488 		case T_Material:
2489 		case T_Sort:
2490 		case T_Unique:
2491 		case T_SetOp:
2492 		case T_Group:
2493 			/* no node-type-specific fields need fixing */
2494 			break;
2495 
2496 		default:
2497 			elog(ERROR, "unrecognized node type: %d",
2498 				 (int) nodeTag(plan));
2499 	}
2500 
2501 	/* Process left and right child plans, if any */
2502 	child_params = finalize_plan(root,
2503 								 plan->lefttree,
2504 								 gather_param,
2505 								 valid_params,
2506 								 scan_params);
2507 	context.paramids = bms_add_members(context.paramids, child_params);
2508 
2509 	if (nestloop_params)
2510 	{
2511 		/* right child can reference nestloop_params as well as valid_params */
2512 		child_params = finalize_plan(root,
2513 									 plan->righttree,
2514 									 gather_param,
2515 									 bms_union(nestloop_params, valid_params),
2516 									 scan_params);
2517 		/* ... and they don't count as parameters used at my level */
2518 		child_params = bms_difference(child_params, nestloop_params);
2519 		bms_free(nestloop_params);
2520 	}
2521 	else
2522 	{
2523 		/* easy case */
2524 		child_params = finalize_plan(root,
2525 									 plan->righttree,
2526 									 gather_param,
2527 									 valid_params,
2528 									 scan_params);
2529 	}
2530 	context.paramids = bms_add_members(context.paramids, child_params);
2531 
2532 	/*
2533 	 * Any locally generated parameter doesn't count towards its generating
2534 	 * plan node's external dependencies.  (Note: if we changed valid_params
2535 	 * and/or scan_params, we leak those bitmapsets; not worth the notational
2536 	 * trouble to clean them up.)
2537 	 */
2538 	if (locally_added_param >= 0)
2539 	{
2540 		context.paramids = bms_del_member(context.paramids,
2541 										  locally_added_param);
2542 	}
2543 
2544 	/* Now we have all the paramids referenced in this node and children */
2545 
2546 	if (!bms_is_subset(context.paramids, valid_params))
2547 		elog(ERROR, "plan should not reference subplan's variable");
2548 
2549 	/*
2550 	 * The plan node's allParam and extParam fields should include all its
2551 	 * referenced paramids, plus contributions from any child initPlans.
2552 	 * However, any setParams of the initPlans should not be present in the
2553 	 * parent node's extParams, only in its allParams.  (It's possible that
2554 	 * some initPlans have extParams that are setParams of other initPlans.)
2555 	 */
2556 
2557 	/* allParam must include initplans' extParams and setParams */
2558 	plan->allParam = bms_union(context.paramids, initExtParam);
2559 	plan->allParam = bms_add_members(plan->allParam, initSetParam);
2560 	/* extParam must include any initplan extParams */
2561 	plan->extParam = bms_union(context.paramids, initExtParam);
2562 	/* but not any initplan setParams */
2563 	plan->extParam = bms_del_members(plan->extParam, initSetParam);
2564 
2565 	/*
2566 	 * For speed at execution time, make sure extParam/allParam are actually
2567 	 * NULL if they are empty sets.
2568 	 */
2569 	if (bms_is_empty(plan->extParam))
2570 		plan->extParam = NULL;
2571 	if (bms_is_empty(plan->allParam))
2572 		plan->allParam = NULL;
2573 
2574 	return plan->allParam;
2575 }
2576 
2577 /*
2578  * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
2579  * expression tree to the result set.
2580  */
2581 static bool
finalize_primnode(Node * node,finalize_primnode_context * context)2582 finalize_primnode(Node *node, finalize_primnode_context *context)
2583 {
2584 	if (node == NULL)
2585 		return false;
2586 	if (IsA(node, Param))
2587 	{
2588 		if (((Param *) node)->paramkind == PARAM_EXEC)
2589 		{
2590 			int			paramid = ((Param *) node)->paramid;
2591 
2592 			context->paramids = bms_add_member(context->paramids, paramid);
2593 		}
2594 		return false;			/* no more to do here */
2595 	}
2596 	if (IsA(node, SubPlan))
2597 	{
2598 		SubPlan    *subplan = (SubPlan *) node;
2599 		Plan	   *plan = planner_subplan_get_plan(context->root, subplan);
2600 		ListCell   *lc;
2601 		Bitmapset  *subparamids;
2602 
2603 		/* Recurse into the testexpr, but not into the Plan */
2604 		finalize_primnode(subplan->testexpr, context);
2605 
2606 		/*
2607 		 * Remove any param IDs of output parameters of the subplan that were
2608 		 * referenced in the testexpr.  These are not interesting for
2609 		 * parameter change signaling since we always re-evaluate the subplan.
2610 		 * Note that this wouldn't work too well if there might be uses of the
2611 		 * same param IDs elsewhere in the plan, but that can't happen because
2612 		 * generate_new_exec_param never tries to merge params.
2613 		 */
2614 		foreach(lc, subplan->paramIds)
2615 		{
2616 			context->paramids = bms_del_member(context->paramids,
2617 											   lfirst_int(lc));
2618 		}
2619 
2620 		/* Also examine args list */
2621 		finalize_primnode((Node *) subplan->args, context);
2622 
2623 		/*
2624 		 * Add params needed by the subplan to paramids, but excluding those
2625 		 * we will pass down to it.  (We assume SS_finalize_plan was run on
2626 		 * the subplan already.)
2627 		 */
2628 		subparamids = bms_copy(plan->extParam);
2629 		foreach(lc, subplan->parParam)
2630 		{
2631 			subparamids = bms_del_member(subparamids, lfirst_int(lc));
2632 		}
2633 		context->paramids = bms_join(context->paramids, subparamids);
2634 
2635 		return false;			/* no more to do here */
2636 	}
2637 	return expression_tree_walker(node, finalize_primnode,
2638 								  (void *) context);
2639 }
2640 
2641 /*
2642  * finalize_agg_primnode: find all Aggref nodes in the given expression tree,
2643  * and add IDs of all PARAM_EXEC params appearing within their aggregated
2644  * arguments to the result set.
2645  */
2646 static bool
finalize_agg_primnode(Node * node,finalize_primnode_context * context)2647 finalize_agg_primnode(Node *node, finalize_primnode_context *context)
2648 {
2649 	if (node == NULL)
2650 		return false;
2651 	if (IsA(node, Aggref))
2652 	{
2653 		Aggref	   *agg = (Aggref *) node;
2654 
2655 		/* we should not consider the direct arguments, if any */
2656 		finalize_primnode((Node *) agg->args, context);
2657 		finalize_primnode((Node *) agg->aggfilter, context);
2658 		return false;			/* there can't be any Aggrefs below here */
2659 	}
2660 	return expression_tree_walker(node, finalize_agg_primnode,
2661 								  (void *) context);
2662 }
2663 
2664 /*
2665  * SS_make_initplan_output_param - make a Param for an initPlan's output
2666  *
2667  * The plan is expected to return a scalar value of the given type/collation.
2668  *
2669  * Note that in some cases the initplan may not ever appear in the finished
2670  * plan tree.  If that happens, we'll have wasted a PARAM_EXEC slot, which
2671  * is no big deal.
2672  */
2673 Param *
SS_make_initplan_output_param(PlannerInfo * root,Oid resulttype,int32 resulttypmod,Oid resultcollation)2674 SS_make_initplan_output_param(PlannerInfo *root,
2675 							  Oid resulttype, int32 resulttypmod,
2676 							  Oid resultcollation)
2677 {
2678 	return generate_new_exec_param(root, resulttype,
2679 								   resulttypmod, resultcollation);
2680 }
2681 
2682 /*
2683  * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
2684  *
2685  * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
2686  * list for the outer query level.  A Param that represents the initplan's
2687  * output has already been assigned using SS_make_initplan_output_param.
2688  */
2689 void
SS_make_initplan_from_plan(PlannerInfo * root,PlannerInfo * subroot,Plan * plan,Param * prm)2690 SS_make_initplan_from_plan(PlannerInfo *root,
2691 						   PlannerInfo *subroot, Plan *plan,
2692 						   Param *prm)
2693 {
2694 	SubPlan    *node;
2695 
2696 	/*
2697 	 * Add the subplan and its PlannerInfo to the global lists.
2698 	 */
2699 	root->glob->subplans = lappend(root->glob->subplans, plan);
2700 	root->glob->subroots = lappend(root->glob->subroots, subroot);
2701 
2702 	/*
2703 	 * Create a SubPlan node and add it to the outer list of InitPlans. Note
2704 	 * it has to appear after any other InitPlans it might depend on (see
2705 	 * comments in ExecReScan).
2706 	 */
2707 	node = makeNode(SubPlan);
2708 	node->subLinkType = EXPR_SUBLINK;
2709 	node->plan_id = list_length(root->glob->subplans);
2710 	node->plan_name = psprintf("InitPlan %d (returns $%d)",
2711 							   node->plan_id, prm->paramid);
2712 	get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
2713 					   &node->firstColCollation);
2714 	node->setParam = list_make1_int(prm->paramid);
2715 
2716 	root->init_plans = lappend(root->init_plans, node);
2717 
2718 	/*
2719 	 * The node can't have any inputs (since it's an initplan), so the
2720 	 * parParam and args lists remain empty.
2721 	 */
2722 
2723 	/* Set costs of SubPlan using info from the plan tree */
2724 	cost_subplan(subroot, node, plan);
2725 }
2726