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
B
Bruce Momjian 已提交
10
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/plan/subselect.c,v 1.55 2002/09/04 20:31:21 momjian 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 47 48

/*--------------------
 * 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.
 *--------------------
 */
49 50


51 52 53 54 55 56
/*
 * Create a new entry in the PlannerParamVar list, and return its index.
 *
 * var contains the data to be copied, except for varlevelsup which
 * is set from the absolute level value given by varlevel.
 */
57
static int
58
new_param(Var *var, Index varlevel)
59
{
60
	Var		   *paramVar = (Var *) copyObject(var);
61

62
	paramVar->varlevelsup = varlevel;
63

64
	PlannerParamVar = lappend(PlannerParamVar, paramVar);
65

66
	return length(PlannerParamVar) - 1;
67 68
}

69 70 71 72
/*
 * Generate a Param node to replace the given Var,
 * which is expected to have varlevelsup > 0 (ie, it is not local).
 */
73
static Param *
74
replace_var(Var *var)
75
{
76
	List	   *ppv;
77
	Param	   *retval;
78
	Index		varlevel;
79 80
	int			i;

81 82
	Assert(var->varlevelsup > 0 && var->varlevelsup < PlannerQueryLevel);
	varlevel = PlannerQueryLevel - var->varlevelsup;
83

84
	/*
85
	 * If there's already a PlannerParamVar entry for this same Var, just
B
Bruce Momjian 已提交
86 87 88 89 90 91
	 * 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
92
	 * execution in each part of the tree.
93 94 95
	 */
	i = 0;
	foreach(ppv, PlannerParamVar)
96
	{
97
		Var		   *pvar = lfirst(ppv);
98 99 100 101 102

		if (pvar->varno == var->varno &&
			pvar->varattno == var->varattno &&
			pvar->varlevelsup == varlevel &&
			pvar->vartype == var->vartype)
103
			break;
104
		i++;
105
	}
106

107
	if (!ppv)
108 109
	{
		/* Nope, so make a new one */
110
		i = new_param(var, varlevel);
111
	}
112

113 114 115 116
	retval = makeNode(Param);
	retval->paramkind = PARAM_EXEC;
	retval->paramid = (AttrNumber) i;
	retval->paramtype = var->vartype;
117

118
	return retval;
119 120
}

121 122 123
/*
 * Convert a bare SubLink (as created by the parser) into a SubPlan.
 */
124
static Node *
125
make_subplan(SubLink *slink)
126
{
127
	SubPlan    *node = makeNode(SubPlan);
128
	Query	   *subquery = (Query *) (slink->subselect);
129
	Oid			result_type = exprType((Node *) slink);
130
	double		tuple_fraction;
131 132 133
	Plan	   *plan;
	List	   *lst;
	Node	   *result;
134

135 136 137 138
	/*
	 * 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.
139 140
	 */
	if (subquery == NULL)
141 142
		elog(ERROR, "make_subplan: invalid expression structure (SubLink already processed?)");
	if (subquery->base_rel_list != NIL)
143 144
		elog(ERROR, "make_subplan: invalid expression structure (subquery already processed?)");

145
	/*
B
Bruce Momjian 已提交
146 147 148 149
	 * 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...
150 151 152
	 */
	subquery = (Query *) copyObject(subquery);

153
	/*
154 155 156 157 158 159 160
	 * 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).
161
	 *
162 163 164
	 * NOTE: if you change these numbers, also change cost_qual_eval_walker()
	 * in path/costsize.c.
	 *
165 166 167 168 169 170 171 172
	 * 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.
173 174 175
	 */
	if (slink->subLinkType == EXISTS_SUBLINK)
		tuple_fraction = 1.0;	/* just like a LIMIT 1 */
176 177
	else if (slink->subLinkType == ALL_SUBLINK ||
			 slink->subLinkType == ANY_SUBLINK)
178
		tuple_fraction = 0.5;	/* 50% */
179 180
	else
		tuple_fraction = -1.0;	/* default behavior */
181

182
	/*
183
	 * Generate the plan for the subquery.
184
	 */
185
	node->plan = plan = subquery_planner(subquery, tuple_fraction);
186

B
Bruce Momjian 已提交
187 188
	node->plan_id = PlannerPlanId++;	/* Assign unique ID to this
										 * SubPlan */
189

190
	node->rtable = subquery->rtable;
191
	node->sublink = slink;
192

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

195
	/*
B
Bruce Momjian 已提交
196 197
	 * Make parParam list of params that current query level will pass to
	 * this child plan.
198
	 */
199
	foreach(lst, plan->extParam)
200
	{
201 202
		int			paramid = lfirsti(lst);
		Var		   *var = nth(paramid, PlannerParamVar);
203

204
		/* note varlevelsup is absolute level number */
205
		if (var->varlevelsup == PlannerQueryLevel)
206
			node->parParam = lappendi(node->parParam, paramid);
207
	}
208 209

	/*
210
	 * Un-correlated or undirect correlated plans of EXISTS, EXPR, or
211 212
	 * MULTIEXPR types can be used as initPlans.  For EXISTS or EXPR, we
	 * just produce a Param referring to the result of evaluating the
213 214 215
	 * 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.
216
	 */
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	if (node->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK)
	{
		Var		   *var = makeVar(0, 0, BOOLOID, -1, 0);
		Param	   *prm = makeNode(Param);

		prm->paramkind = PARAM_EXEC;
		prm->paramid = (AttrNumber) new_param(var, PlannerQueryLevel);
		prm->paramtype = var->vartype;
		pfree(var);				/* var is only needed for new_param */
		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);
233

234 235 236 237 238 239 240 241 242 243 244 245 246 247
		/* need a var node just to pass to new_param()... */
		Var		   *var = makeVar(0, 0, te->resdom->restype,
								  te->resdom->restypmod, 0);
		Param	   *prm = makeNode(Param);

		prm->paramkind = PARAM_EXEC;
		prm->paramid = (AttrNumber) new_param(var, PlannerQueryLevel);
		prm->paramtype = var->vartype;
		pfree(var);				/* var is only needed for new_param */
		node->setParam = lappendi(node->setParam, prm->paramid);
		PlannerInitPlan = lappend(PlannerInitPlan, node);
		result = (Node *) prm;
	}
	else if (node->parParam == NIL && slink->subLinkType == MULTIEXPR_SUBLINK)
248
	{
249
		List	   *newoper = NIL;
250 251
		int			i = 0;

252
		/*
253 254
		 * Convert oper list of Opers into a list of Exprs, using lefthand
		 * arguments and Params representing inside results.
255
		 */
256
		foreach(lst, slink->oper)
257
		{
258 259
			Oper	   *oper = (Oper *) lfirst(lst);
			Node	   *lefthand = nth(i, slink->lefthand);
260
			TargetEntry *te = nth(i, plan->targetlist);
261

262
			/* need a var node just to pass to new_param()... */
263
			Var		   *var = makeVar(0, 0, te->resdom->restype,
264
									  te->resdom->restypmod, 0);
265
			Param	   *prm = makeNode(Param);
266 267 268 269
			Operator	tup;
			Form_pg_operator opform;
			Node	   *left,
					   *right;
270

271
			prm->paramkind = PARAM_EXEC;
272
			prm->paramid = (AttrNumber) new_param(var, PlannerQueryLevel);
273
			prm->paramtype = var->vartype;
274
			pfree(var);			/* var is only needed for new_param */
275 276

			Assert(IsA(oper, Oper));
277 278 279
			tup = SearchSysCache(OPEROID,
								 ObjectIdGetDatum(oper->opno),
								 0, 0, 0);
B
Bruce Momjian 已提交
280
			if (!HeapTupleIsValid(tup))
281
				elog(ERROR, "cache lookup failed for operator %u", oper->opno);
282
			opform = (Form_pg_operator) GETSTRUCT(tup);
283 284 285

			/*
			 * Note: we use make_operand in case runtime type conversion
286 287
			 * function calls must be inserted for this operator!
			 */
288
			left = make_operand(lefthand,
289
								exprType(lefthand), opform->oprleft);
290
			right = make_operand((Node *) prm,
291
								 prm->paramtype, opform->oprright);
292 293
			ReleaseSysCache(tup);

294 295 296 297
			newoper = lappend(newoper,
							  make_opclause(oper,
											(Var *) left,
											(Var *) right));
298
			node->setParam = lappendi(node->setParam, prm->paramid);
299 300
			i++;
		}
301 302
		slink->oper = newoper;
		slink->lefthand = NIL;
303 304
		PlannerInitPlan = lappend(PlannerInitPlan, node);
		if (i > 1)
305 306
			result = (Node *) ((slink->useor) ? make_orclause(newoper) :
							   make_andclause(newoper));
307
		else
308
			result = (Node *) lfirst(newoper);
309
	}
310
	else
311
	{
312
		Expr	   *expr = makeNode(Expr);
313
		List	   *args = NIL;
314
		List	   *newoper = NIL;
315 316
		int			i = 0;

317
		/*
318 319 320 321 322 323 324 325 326 327
		 * 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.
328 329 330 331 332 333
		 *
		 * 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.
334 335 336 337 338 339 340 341
		 */
		if (node->parParam == NIL)
		{
			bool		use_material;

			switch (nodeTag(plan))
			{
				case T_SeqScan:
342 343 344 345 346 347 348 349 350 351 352 353
					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;
					}
354 355
					break;
				case T_Material:
356
				case T_FunctionScan:
357
				case T_Sort:
358 359 360

					/*
					 * Don't add another Material node if there's one
361 362
					 * already, nor if the top node is any other type that
					 * materializes its output anyway.
363 364 365 366 367 368 369 370 371
					 */
					use_material = false;
					break;
				default:
					use_material = true;
					break;
			}
			if (use_material)
			{
B
Bruce Momjian 已提交
372
				Plan	   *matplan;
373 374 375 376 377 378

				matplan = (Plan *) make_material(plan->targetlist, plan);
				/* kluge --- see comments above */
				matplan->extParam = listCopy(plan->extParam);
				matplan->locParam = listCopy(plan->locParam);
				node->plan = plan = matplan;
379 380 381 382 383 384
			}
		}

		/*
		 * Make expression of SUBPLAN type
		 */
385
		expr->typeOid = result_type;
386
		expr->opType = SUBPLAN_EXPR;
387 388 389
		expr->oper = (Node *) node;

		/*
390
		 * Make expr->args from parParam.
391
		 */
392
		foreach(lst, node->parParam)
393
		{
394 395 396
			Var		   *var = nth(lfirsti(lst), PlannerParamVar);

			var = (Var *) copyObject(var);
397 398 399 400 401

			/*
			 * Must fix absolute-level varlevelsup from the
			 * PlannerParamVar entry.  But since var is at current subplan
			 * level, this is easy:
402
			 */
403
			var->varlevelsup = 0;
404
			args = lappend(args, var);
405
		}
406
		expr->args = args;
407

408
		/*
409 410
		 * Convert oper list of Opers into a list of Exprs, using lefthand
		 * arguments and Consts representing inside results.
411
		 */
412
		foreach(lst, slink->oper)
413
		{
414 415
			Oper	   *oper = (Oper *) lfirst(lst);
			Node	   *lefthand = nth(i, slink->lefthand);
416
			TargetEntry *te = nth(i, plan->targetlist);
417 418 419 420 421 422
			Const	   *con;
			Operator	tup;
			Form_pg_operator opform;
			Node	   *left,
					   *right;

423
			con = makeNullConst(te->resdom->restype);
424 425

			Assert(IsA(oper, Oper));
426 427 428
			tup = SearchSysCache(OPEROID,
								 ObjectIdGetDatum(oper->opno),
								 0, 0, 0);
B
Bruce Momjian 已提交
429
			if (!HeapTupleIsValid(tup))
430
				elog(ERROR, "cache lookup failed for operator %u", oper->opno);
431
			opform = (Form_pg_operator) GETSTRUCT(tup);
432 433 434

			/*
			 * Note: we use make_operand in case runtime type conversion
435 436
			 * function calls must be inserted for this operator!
			 */
437
			left = make_operand(lefthand,
438
								exprType(lefthand), opform->oprleft);
439
			right = make_operand((Node *) con,
440
								 con->consttype, opform->oprright);
441 442
			ReleaseSysCache(tup);

443 444 445 446
			newoper = lappend(newoper,
							  make_opclause(oper,
											(Var *) left,
											(Var *) right));
447 448
			i++;
		}
449 450
		slink->oper = newoper;
		slink->lefthand = NIL;
451
		result = (Node *) expr;
452
	}
453

454
	return result;
455 456
}

457 458
/*
 * finalize_primnode: build lists of subplans and params appearing
459 460
 * in the given expression tree.  NOTE: items are added to lists passed in,
 * so caller must initialize lists to NIL before first call!
461 462 463 464 465 466
 *
 * 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.
467 468
 */

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

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

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

496 497 498 499
		/* 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)
500
		{
501 502
			int			paramid = lfirsti(lst);
			Var		   *var = nth(paramid, PlannerParamVar);
503

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

515 516
/*
 * Replace correlation vars (uplevel vars) with Params.
517
 */
518 519 520

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

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

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

543 544
/*
 * Expand SubLinks to SubPlans in the given expression.
545
 */
546 547 548

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

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

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

565 566 567 568
		/*
		 * 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!)
569
		 */
570 571 572 573
		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);
574
	}
575

576 577
	/*
	 * Note that we will never see a SubPlan expression in the input
578 579 580
	 * (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.
581
	 */
582
	Assert(!is_subplan(node));
583

584 585 586
	return expression_tree_mutator(node,
								   process_sublinks_mutator,
								   context);
587 588
}

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

	if (plan == NULL)
598
		return NIL;
599

600 601
	results.subplans = NIL;		/* initialize lists to NIL */
	results.paramids = NIL;
602

603 604
	/*
	 * When we call finalize_primnode, results.paramids lists are
605 606 607 608
	 * 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.)
609 610 611
	 */

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

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

623 624 625 626 627 628 629 630 631 632 633 634 635 636
		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);
637
			break;
638

639
		case T_SubqueryScan:
B
Bruce Momjian 已提交
640

641
			/*
B
Bruce Momjian 已提交
642 643 644 645 646
			 * 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.
647
			 */
648
			results.paramids = set_unioni(results.paramids,
B
Bruce Momjian 已提交
649
							 ((SubqueryScan *) plan)->subplan->extParam);
650 651
			break;

652 653 654
		case T_FunctionScan:
			{
				RangeTblEntry *rte;
655

656 657 658 659 660 661 662 663 664 665
				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 已提交
666 667
								   SS_finalize_plan((Plan *) lfirst(lst),
													rtable));
668 669
			break;

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

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

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

689
		case T_Hash:
690
			finalize_primnode(((Hash *) plan)->hashkey,
691
							  &results);
692 693 694 695 696 697 698
			break;

		case T_Agg:
		case T_SeqScan:
		case T_Material:
		case T_Sort:
		case T_Unique:
699
		case T_SetOp:
700
		case T_Limit:
701 702
		case T_Group:
			break;
703

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

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

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

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

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

736 737
	plan->extParam = extParam;
	plan->locParam = locParam;
738
	plan->subPlan = results.subplans;
739

740
	return results.paramids;
741
}