subselect.c 21.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * subselect.c
4 5
 *	  Planning routines for subselects and parameters.
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/plan/subselect.c,v 1.58 2002/11/30 05:21:03 tgl Exp $
11 12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

16
#include "catalog/pg_operator.h"
17 18 19
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
20 21
#include "optimizer/cost.h"
#include "optimizer/planmain.h"
B
Bruce Momjian 已提交
22 23
#include "optimizer/planner.h"
#include "optimizer/subselect.h"
24
#include "parser/parsetree.h"
25 26
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
27
#include "utils/syscache.h"
28

29

30
Index		PlannerQueryLevel;	/* level of current query */
31
List	   *PlannerInitPlan;	/* init subplans for current query */
32
List	   *PlannerParamVar;	/* to get Var from Param->paramid */
33 34

int			PlannerPlanId = 0;	/* to assign unique ID to subquery plans */
35 36 37 38 39 40 41 42 43 44 45 46

/*--------------------
 * PlannerParamVar is a list of Var nodes, wherein the n'th entry
 * (n counts from 0) corresponds to Param->paramid = n.  The Var nodes
 * are ordinary except for one thing: their varlevelsup field does NOT
 * have the usual interpretation of "subplan levels out from current".
 * Instead, it contains the absolute plan level, with the outermost
 * plan being level 1 and nested plans having higher level numbers.
 * This nonstandardness is useful because we don't have to run around
 * and update the list elements when we enter or exit a subplan
 * recursion level.  But we must pay attention not to confuse this
 * meaning with the normal meaning of varlevelsup.
47 48 49 50
 *
 * We also need to create Param slots that don't correspond to any outer Var.
 * For these, we set varno = 0 and varlevelsup = 0, so that they can't
 * accidentally match an outer Var.
51 52
 *--------------------
 */
53 54


55 56 57 58
static void convert_sublink_opers(SubLink *slink, List *targetlist,
								  List **setParams);


59 60 61
/*
 * Create a new entry in the PlannerParamVar list, and return its index.
 *
62 63 64 65
 * var contains the data to use, except for varlevelsup which
 * is set from the absolute level value given by varlevel.  NOTE that
 * the passed var is scribbled on and placed directly into the list!
 * Generally, caller should have just created or copied it.
66
 */
67
static int
68
new_param(Var *var, Index varlevel)
69
{
70
	var->varlevelsup = varlevel;
71

72
	PlannerParamVar = lappend(PlannerParamVar, var);
73

74
	return length(PlannerParamVar) - 1;
75 76
}

77 78 79 80
/*
 * Generate a Param node to replace the given Var,
 * which is expected to have varlevelsup > 0 (ie, it is not local).
 */
81
static Param *
82
replace_var(Var *var)
83
{
84
	List	   *ppv;
85
	Param	   *retval;
86
	Index		varlevel;
87 88
	int			i;

89 90
	Assert(var->varlevelsup > 0 && var->varlevelsup < PlannerQueryLevel);
	varlevel = PlannerQueryLevel - var->varlevelsup;
91

92
	/*
93
	 * If there's already a PlannerParamVar entry for this same Var, just
B
Bruce Momjian 已提交
94 95 96 97 98 99
	 * use it.	NOTE: in sufficiently complex querytrees, it is possible
	 * for the same varno/varlevel to refer to different RTEs in different
	 * parts of the parsetree, so that different fields might end up
	 * sharing the same Param number.  As long as we check the vartype as
	 * well, I believe that this sort of aliasing will cause no trouble.
	 * The correct field should get stored into the Param slot at
100
	 * execution in each part of the tree.
101 102 103
	 */
	i = 0;
	foreach(ppv, PlannerParamVar)
104
	{
105
		Var		   *pvar = lfirst(ppv);
106 107 108 109 110

		if (pvar->varno == var->varno &&
			pvar->varattno == var->varattno &&
			pvar->varlevelsup == varlevel &&
			pvar->vartype == var->vartype)
111
			break;
112
		i++;
113
	}
114

115
	if (!ppv)
116 117
	{
		/* Nope, so make a new one */
118
		i = new_param((Var *) copyObject(var), varlevel);
119
	}
120

121 122 123 124
	retval = makeNode(Param);
	retval->paramkind = PARAM_EXEC;
	retval->paramid = (AttrNumber) i;
	retval->paramtype = var->vartype;
125

126
	return retval;
127 128
}

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
/*
 * Generate a new Param node that will not conflict with any other.
 */
static Param *
generate_new_param(Oid paramtype, int32 paramtypmod)
{
	Var		   *var = makeVar(0, 0, paramtype, paramtypmod, 0);
	Param	   *retval = makeNode(Param);

	retval->paramkind = PARAM_EXEC;
	retval->paramid = (AttrNumber) new_param(var, 0);
	retval->paramtype = paramtype;

	return retval;
}

145 146 147
/*
 * Convert a bare SubLink (as created by the parser) into a SubPlan.
 */
148
static Node *
149
make_subplan(SubLink *slink)
150
{
151
	SubPlan    *node = makeNode(SubPlan);
152
	Query	   *subquery = (Query *) (slink->subselect);
153
	Oid			result_type = exprType((Node *) slink);
154
	double		tuple_fraction;
155 156 157
	Plan	   *plan;
	List	   *lst;
	Node	   *result;
158

159 160 161 162
	/*
	 * Check to see if this node was already processed; if so we have
	 * trouble.  We check to see if the linked-to Query appears to have
	 * been planned already, too.
163 164
	 */
	if (subquery == NULL)
165 166
		elog(ERROR, "make_subplan: invalid expression structure (SubLink already processed?)");
	if (subquery->base_rel_list != NIL)
167 168
		elog(ERROR, "make_subplan: invalid expression structure (subquery already processed?)");

169
	/*
B
Bruce Momjian 已提交
170 171 172 173
	 * Copy the source Query node.	This is a quick and dirty kluge to
	 * resolve the fact that the parser can generate trees with multiple
	 * links to the same sub-Query node, but the planner wants to scribble
	 * on the Query. Try to clean this up when we do querytree redesign...
174 175 176
	 */
	subquery = (Query *) copyObject(subquery);

177
	/*
178 179 180 181 182 183 184
	 * For an EXISTS subplan, tell lower-level planner to expect that only
	 * the first tuple will be retrieved.  For ALL and ANY subplans, we
	 * will be able to stop evaluating if the test condition fails, so
	 * very often not all the tuples will be retrieved; for lack of a
	 * better idea, specify 50% retrieval.	For EXPR and MULTIEXPR
	 * subplans, use default behavior (we're only expecting one row out,
	 * anyway).
185
	 *
186 187 188
	 * NOTE: if you change these numbers, also change cost_qual_eval_walker()
	 * in path/costsize.c.
	 *
189 190 191 192 193 194 195 196
	 * XXX If an ALL/ANY subplan is uncorrelated, we may decide to
	 * materialize its result below.  In that case it would've been better
	 * to specify full retrieval.  At present, however, we can only detect
	 * correlation or lack of it after we've made the subplan :-(. Perhaps
	 * detection of correlation should be done as a separate step.
	 * Meanwhile, we don't want to be too optimistic about the percentage
	 * of tuples retrieved, for fear of selecting a plan that's bad for
	 * the materialization case.
197 198 199
	 */
	if (slink->subLinkType == EXISTS_SUBLINK)
		tuple_fraction = 1.0;	/* just like a LIMIT 1 */
200 201
	else if (slink->subLinkType == ALL_SUBLINK ||
			 slink->subLinkType == ANY_SUBLINK)
202
		tuple_fraction = 0.5;	/* 50% */
203 204
	else
		tuple_fraction = -1.0;	/* default behavior */
205

206
	/*
207
	 * Generate the plan for the subquery.
208
	 */
209
	node->plan = plan = subquery_planner(subquery, tuple_fraction);
210

B
Bruce Momjian 已提交
211 212
	node->plan_id = PlannerPlanId++;	/* Assign unique ID to this
										 * SubPlan */
213

214
	node->rtable = subquery->rtable;
215
	node->sublink = slink;
216

217
	slink->subselect = NULL;	/* cool ?! see error check above! */
218

219
	/*
B
Bruce Momjian 已提交
220 221
	 * Make parParam list of params that current query level will pass to
	 * this child plan.
222
	 */
223
	foreach(lst, plan->extParam)
224
	{
225 226
		int			paramid = lfirsti(lst);
		Var		   *var = nth(paramid, PlannerParamVar);
227

228
		/* note varlevelsup is absolute level number */
229
		if (var->varlevelsup == PlannerQueryLevel)
230
			node->parParam = lappendi(node->parParam, paramid);
231
	}
232 233

	/*
234
	 * Un-correlated or undirect correlated plans of EXISTS, EXPR, or
235 236
	 * MULTIEXPR types can be used as initPlans.  For EXISTS or EXPR, we
	 * just produce a Param referring to the result of evaluating the
237 238 239
	 * initPlan.  For MULTIEXPR, we must build an AND or OR-clause of the
	 * individual comparison operators, using the appropriate lefthand
	 * side expressions and Params for the initPlan's target items.
240
	 */
241 242
	if (node->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK)
	{
243
		Param	   *prm;
244

245
		prm = generate_new_param(BOOLOID, -1);
246 247 248 249 250 251 252
		node->setParam = lappendi(node->setParam, prm->paramid);
		PlannerInitPlan = lappend(PlannerInitPlan, node);
		result = (Node *) prm;
	}
	else if (node->parParam == NIL && slink->subLinkType == EXPR_SUBLINK)
	{
		TargetEntry *te = lfirst(plan->targetlist);
253
		Param	   *prm;
254

255
		prm = generate_new_param(te->resdom->restype, te->resdom->restypmod);
256 257 258 259 260
		node->setParam = lappendi(node->setParam, prm->paramid);
		PlannerInitPlan = lappend(PlannerInitPlan, node);
		result = (Node *) prm;
	}
	else if (node->parParam == NIL && slink->subLinkType == MULTIEXPR_SUBLINK)
261
	{
262
		convert_sublink_opers(slink, plan->targetlist, &node->setParam);
263
		PlannerInitPlan = lappend(PlannerInitPlan, node);
264 265 266
		if (length(slink->oper) > 1)
			result = (Node *) ((slink->useor) ? make_orclause(slink->oper) :
							   make_andclause(slink->oper));
267
		else
268
			result = (Node *) lfirst(slink->oper);
269
	}
270
	else
271
	{
272
		Expr	   *expr = makeNode(Expr);
273
		List	   *args = NIL;
274

275
		/*
276 277 278 279 280 281 282 283 284 285
		 * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types
		 * to initPlans, even when they are uncorrelated or undirect
		 * correlated, because we need to scan the output of the subplan
		 * for each outer tuple.  However, we have the option to tack a
		 * MATERIAL node onto the top of an uncorrelated/undirect
		 * correlated subplan, which lets us do the work of evaluating the
		 * subplan only once.  We do this if the subplan's top plan node
		 * is anything more complicated than a plain sequential scan, and
		 * we do it even for seqscan if the qual appears selective enough
		 * to eliminate many tuples.
286 287 288 289 290 291
		 *
		 * XXX It's pretty ugly to be inserting a MATERIAL node at this
		 * point.  Since subquery_planner has already run SS_finalize_plan
		 * on the subplan tree, we have to kluge up parameter lists for
		 * the MATERIAL node.  Possibly this could be fixed by postponing
		 * SS_finalize_plan processing until setrefs.c is run.
292 293 294 295 296 297 298 299
		 */
		if (node->parParam == NIL)
		{
			bool		use_material;

			switch (nodeTag(plan))
			{
				case T_SeqScan:
300 301 302 303 304 305 306 307 308 309 310 311
					if (plan->initPlan || plan->subPlan)
						use_material = true;
					else
					{
						Selectivity qualsel;

						qualsel = clauselist_selectivity(subquery,
														 plan->qual,
														 0);
						/* Is 10% selectivity a good threshold?? */
						use_material = qualsel < 0.10;
					}
312 313
					break;
				case T_Material:
314
				case T_FunctionScan:
315
				case T_Sort:
316 317 318

					/*
					 * Don't add another Material node if there's one
319 320
					 * already, nor if the top node is any other type that
					 * materializes its output anyway.
321 322 323 324 325 326 327 328 329
					 */
					use_material = false;
					break;
				default:
					use_material = true;
					break;
			}
			if (use_material)
			{
B
Bruce Momjian 已提交
330
				Plan	   *matplan;
331
				Path		matpath; /* dummy for result of cost_material */
332 333

				matplan = (Plan *) make_material(plan->targetlist, plan);
334 335 336 337 338 339 340 341
				/* need to calculate costs */
				cost_material(&matpath,
							  plan->total_cost,
							  plan->plan_rows,
							  plan->plan_width);
				matplan->startup_cost = matpath.startup_cost;
				matplan->total_cost = matpath.total_cost;
				/* parameter kluge --- see comments above */
342 343 344
				matplan->extParam = listCopy(plan->extParam);
				matplan->locParam = listCopy(plan->locParam);
				node->plan = plan = matplan;
345 346 347
			}
		}

348 349 350
		/* Fix the SubLink's oper list */
		convert_sublink_opers(slink, plan->targetlist, NULL);

351 352 353
		/*
		 * Make expression of SUBPLAN type
		 */
354
		expr->typeOid = result_type;
355
		expr->opType = SUBPLAN_EXPR;
356 357 358
		expr->oper = (Node *) node;

		/*
359
		 * Make expr->args from parParam.
360
		 */
361
		foreach(lst, node->parParam)
362
		{
363 364 365
			Var		   *var = nth(lfirsti(lst), PlannerParamVar);

			var = (Var *) copyObject(var);
366 367 368 369 370

			/*
			 * Must fix absolute-level varlevelsup from the
			 * PlannerParamVar entry.  But since var is at current subplan
			 * level, this is easy:
371
			 */
372
			var->varlevelsup = 0;
373
			args = lappend(args, var);
374
		}
375
		expr->args = args;
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
		result = (Node *) expr;
	}

	return result;
}

/*
 * convert_sublink_opers: convert a SubLink's oper list from the
 * parser/rewriter format into the executor's format.
 *
 * The oper list is initially just a list of Oper nodes.  We replace it
 * with a list of actually executable expressions, in which the specified
 * operators are applied to corresponding elements of the lefthand list
 * and Params representing the results of the subplan.  lefthand is then
 * set to NIL.
 *
 * If setParams is not NULL, the paramids of the Params created are added
 * to the *setParams list.
 */
static void
convert_sublink_opers(SubLink *slink, List *targetlist,
					  List **setParams)
{
	List	   *newoper = NIL;
	List	   *leftlist = slink->lefthand;
	List	   *lst;

	foreach(lst, slink->oper)
	{
		Oper	   *oper = (Oper *) lfirst(lst);
		Node	   *lefthand = lfirst(leftlist);
		TargetEntry *te = lfirst(targetlist);
		Param	   *prm;
		Operator	tup;
		Form_pg_operator opform;
		Node	   *left,
				   *right;

		/* Make the Param node representing the subplan's result */
		prm = generate_new_param(te->resdom->restype,
								 te->resdom->restypmod);

		/* Record its ID if needed */
		if (setParams)
			*setParams = lappendi(*setParams, prm->paramid);

		/* Look up the operator to check its declared input types */
		Assert(IsA(oper, Oper));
		tup = SearchSysCache(OPEROID,
							 ObjectIdGetDatum(oper->opno),
							 0, 0, 0);
		if (!HeapTupleIsValid(tup))
			elog(ERROR, "cache lookup failed for operator %u", oper->opno);
		opform = (Form_pg_operator) GETSTRUCT(tup);

432
		/*
433 434 435 436
		 * Make the expression node.
		 *
		 * Note: we use make_operand in case runtime type conversion
		 * function calls must be inserted for this operator!
437
		 */
438 439 440 441 442 443
		left = make_operand(lefthand, exprType(lefthand), opform->oprleft);
		right = make_operand((Node *) prm, prm->paramtype, opform->oprright);
		newoper = lappend(newoper,
						  make_opclause(oper,
										(Var *) left,
										(Var *) right));
444

445 446 447 448
		ReleaseSysCache(tup);

		leftlist = lnext(leftlist);
		targetlist = lnext(targetlist);
449
	}
450

451 452
	slink->oper = newoper;
	slink->lefthand = NIL;
453 454
}

455 456
/*
 * finalize_primnode: build lists of subplans and params appearing
457 458
 * in the given expression tree.  NOTE: items are added to lists passed in,
 * so caller must initialize lists to NIL before first call!
459 460 461 462 463 464
 *
 * Note: the subplan list that is constructed here and assigned to the
 * plan's subPlan field will be replaced with an up-to-date list in
 * set_plan_references().  We could almost dispense with building this
 * subplan list at all; I believe the only place that uses it is the
 * check in make_subplan to see whether a subselect has any subselects.
465 466
 */

467 468 469 470
typedef struct finalize_primnode_results
{
	List	   *subplans;		/* List of subplans found in expr */
	List	   *paramids;		/* List of PARAM_EXEC paramids found */
471
} finalize_primnode_results;
472

473
static bool
474
finalize_primnode(Node *node, finalize_primnode_results *results)
475 476 477 478
{
	if (node == NULL)
		return false;
	if (IsA(node, Param))
479
	{
480 481
		if (((Param *) node)->paramkind == PARAM_EXEC)
		{
482
			int			paramid = (int) ((Param *) node)->paramid;
483

484
			if (!intMember(paramid, results->paramids))
485 486 487
				results->paramids = lconsi(paramid, results->paramids);
		}
		return false;			/* no more to do here */
488
	}
489
	if (is_subplan(node))
490
	{
491
		SubPlan    *subplan = (SubPlan *) ((Expr *) node)->oper;
492 493
		List	   *lst;

494 495 496 497
		/* Add subplan to subplans list */
		results->subplans = lappend(results->subplans, subplan);
		/* Check extParam list for params to add to paramids */
		foreach(lst, subplan->plan->extParam)
498
		{
499 500
			int			paramid = lfirsti(lst);
			Var		   *var = nth(paramid, PlannerParamVar);
501

502
			/* note varlevelsup is absolute level number */
503
			if (var->varlevelsup < PlannerQueryLevel &&
504
				!intMember(paramid, results->paramids))
505
				results->paramids = lconsi(paramid, results->paramids);
506
		}
507
		/* fall through to recurse into subplan args */
508
	}
509
	return expression_tree_walker(node, finalize_primnode,
510
								  (void *) results);
511 512
}

513 514
/*
 * Replace correlation vars (uplevel vars) with Params.
515
 */
516 517 518

static Node *replace_correlation_vars_mutator(Node *node, void *context);

519
Node *
520
SS_replace_correlation_vars(Node *expr)
521
{
522 523 524
	/* No setup needed for tree walk, so away we go */
	return replace_correlation_vars_mutator(expr, NULL);
}
525

526 527 528 529 530 531
static Node *
replace_correlation_vars_mutator(Node *node, void *context)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
532
	{
533 534
		if (((Var *) node)->varlevelsup > 0)
			return (Node *) replace_var((Var *) node);
535
	}
536 537 538
	return expression_tree_mutator(node,
								   replace_correlation_vars_mutator,
								   context);
539 540
}

541 542
/*
 * Expand SubLinks to SubPlans in the given expression.
543
 */
544 545 546

static Node *process_sublinks_mutator(Node *node, void *context);

547 548
Node *
SS_process_sublinks(Node *expr)
549
{
550
	/* No setup needed for tree walk, so away we go */
551
	return process_sublinks_mutator(expr, NULL);
552 553 554 555 556 557
}

static Node *
process_sublinks_mutator(Node *node, void *context)
{
	if (node == NULL)
558
		return NULL;
559
	if (IsA(node, SubLink))
560
	{
561
		SubLink    *sublink = (SubLink *) node;
562

563 564 565 566
		/*
		 * First, scan the lefthand-side expressions, if any. This is a
		 * tad klugy since we modify the input SubLink node, but that
		 * should be OK (make_subplan does it too!)
567
		 */
568 569 570 571
		sublink->lefthand = (List *)
			process_sublinks_mutator((Node *) sublink->lefthand, context);
		/* Now build the SubPlan node and make the expr to return */
		return make_subplan(sublink);
572
	}
573

574 575
	/*
	 * Note that we will never see a SubPlan expression in the input
576 577 578
	 * (since this is the very routine that creates 'em to begin with). So
	 * the code in expression_tree_mutator() that might do inappropriate
	 * things with SubPlans or SubLinks will not be exercised.
579
	 */
580
	Assert(!is_subplan(node));
581

582 583 584
	return expression_tree_mutator(node,
								   process_sublinks_mutator,
								   context);
585 586
}

587
List *
588
SS_finalize_plan(Plan *plan, List *rtable)
589
{
590 591 592
	List	   *extParam = NIL;
	List	   *locParam = NIL;
	finalize_primnode_results results;
593 594 595
	List	   *lst;

	if (plan == NULL)
596
		return NIL;
597

598 599
	results.subplans = NIL;		/* initialize lists to NIL */
	results.paramids = NIL;
600

601 602
	/*
	 * When we call finalize_primnode, results.paramids lists are
603 604 605 606
	 * automatically merged together.  But when recursing to self, we have
	 * to do it the hard way.  We want the paramids list to include params
	 * in subplans as well as at this level. (We don't care about finding
	 * subplans of subplans, though.)
607 608 609
	 */

	/* Find params and subplans in targetlist and qual */
610
	finalize_primnode((Node *) plan->targetlist, &results);
611
	finalize_primnode((Node *) plan->qual, &results);
612

613
	/* Check additional node-type-specific fields */
614 615 616
	switch (nodeTag(plan))
	{
		case T_Result:
617 618
			finalize_primnode(((Result *) plan)->resconstantqual,
							  &results);
619 620
			break;

621 622 623 624 625 626 627 628 629 630 631 632 633 634
		case T_IndexScan:
			finalize_primnode((Node *) ((IndexScan *) plan)->indxqual,
							  &results);

			/*
			 * we need not look at indxqualorig, since it will have the
			 * same param references as indxqual, and we aren't really
			 * concerned yet about having a complete subplan list.
			 */
			break;

		case T_TidScan:
			finalize_primnode((Node *) ((TidScan *) plan)->tideval,
							  &results);
635
			break;
636

637
		case T_SubqueryScan:
B
Bruce Momjian 已提交
638

639
			/*
B
Bruce Momjian 已提交
640 641 642 643 644
			 * In a SubqueryScan, SS_finalize_plan has already been run on
			 * the subplan by the inner invocation of subquery_planner, so
			 * there's no need to do it again.  Instead, just pull out the
			 * subplan's extParams list, which represents the params it
			 * needs from my level and higher levels.
645
			 */
646
			results.paramids = set_unioni(results.paramids,
B
Bruce Momjian 已提交
647
							 ((SubqueryScan *) plan)->subplan->extParam);
648 649
			break;

650 651 652
		case T_FunctionScan:
			{
				RangeTblEntry *rte;
653

654 655 656 657 658 659 660 661 662 663
				rte = rt_fetch(((FunctionScan *) plan)->scan.scanrelid,
							   rtable);
				Assert(rte->rtekind == RTE_FUNCTION);
				finalize_primnode(rte->funcexpr, &results);
			}
			break;

		case T_Append:
			foreach(lst, ((Append *) plan)->appendplans)
				results.paramids = set_unioni(results.paramids,
B
Bruce Momjian 已提交
664 665
								   SS_finalize_plan((Plan *) lfirst(lst),
													rtable));
666 667
			break;

668 669 670 671 672
		case T_NestLoop:
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
			break;

673
		case T_MergeJoin:
674 675
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
676 677
			finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
							  &results);
678 679 680
			break;

		case T_HashJoin:
681 682
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
683 684
			finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
							  &results);
685
			break;
686

687
		case T_Hash:
688
			finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
689
							  &results);
690 691 692 693 694 695 696
			break;

		case T_Agg:
		case T_SeqScan:
		case T_Material:
		case T_Sort:
		case T_Unique:
697
		case T_SetOp:
698
		case T_Limit:
699 700
		case T_Group:
			break;
701

702
		default:
703 704
			elog(ERROR, "SS_finalize_plan: node %d unsupported",
				 nodeTag(plan));
705
	}
706

707
	/* Process left and right subplans, if any */
708
	results.paramids = set_unioni(results.paramids,
709 710
								  SS_finalize_plan(plan->lefttree,
												   rtable));
711
	results.paramids = set_unioni(results.paramids,
712 713
								  SS_finalize_plan(plan->righttree,
												   rtable));
714 715

	/* Now we have all the paramids and subplans */
716

717
	foreach(lst, results.paramids)
718
	{
719 720
		int			paramid = lfirsti(lst);
		Var		   *var = nth(paramid, PlannerParamVar);
721

722
		/* note varlevelsup is absolute level number */
723
		if (var->varlevelsup < PlannerQueryLevel)
724
			extParam = lappendi(extParam, paramid);
725
		else if (var->varlevelsup > PlannerQueryLevel)
726
			elog(ERROR, "SS_finalize_plan: plan shouldn't reference subplan's variable");
727 728
		else
		{
729
			Assert(var->varno == 0 && var->varattno == 0);
730
			locParam = lappendi(locParam, paramid);
731 732
		}
	}
733

734 735
	plan->extParam = extParam;
	plan->locParam = locParam;
736
	plan->subPlan = results.subplans;
737

738
	return results.paramids;
739
}