subselect.c 21.0 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.62 2003/01/09 20:50:51 tgl Exp $
11 12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

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

30

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

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

/*--------------------
 * 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.
48 49 50 51
 *
 * 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.
52 53
 *--------------------
 */
54 55


56 57 58 59 60 61 62 63 64 65 66
typedef struct finalize_primnode_results
{
	List	   *paramids;		/* List of PARAM_EXEC paramids found */
} finalize_primnode_results;


static List *convert_sublink_opers(List *operlist, List *lefthand,
								   List *targetlist, List **setParams);
static Node *replace_correlation_vars_mutator(Node *node, void *context);
static Node *process_sublinks_mutator(Node *node, void *context);
static bool finalize_primnode(Node *node, finalize_primnode_results *results);
67 68


69 70 71
/*
 * Create a new entry in the PlannerParamVar list, and return its index.
 *
72 73 74 75
 * 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.
76
 */
77
static int
78
new_param(Var *var, Index varlevel)
79
{
80
	var->varlevelsup = varlevel;
81

82
	PlannerParamVar = lappend(PlannerParamVar, var);
83

84
	return length(PlannerParamVar) - 1;
85 86
}

87 88 89 90
/*
 * Generate a Param node to replace the given Var,
 * which is expected to have varlevelsup > 0 (ie, it is not local).
 */
91
static Param *
92
replace_var(Var *var)
93
{
94
	List	   *ppv;
95
	Param	   *retval;
96
	Index		varlevel;
97 98
	int			i;

99 100
	Assert(var->varlevelsup > 0 && var->varlevelsup < PlannerQueryLevel);
	varlevel = PlannerQueryLevel - var->varlevelsup;
101

102
	/*
103
	 * If there's already a PlannerParamVar entry for this same Var, just
B
Bruce Momjian 已提交
104 105 106 107 108 109
	 * 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
110
	 * execution in each part of the tree.
111 112 113
	 */
	i = 0;
	foreach(ppv, PlannerParamVar)
114
	{
115
		Var		   *pvar = lfirst(ppv);
116 117 118 119 120

		if (pvar->varno == var->varno &&
			pvar->varattno == var->varattno &&
			pvar->varlevelsup == varlevel &&
			pvar->vartype == var->vartype)
121
			break;
122
		i++;
123
	}
124

125
	if (!ppv)
126 127
	{
		/* Nope, so make a new one */
128
		i = new_param((Var *) copyObject(var), varlevel);
129
	}
130

131 132 133 134
	retval = makeNode(Param);
	retval->paramkind = PARAM_EXEC;
	retval->paramid = (AttrNumber) i;
	retval->paramtype = var->vartype;
135

136
	return retval;
137 138
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
/*
 * 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;
}

155
/*
156 157 158 159 160 161 162 163 164 165
 * Convert a bare SubLink (as created by the parser) into a SubPlan.
 *
 * We are given the raw SubLink and the already-processed lefthand argument
 * list (use this instead of the SubLink's own field).
 *
 * The result is whatever we need to substitute in place of the SubLink
 * node in the executable expression.  This will be either the SubPlan
 * node (if we have to do the subplan as a subplan), or a Param node
 * representing the result of an InitPlan, or possibly an AND or OR tree
 * containing InitPlan Param nodes.
166
 */
167
static Node *
168
make_subplan(SubLink *slink, List *lefthand)
169
{
170
	SubPlan	   *node = makeNode(SubPlan);
171
	Query	   *subquery = (Query *) (slink->subselect);
172
	double		tuple_fraction;
173 174 175
	Plan	   *plan;
	List	   *lst;
	Node	   *result;
176

177
	/*
B
Bruce Momjian 已提交
178 179 180 181
	 * 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...
182 183 184
	 */
	subquery = (Query *) copyObject(subquery);

185
	/*
186 187 188 189 190 191 192
	 * 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).
193
	 *
194 195 196
	 * NOTE: if you change these numbers, also change cost_qual_eval_walker()
	 * in path/costsize.c.
	 *
197 198 199 200 201 202 203 204
	 * 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.
205 206 207
	 */
	if (slink->subLinkType == EXISTS_SUBLINK)
		tuple_fraction = 1.0;	/* just like a LIMIT 1 */
208 209
	else if (slink->subLinkType == ALL_SUBLINK ||
			 slink->subLinkType == ANY_SUBLINK)
210
		tuple_fraction = 0.5;	/* 50% */
211 212
	else
		tuple_fraction = -1.0;	/* default behavior */
213

214
	/*
215
	 * Generate the plan for the subquery.
216
	 */
217
	node->plan = plan = subquery_planner(subquery, tuple_fraction);
218

B
Bruce Momjian 已提交
219
	node->plan_id = PlannerPlanId++;	/* Assign unique ID to this
220
										 * SubPlan */
221

222
	node->rtable = subquery->rtable;
223

224 225 226 227
	/*
	 * Fill in other fields of the SubPlan node.
	 */
	node->subLinkType = slink->subLinkType;
228
	node->useOr = slink->useOr;
229 230 231 232
	node->oper = NIL;
	node->setParam = NIL;
	node->parParam = NIL;
	node->args = NIL;
233

234
	/*
B
Bruce Momjian 已提交
235 236
	 * Make parParam list of params that current query level will pass to
	 * this child plan.
237
	 */
238
	foreach(lst, plan->extParam)
239
	{
240 241
		int			paramid = lfirsti(lst);
		Var		   *var = nth(paramid, PlannerParamVar);
242

243
		/* note varlevelsup is absolute level number */
244
		if (var->varlevelsup == PlannerQueryLevel)
245
			node->parParam = lappendi(node->parParam, paramid);
246
	}
247 248

	/*
249
	 * Un-correlated or undirect correlated plans of EXISTS, EXPR, or
250 251
	 * MULTIEXPR types can be used as initPlans.  For EXISTS or EXPR, we
	 * just produce a Param referring to the result of evaluating the
252 253 254
	 * 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.
255
	 */
256 257
	if (node->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK)
	{
258
		Param	   *prm;
259

260
		prm = generate_new_param(BOOLOID, -1);
261 262 263 264 265 266 267
		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);
268
		Param	   *prm;
269

270
		prm = generate_new_param(te->resdom->restype, te->resdom->restypmod);
271 272 273 274 275
		node->setParam = lappendi(node->setParam, prm->paramid);
		PlannerInitPlan = lappend(PlannerInitPlan, node);
		result = (Node *) prm;
	}
	else if (node->parParam == NIL && slink->subLinkType == MULTIEXPR_SUBLINK)
276
	{
277 278 279 280 281 282 283
		List   *oper;

		/* Convert the oper list, but don't put it into the SubPlan node */
		oper = convert_sublink_opers(slink->oper,
									 lefthand,
									 plan->targetlist,
									 &node->setParam);
284
		PlannerInitPlan = lappend(PlannerInitPlan, node);
285
		if (length(oper) > 1)
286
			result = (Node *) (node->useOr ? make_orclause(oper) :
287
							   make_andclause(oper));
288
		else
289
			result = (Node *) lfirst(oper);
290
	}
291
	else
292
	{
293
		List	   *args;
294

295
		/*
296 297 298 299 300 301 302 303 304 305
		 * 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.
306 307 308 309 310 311
		 *
		 * 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.
312 313 314 315 316 317 318 319
		 */
		if (node->parParam == NIL)
		{
			bool		use_material;

			switch (nodeTag(plan))
			{
				case T_SeqScan:
320
					if (plan->initPlan)
321 322 323 324 325 326 327 328 329 330 331
						use_material = true;
					else
					{
						Selectivity qualsel;

						qualsel = clauselist_selectivity(subquery,
														 plan->qual,
														 0);
						/* Is 10% selectivity a good threshold?? */
						use_material = qualsel < 0.10;
					}
332 333
					break;
				case T_Material:
334
				case T_FunctionScan:
335
				case T_Sort:
336 337 338

					/*
					 * Don't add another Material node if there's one
339 340
					 * already, nor if the top node is any other type that
					 * materializes its output anyway.
341 342 343 344 345 346 347 348 349
					 */
					use_material = false;
					break;
				default:
					use_material = true;
					break;
			}
			if (use_material)
			{
B
Bruce Momjian 已提交
350
				Plan	   *matplan;
351
				Path		matpath; /* dummy for result of cost_material */
352 353

				matplan = (Plan *) make_material(plan->targetlist, plan);
354 355 356 357 358 359 360 361
				/* 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 */
362 363 364
				matplan->extParam = listCopy(plan->extParam);
				matplan->locParam = listCopy(plan->locParam);
				node->plan = plan = matplan;
365 366 367
			}
		}

368 369 370 371 372
		/* Convert the SubLink's oper list into executable form */
		node->oper = convert_sublink_opers(slink->oper,
										   lefthand,
										   plan->targetlist,
										   NULL);
373

374
		/*
375
		 * Make node->args from parParam.
376
		 */
377
		args = NIL;
378
		foreach(lst, node->parParam)
379
		{
380 381 382
			Var		   *var = nth(lfirsti(lst), PlannerParamVar);

			var = (Var *) copyObject(var);
383 384 385 386 387

			/*
			 * Must fix absolute-level varlevelsup from the
			 * PlannerParamVar entry.  But since var is at current subplan
			 * level, this is easy:
388
			 */
389
			var->varlevelsup = 0;
390
			args = lappend(args, var);
391
		}
392
		node->args = args;
393

394
		result = (Node *) node;
395 396 397 398 399 400 401 402 403
	}

	return result;
}

/*
 * convert_sublink_opers: convert a SubLink's oper list from the
 * parser/rewriter format into the executor's format.
 *
404 405 406 407
 * The oper list is initially a list of OpExpr nodes with NIL args.  We
 * convert it to 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.
408 409 410 411
 *
 * If setParams is not NULL, the paramids of the Params created are added
 * to the *setParams list.
 */
412 413 414
static List *
convert_sublink_opers(List *operlist, List *lefthand,
					  List *targetlist, List **setParams)
415 416
{
	List	   *newoper = NIL;
417
	List	   *leftlist = lefthand;
418 419
	List	   *lst;

420
	foreach(lst, operlist)
421
	{
422
		OpExpr	   *oper = (OpExpr *) lfirst(lst);
423
		Node	   *leftop = lfirst(leftlist);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
		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 */
440
		Assert(IsA(oper, OpExpr));
441 442 443 444 445 446 447
		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);

448
		/*
449 450 451 452
		 * Make the expression node.
		 *
		 * Note: we use make_operand in case runtime type conversion
		 * function calls must be inserted for this operator!
453
		 */
454
		left = make_operand(leftop, exprType(leftop), opform->oprleft);
455 456
		right = make_operand((Node *) prm, prm->paramtype, opform->oprright);
		newoper = lappend(newoper,
457 458 459 460 461
						  make_opclause(oper->opno,
										oper->opresulttype,
										oper->opretset,
										(Expr *) left,
										(Expr *) right));
462

463 464 465 466
		ReleaseSysCache(tup);

		leftlist = lnext(leftlist);
		targetlist = lnext(targetlist);
467
	}
468

469
	return newoper;
470 471
}

472 473
/*
 * Replace correlation vars (uplevel vars) with Params.
474
 */
475
Node *
476
SS_replace_correlation_vars(Node *expr)
477
{
478 479 480
	/* No setup needed for tree walk, so away we go */
	return replace_correlation_vars_mutator(expr, NULL);
}
481

482 483 484 485 486 487
static Node *
replace_correlation_vars_mutator(Node *node, void *context)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
488
	{
489 490
		if (((Var *) node)->varlevelsup > 0)
			return (Node *) replace_var((Var *) node);
491
	}
492 493 494
	return expression_tree_mutator(node,
								   replace_correlation_vars_mutator,
								   context);
495 496
}

497 498
/*
 * Expand SubLinks to SubPlans in the given expression.
499
 */
500 501
Node *
SS_process_sublinks(Node *expr)
502
{
503
	/* No setup needed for tree walk, so away we go */
504
	return process_sublinks_mutator(expr, NULL);
505 506 507 508 509 510
}

static Node *
process_sublinks_mutator(Node *node, void *context)
{
	if (node == NULL)
511
		return NULL;
512
	if (IsA(node, SubLink))
513
	{
514
		SubLink    *sublink = (SubLink *) node;
515
		List	   *lefthand;
516

517
		/*
518
		 * First, recursively process the lefthand-side expressions, if any.
519
		 */
520
		lefthand = (List *)
521
			process_sublinks_mutator((Node *) sublink->lefthand, context);
522 523 524 525
		/*
		 * Now build the SubPlan node and make the expr to return.
		 */
		return make_subplan(sublink, lefthand);
526
	}
527

528
	/*
529
	 * Note that we will never see a SubPlan expression in the input
530 531 532
	 * (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.
533
	 */
534
	Assert(!is_subplan(node));
535

536 537 538
	return expression_tree_mutator(node,
								   process_sublinks_mutator,
								   context);
539 540
}

541 542 543 544 545 546
/*
 * SS_finalize_plan - do final sublink processing for a completed Plan.
 *
 * This recursively computes and sets the extParam and locParam lists
 * for every Plan node in the given tree.
 */
547
List *
548
SS_finalize_plan(Plan *plan, List *rtable)
549
{
550 551 552
	List	   *extParam = NIL;
	List	   *locParam = NIL;
	finalize_primnode_results results;
553 554 555
	List	   *lst;

	if (plan == NULL)
556
		return NIL;
557

558
	results.paramids = NIL;		/* initialize list to NIL */
559

560 561
	/*
	 * When we call finalize_primnode, results.paramids lists are
562 563
	 * automatically merged together.  But when recursing to self, we have
	 * to do it the hard way.  We want the paramids list to include params
564
	 * in subplans as well as at this level.
565 566
	 */

567
	/* Find params in targetlist and qual */
568
	finalize_primnode((Node *) plan->targetlist, &results);
569
	finalize_primnode((Node *) plan->qual, &results);
570

571
	/* Check additional node-type-specific fields */
572 573 574
	switch (nodeTag(plan))
	{
		case T_Result:
575 576
			finalize_primnode(((Result *) plan)->resconstantqual,
							  &results);
577 578
			break;

579 580 581 582 583 584
		case T_IndexScan:
			finalize_primnode((Node *) ((IndexScan *) plan)->indxqual,
							  &results);

			/*
			 * we need not look at indxqualorig, since it will have the
585
			 * same param references as indxqual.
586 587 588 589 590 591
			 */
			break;

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

594
		case T_SubqueryScan:
B
Bruce Momjian 已提交
595

596
			/*
B
Bruce Momjian 已提交
597 598 599 600 601
			 * 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.
602
			 */
603
			results.paramids = set_unioni(results.paramids,
B
Bruce Momjian 已提交
604
							 ((SubqueryScan *) plan)->subplan->extParam);
605 606
			break;

607 608 609
		case T_FunctionScan:
			{
				RangeTblEntry *rte;
610

611 612 613 614 615 616 617 618 619 620
				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 已提交
621 622
								   SS_finalize_plan((Plan *) lfirst(lst),
													rtable));
623 624
			break;

625 626 627 628 629
		case T_NestLoop:
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
			break;

630
		case T_MergeJoin:
631 632
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
633 634
			finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
							  &results);
635 636 637
			break;

		case T_HashJoin:
638 639
			finalize_primnode((Node *) ((Join *) plan)->joinqual,
							  &results);
640 641
			finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
							  &results);
642
			break;
643

644
		case T_Hash:
645
			finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
646
							  &results);
647 648 649 650 651 652 653
			break;

		case T_Agg:
		case T_SeqScan:
		case T_Material:
		case T_Sort:
		case T_Unique:
654
		case T_SetOp:
655
		case T_Limit:
656 657
		case T_Group:
			break;
658

659
		default:
660 661
			elog(ERROR, "SS_finalize_plan: node %d unsupported",
				 nodeTag(plan));
662
	}
663

664
	/* Process left and right child plans, if any */
665
	results.paramids = set_unioni(results.paramids,
666 667
								  SS_finalize_plan(plan->lefttree,
												   rtable));
668
	results.paramids = set_unioni(results.paramids,
669 670
								  SS_finalize_plan(plan->righttree,
												   rtable));
671

672
	/* Now we have all the paramids */
673

674
	foreach(lst, results.paramids)
675
	{
676 677
		int			paramid = lfirsti(lst);
		Var		   *var = nth(paramid, PlannerParamVar);
678

679
		/* note varlevelsup is absolute level number */
680
		if (var->varlevelsup < PlannerQueryLevel)
681
			extParam = lappendi(extParam, paramid);
682
		else if (var->varlevelsup > PlannerQueryLevel)
683
			elog(ERROR, "SS_finalize_plan: plan shouldn't reference subplan's variable");
684 685
		else
		{
686
			Assert(var->varno == 0 && var->varattno == 0);
687
			locParam = lappendi(locParam, paramid);
688 689
		}
	}
690

691 692 693
	plan->extParam = extParam;
	plan->locParam = locParam;

694
	return results.paramids;
695
}
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738

/*
 * finalize_primnode: build lists of params appearing
 * in the given expression tree.  NOTE: items are added to list passed in,
 * so caller must initialize list to NIL before first call!
 */
static bool
finalize_primnode(Node *node, finalize_primnode_results *results)
{
	if (node == NULL)
		return false;
	if (IsA(node, Param))
	{
		if (((Param *) node)->paramkind == PARAM_EXEC)
		{
			int			paramid = (int) ((Param *) node)->paramid;

			if (!intMember(paramid, results->paramids))
				results->paramids = lconsi(paramid, results->paramids);
		}
		return false;			/* no more to do here */
	}
	if (is_subplan(node))
	{
		SubPlan	   *subplan = (SubPlan *) node;
		List	   *lst;

		/* Check extParam list for params to add to paramids */
		foreach(lst, subplan->plan->extParam)
		{
			int			paramid = lfirsti(lst);
			Var		   *var = nth(paramid, PlannerParamVar);

			/* note varlevelsup is absolute level number */
			if (var->varlevelsup < PlannerQueryLevel &&
				!intMember(paramid, results->paramids))
				results->paramids = lconsi(paramid, results->paramids);
		}
		/* fall through to recurse into subplan args */
	}
	return expression_tree_walker(node, finalize_primnode,
								  (void *) results);
}