setrefs.c 57.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * setrefs.c
4
 *	  Post-processing of a completed plan tree: fix references to subplan
5
 *	  vars, compute regproc values for operators, etc
6
 *
7
 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9 10 11
 *
 *
 * IDENTIFICATION
12
 *	  src/backend/optimizer/plan/setrefs.c
13 14 15 16 17
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

18
#include "access/transam.h"
19
#include "catalog/pg_type.h"
20
#include "nodes/makefuncs.h"
21
#include "nodes/nodeFuncs.h"
22
#include "optimizer/pathnode.h"
23 24
#include "optimizer/planmain.h"
#include "optimizer/tlist.h"
25
#include "tcop/utility.h"
26
#include "utils/lsyscache.h"
27
#include "utils/syscache.h"
28

29

30 31 32 33 34 35 36 37 38 39 40
typedef struct
{
	Index		varno;			/* RT index of Var */
	AttrNumber	varattno;		/* attr number of Var */
	AttrNumber	resno;			/* TLE position of Var */
} tlist_vinfo;

typedef struct
{
	List	   *tlist;			/* underlying target list */
	int			num_vars;		/* number of plain Var tlist entries */
41 42
	bool		has_ph_vars;	/* are there PlaceHolderVar entries? */
	bool		has_non_vars;	/* are there other entries? */
43
	/* array of num_vars entries: */
B
Bruce Momjian 已提交
44
	tlist_vinfo vars[1];		/* VARIABLE LENGTH ARRAY */
45 46
} indexed_tlist;				/* VARIABLE LENGTH STRUCT */

47 48
typedef struct
{
49
	PlannerInfo *root;
50
	int			rtoffset;
51
} fix_scan_expr_context;
52

53 54
typedef struct
{
55
	PlannerInfo *root;
56 57
	indexed_tlist *outer_itlist;
	indexed_tlist *inner_itlist;
58
	Index		acceptable_rel;
59
	int			rtoffset;
60
} fix_join_expr_context;
61

62 63
typedef struct
{
64
	PlannerInfo *root;
65
	indexed_tlist *subplan_itlist;
66
	Index		newvarno;
67
	int			rtoffset;
68
} fix_upper_expr_context;
69

70 71 72 73 74 75 76 77 78 79 80
/*
 * Check if a Const node is a regclass value.  We accept plain OID too,
 * since a regclass Const will get folded to that type if it's an argument
 * to oideq or similar operators.  (This might result in some extraneous
 * values in a plan's list of relation dependencies, but the worst result
 * would be occasional useless replans.)
 */
#define ISREGCLASSCONST(con) \
	(((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
	 !(con)->constisnull)

81 82
#define fix_scan_list(root, lst, rtoffset) \
	((List *) fix_scan_expr(root, (Node *) (lst), rtoffset))
83

84
static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
85 86 87
static Plan *set_indexonlyscan_references(PlannerInfo *root,
							 IndexOnlyScan *plan,
							 int rtoffset);
88
static Plan *set_subqueryscan_references(PlannerInfo *root,
B
Bruce Momjian 已提交
89 90
							SubqueryScan *plan,
							int rtoffset);
91
static bool trivial_subqueryscan(SubqueryScan *plan);
92
static Node *fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset);
93
static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
94
static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
95 96
static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
97
static void set_dummy_tlist_references(Plan *plan, int rtoffset);
98 99
static indexed_tlist *build_tlist_index(List *tlist);
static Var *search_indexed_tlist_for_var(Var *var,
B
Bruce Momjian 已提交
100
							 indexed_tlist *itlist,
101 102
							 Index newvarno,
							 int rtoffset);
103
static Var *search_indexed_tlist_for_non_var(Node *node,
B
Bruce Momjian 已提交
104 105
								 indexed_tlist *itlist,
								 Index newvarno);
106 107 108 109
static Var *search_indexed_tlist_for_sortgroupref(Node *node,
									  Index sortgroupref,
									  indexed_tlist *itlist,
									  Index newvarno);
110
static List *fix_join_expr(PlannerInfo *root,
B
Bruce Momjian 已提交
111 112 113 114
			  List *clauses,
			  indexed_tlist *outer_itlist,
			  indexed_tlist *inner_itlist,
			  Index acceptable_rel, int rtoffset);
115
static Node *fix_join_expr_mutator(Node *node,
116
					  fix_join_expr_context *context);
117
static Node *fix_upper_expr(PlannerInfo *root,
B
Bruce Momjian 已提交
118 119
			   Node *node,
			   indexed_tlist *subplan_itlist,
120
			   Index newvarno,
B
Bruce Momjian 已提交
121
			   int rtoffset);
122
static Node *fix_upper_expr_mutator(Node *node,
123
					   fix_upper_expr_context *context);
124 125 126 127 128
static List *set_returning_clause_references(PlannerInfo *root,
								List *rlist,
								Plan *topplan,
								Index resultRelation,
								int rtoffset);
129
static bool fix_opfuncids_walker(Node *node, void *context);
130
static bool extract_query_dependencies_walker(Node *node,
131
								  PlannerInfo *context);
132

133 134

/*****************************************************************************
135 136 137
 *
 *		SUBPLAN REFERENCES
 *
138 139
 *****************************************************************************/

140
/*
141
 * set_plan_references
142
 *
B
Bruce Momjian 已提交
143
 * This is the final processing pass of the planner/optimizer.	The plan
144
 * tree is complete; we just have to adjust some representational details
145 146 147 148 149 150 151 152 153 154 155 156
 * for the convenience of the executor:
 *
 * 1. We flatten the various subquery rangetables into a single list, and
 * zero out RangeTblEntry fields that are not useful to the executor.
 *
 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
 *
 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
 * subplans.
 *
 * 4. We compute regproc OIDs for operators (ie, we look up the function
 * that implements each op).
157
 *
158
 * 5. We create lists of specific objects that the plan depends on.
159
 * This will be used by plancache.c to drive invalidation of cached plans.
160 161 162 163
 * Relation dependencies are represented by OIDs, and everything else by
 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
 * Currently, relations and user-defined functions are the only types of
 * objects that are explicitly tracked this way.
164
 *
165 166 167 168
 * We also perform one final optimization step, which is to delete
 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
 * no qual and a no-op targetlist).  The reason for doing this last is that
 * it can't readily be done before set_plan_references, because it would
169 170
 * break set_upper_references: the Vars in the subquery's top tlist
 * wouldn't match up with the Vars in the outer plan tree.  The SubqueryScan
171
 * serves a necessary function as a buffer between outer query and subquery
172
 * variable numbering ... but after we've flattened the rangetable this is
173
 * no longer a problem, since then there's only one rtindex namespace.
174 175 176 177 178 179
 *
 * set_plan_references recursively traverses the whole plan tree.
 *
 * The return value is normally the same Plan node passed in, but can be
 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
 *
180 181 182 183 184
 * The flattened rangetable entries are appended to root->glob->finalrtable.
 * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
 * RT indexes of ModifyTable result relations to root->glob->resultRelations.
 * Plan dependencies are appended to root->glob->relationOids (for relations)
 * and root->glob->invalItems (for everything else).
185 186
 *
 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
B
Bruce Momjian 已提交
187
 * to process targetlist and qual expressions.	We can assume that the Plan
188 189
 * nodes were just built by the planner and are not multiply referenced, but
 * it's not so safe to assume that for expression tree nodes.
190
 */
191
Plan *
192
set_plan_references(PlannerInfo *root, Plan *plan)
193
{
194
	PlannerGlobal *glob = root->glob;
195 196 197 198
	int			rtoffset = list_length(glob->finalrtable);
	ListCell   *lc;

	/*
B
Bruce Momjian 已提交
199 200 201
	 * In the flat rangetable, we zero out substructure pointers that are not
	 * needed by the executor; this reduces the storage space and copying cost
	 * for cached plans.  We keep only the alias and eref Alias fields, which
202
	 * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
203 204
	 * which are needed for executor-startup permissions checking and for
	 * trigger event checking.
205
	 */
206
	foreach(lc, root->parse->rtable)
207
	{
B
Bruce Momjian 已提交
208 209
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
		RangeTblEntry *newrte;
210 211 212 213 214

		/* flat copy to duplicate all the scalar fields */
		newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
		memcpy(newrte, rte, sizeof(RangeTblEntry));

215
		/* zap unneeded sub-structure */
216
		newrte->subquery = NULL;
217
		newrte->joinaliasvars = NIL;
218 219 220
		newrte->funcexpr = NULL;
		newrte->funccoltypes = NIL;
		newrte->funccoltypmods = NIL;
P
Peter Eisentraut 已提交
221
		newrte->funccolcollations = NIL;
222
		newrte->values_lists = NIL;
223
		newrte->values_collations = NIL;
224 225
		newrte->ctecoltypes = NIL;
		newrte->ctecoltypmods = NIL;
P
Peter Eisentraut 已提交
226
		newrte->ctecolcollations = NIL;
227 228

		glob->finalrtable = lappend(glob->finalrtable, newrte);
229 230 231 232

		/*
		 * If it's a plain relation RTE, add the table to relationOids.
		 *
B
Bruce Momjian 已提交
233 234 235 236 237
		 * We do this even though the RTE might be unreferenced in the plan
		 * tree; this would correspond to cases such as views that were
		 * expanded, child tables that were eliminated by constraint
		 * exclusion, etc.	Schema invalidation on such a rel must still force
		 * rebuilding of the plan.
238 239 240 241 242 243 244
		 *
		 * Note we don't bother to avoid duplicate list entries.  We could,
		 * but it would probably cost more cycles than it would save.
		 */
		if (newrte->rtekind == RTE_RELATION)
			glob->relationOids = lappend_oid(glob->relationOids,
											 newrte->relid);
245 246
	}

247 248 249 250 251 252 253 254 255 256
	/*
	 * Check for RT index overflow; it's very unlikely, but if it did happen,
	 * the executor would get confused by varnos that match the special varno
	 * values.
	 */
	if (IS_SPECIAL_VARNO(list_length(glob->finalrtable)))
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("too many range table entries")));

257
	/*
258
	 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
259
	 */
260
	foreach(lc, root->rowMarks)
261
	{
262 263
		PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
		PlanRowMark *newrc;
264

265 266 267 268 269
		Assert(IsA(rc, PlanRowMark));

		/* flat copy is enough since all fields are scalars */
		newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
		memcpy(newrc, rc, sizeof(PlanRowMark));
270

271
		/* adjust indexes ... but *not* the rowmarkId */
272 273 274 275 276 277
		newrc->rti += rtoffset;
		newrc->prti += rtoffset;

		glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
	}

278
	/* Now fix the Plan tree */
279
	return set_plan_refs(root, plan, rtoffset);
280 281 282 283 284 285
}

/*
 * set_plan_refs: recurse through the Plan nodes of a single subquery level
 */
static Plan *
286
set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
287
{
B
Bruce Momjian 已提交
288
	ListCell   *l;
289

290
	if (plan == NULL)
291
		return NULL;
292

293 294 295 296 297 298
	/*
	 * Plan-type-specific fixes
	 */
	switch (nodeTag(plan))
	{
		case T_SeqScan:
299
			{
B
Bruce Momjian 已提交
300
				SeqScan    *splan = (SeqScan *) plan;
301 302 303

				splan->scanrelid += rtoffset;
				splan->plan.targetlist =
304
					fix_scan_list(root, splan->plan.targetlist, rtoffset);
305
				splan->plan.qual =
306
					fix_scan_list(root, splan->plan.qual, rtoffset);
307
			}
308 309
			break;
		case T_IndexScan:
310
			{
B
Bruce Momjian 已提交
311
				IndexScan  *splan = (IndexScan *) plan;
312 313 314

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
315
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
316
				splan->scan.plan.qual =
317
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
318
				splan->indexqual =
319
					fix_scan_list(root, splan->indexqual, rtoffset);
320
				splan->indexqualorig =
321
					fix_scan_list(root, splan->indexqualorig, rtoffset);
T
Tom Lane 已提交
322
				splan->indexorderby =
323
					fix_scan_list(root, splan->indexorderby, rtoffset);
T
Tom Lane 已提交
324
				splan->indexorderbyorig =
325
					fix_scan_list(root, splan->indexorderbyorig, rtoffset);
326
			}
327
			break;
328 329 330 331 332 333 334
		case T_IndexOnlyScan:
			{
				IndexOnlyScan  *splan = (IndexOnlyScan *) plan;

				return set_indexonlyscan_references(root, splan, rtoffset);
			}
			break;
335
		case T_BitmapIndexScan:
336 337 338 339 340 341 342 343
			{
				BitmapIndexScan *splan = (BitmapIndexScan *) plan;

				splan->scan.scanrelid += rtoffset;
				/* no need to fix targetlist and qual */
				Assert(splan->scan.plan.targetlist == NIL);
				Assert(splan->scan.plan.qual == NIL);
				splan->indexqual =
344
					fix_scan_list(root, splan->indexqual, rtoffset);
345
				splan->indexqualorig =
346
					fix_scan_list(root, splan->indexqualorig, rtoffset);
347
			}
348 349
			break;
		case T_BitmapHeapScan:
350 351 352 353 354
			{
				BitmapHeapScan *splan = (BitmapHeapScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
355
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
356
				splan->scan.plan.qual =
357
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
358
				splan->bitmapqualorig =
359
					fix_scan_list(root, splan->bitmapqualorig, rtoffset);
360
			}
361
			break;
362
		case T_TidScan:
363
			{
B
Bruce Momjian 已提交
364
				TidScan    *splan = (TidScan *) plan;
365 366 367

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
368
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
369
				splan->scan.plan.qual =
370
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
371
				splan->tidquals =
372
					fix_scan_list(root, splan->tidquals, rtoffset);
373
			}
374
			break;
375
		case T_SubqueryScan:
376
			/* Needs special treatment, see comments below */
377
			return set_subqueryscan_references(root,
378 379
											   (SubqueryScan *) plan,
											   rtoffset);
380
		case T_FunctionScan:
381 382 383 384 385
			{
				FunctionScan *splan = (FunctionScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
386
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
387
				splan->scan.plan.qual =
388
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
389
				splan->funcexpr =
390
					fix_scan_expr(root, splan->funcexpr, rtoffset);
391
			}
392
			break;
393
		case T_ValuesScan:
394 395 396 397 398
			{
				ValuesScan *splan = (ValuesScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
399
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
400
				splan->scan.plan.qual =
401
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
402
				splan->values_lists =
403
					fix_scan_list(root, splan->values_lists, rtoffset);
404
			}
405
			break;
406 407
		case T_CteScan:
			{
408
				CteScan    *splan = (CteScan *) plan;
409 410 411

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
412
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
413
				splan->scan.plan.qual =
414
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
415 416 417 418 419
			}
			break;
		case T_WorkTableScan:
			{
				WorkTableScan *splan = (WorkTableScan *) plan;
420

421 422
				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
423
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
424
				splan->scan.plan.qual =
425
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
426 427
			}
			break;
428 429 430 431 432 433
		case T_ForeignScan:
			{
				ForeignScan *splan = (ForeignScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
434
					fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
435
				splan->scan.plan.qual =
436
					fix_scan_list(root, splan->scan.plan.qual, rtoffset);
T
Tom Lane 已提交
437 438
				splan->fdw_exprs =
					fix_scan_list(root, splan->fdw_exprs, rtoffset);
439 440 441
			}
			break;

442 443 444
		case T_NestLoop:
		case T_MergeJoin:
		case T_HashJoin:
445
			set_join_references(root, (Join *) plan, rtoffset);
446
			break;
447

448
		case T_Hash:
449 450 451
		case T_Material:
		case T_Sort:
		case T_Unique:
452
		case T_SetOp:
453 454 455

			/*
			 * These plan types don't actually bother to evaluate their
456
			 * targetlists, because they just return their unmodified input
B
Bruce Momjian 已提交
457
			 * tuples.	Even though the targetlist won't be used by the
458 459 460
			 * executor, we fix it up for possible use by EXPLAIN (not to
			 * mention ease of debugging --- wrong varnos are very confusing).
			 */
461
			set_dummy_tlist_references(plan, rtoffset);
B
Bruce Momjian 已提交
462

463
			/*
B
Bruce Momjian 已提交
464 465
			 * Since these plan types don't check quals either, we should not
			 * find any qual expression attached to them.
466
			 */
467
			Assert(plan->qual == NIL);
468
			break;
469 470 471 472 473 474
		case T_LockRows:
			{
				LockRows   *splan = (LockRows *) plan;

				/*
				 * Like the plan types above, LockRows doesn't evaluate its
B
Bruce Momjian 已提交
475 476
				 * tlist or quals.	But we have to fix up the RT indexes in
				 * its rowmarks.
477 478 479 480 481 482
				 */
				set_dummy_tlist_references(plan, rtoffset);
				Assert(splan->plan.qual == NIL);

				foreach(l, splan->rowMarks)
				{
483
					PlanRowMark *rc = (PlanRowMark *) lfirst(l);
484 485 486 487 488 489

					rc->rti += rtoffset;
					rc->prti += rtoffset;
				}
			}
			break;
490
		case T_Limit:
491
			{
B
Bruce Momjian 已提交
492
				Limit	   *splan = (Limit *) plan;
493 494 495 496

				/*
				 * Like the plan types above, Limit doesn't evaluate its tlist
				 * or quals.  It does have live expressions for limit/offset,
B
Bruce Momjian 已提交
497 498
				 * however; and those cannot contain subplan variable refs, so
				 * fix_scan_expr works for them.
499
				 */
500
				set_dummy_tlist_references(plan, rtoffset);
501
				Assert(splan->plan.qual == NIL);
502

503
				splan->limitOffset =
504
					fix_scan_expr(root, splan->limitOffset, rtoffset);
505
				splan->limitCount =
506
					fix_scan_expr(root, splan->limitCount, rtoffset);
507
			}
508
			break;
509 510
		case T_Agg:
		case T_Group:
511
			set_upper_references(root, plan, rtoffset);
512
			break;
513 514
		case T_WindowAgg:
			{
B
Bruce Momjian 已提交
515
				WindowAgg  *wplan = (WindowAgg *) plan;
516

517
				set_upper_references(root, plan, rtoffset);
518 519 520 521 522 523 524

				/*
				 * Like Limit node limit/offset expressions, WindowAgg has
				 * frame offset expressions, which cannot contain subplan
				 * variable refs, so fix_scan_expr works for them.
				 */
				wplan->startOffset =
525
					fix_scan_expr(root, wplan->startOffset, rtoffset);
526
				wplan->endOffset =
527
					fix_scan_expr(root, wplan->endOffset, rtoffset);
528 529
			}
			break;
530
		case T_Result:
531
			{
B
Bruce Momjian 已提交
532
				Result	   *splan = (Result *) plan;
533 534 535 536 537 538

				/*
				 * Result may or may not have a subplan; if not, it's more
				 * like a scan node than an upper node.
				 */
				if (splan->plan.lefttree != NULL)
539
					set_upper_references(root, plan, rtoffset);
540 541 542
				else
				{
					splan->plan.targetlist =
543
						fix_scan_list(root, splan->plan.targetlist, rtoffset);
544
					splan->plan.qual =
545
						fix_scan_list(root, splan->plan.qual, rtoffset);
546 547 548
				}
				/* resconstantqual can't contain any subplan variable refs */
				splan->resconstantqual =
549
					fix_scan_expr(root, splan->resconstantqual, rtoffset);
550
			}
551
			break;
552 553 554 555
		case T_ModifyTable:
			{
				ModifyTable *splan = (ModifyTable *) plan;

556
				Assert(splan->plan.targetlist == NIL);
557 558
				Assert(splan->plan.qual == NIL);

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
				if (splan->returningLists)
				{
					List	   *newRL = NIL;
					ListCell   *lcrl,
							   *lcrr,
							   *lcp;

					/*
					 * Pass each per-subplan returningList through
					 * set_returning_clause_references().
					 */
					Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
					Assert(list_length(splan->returningLists) == list_length(splan->plans));
					forthree(lcrl, splan->returningLists,
							 lcrr, splan->resultRelations,
							 lcp, splan->plans)
					{
						List   *rlist = (List *) lfirst(lcrl);
						Index	resultrel = lfirst_int(lcrr);
						Plan   *subplan = (Plan *) lfirst(lcp);

						rlist = set_returning_clause_references(root,
																rlist,
																subplan,
																resultrel,
																rtoffset);
						newRL = lappend(newRL, rlist);
					}
					splan->returningLists = newRL;

					/*
					 * Set up the visible plan targetlist as being the same as
					 * the first RETURNING list. This is for the use of
					 * EXPLAIN; the executor won't pay any attention to the
					 * targetlist.  We postpone this step until here so that
					 * we don't have to do set_returning_clause_references()
					 * twice on identical targetlists.
					 */
					splan->plan.targetlist = copyObject(linitial(newRL));
				}

600 601 602 603
				foreach(l, splan->resultRelations)
				{
					lfirst_int(l) += rtoffset;
				}
604 605 606 607 608 609 610
				foreach(l, splan->rowMarks)
				{
					PlanRowMark *rc = (PlanRowMark *) lfirst(l);

					rc->rti += rtoffset;
					rc->prti += rtoffset;
				}
611 612
				foreach(l, splan->plans)
				{
613
					lfirst(l) = set_plan_refs(root,
614 615 616
											  (Plan *) lfirst(l),
											  rtoffset);
				}
617 618 619 620 621 622 623

				/*
				 * Append this ModifyTable node's final result relation RT
				 * index(es) to the global list for the plan, and set its
				 * resultRelIndex to reflect their starting position in the
				 * global list.
				 */
624 625 626
				splan->resultRelIndex = list_length(root->glob->resultRelations);
				root->glob->resultRelations =
					list_concat(root->glob->resultRelations,
627
								list_copy(splan->resultRelations));
628 629
			}
			break;
630
		case T_Append:
631
			{
B
Bruce Momjian 已提交
632
				Append	   *splan = (Append *) plan;
633 634 635 636 637

				/*
				 * Append, like Sort et al, doesn't actually evaluate its
				 * targetlist or check quals.
				 */
638
				set_dummy_tlist_references(plan, rtoffset);
639 640 641
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->appendplans)
				{
642
					lfirst(l) = set_plan_refs(root,
643 644 645 646
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
647
			break;
648 649 650 651 652 653 654 655 656 657 658 659
		case T_MergeAppend:
			{
				MergeAppend *splan = (MergeAppend *) plan;

				/*
				 * MergeAppend, like Sort et al, doesn't actually evaluate its
				 * targetlist or check quals.
				 */
				set_dummy_tlist_references(plan, rtoffset);
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->mergeplans)
				{
660
					lfirst(l) = set_plan_refs(root,
661 662 663 664 665
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
			break;
666 667 668 669 670
		case T_RecursiveUnion:
			/* This doesn't evaluate targetlist or check quals either */
			set_dummy_tlist_references(plan, rtoffset);
			Assert(plan->qual == NIL);
			break;
671
		case T_BitmapAnd:
672
			{
B
Bruce Momjian 已提交
673
				BitmapAnd  *splan = (BitmapAnd *) plan;
674 675 676 677 678 679

				/* BitmapAnd works like Append, but has no tlist */
				Assert(splan->plan.targetlist == NIL);
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->bitmapplans)
				{
680
					lfirst(l) = set_plan_refs(root,
681 682 683 684
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
685 686
			break;
		case T_BitmapOr:
687
			{
B
Bruce Momjian 已提交
688
				BitmapOr   *splan = (BitmapOr *) plan;
689 690 691 692 693 694

				/* BitmapOr works like Append, but has no tlist */
				Assert(splan->plan.targetlist == NIL);
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->bitmapplans)
				{
695
					lfirst(l) = set_plan_refs(root,
696 697 698 699
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
700
			break;
701
		default:
702 703
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(plan));
704 705
			break;
	}
706

707
	/*
708
	 * Now recurse into child plans, if any
709
	 *
710
	 * NOTE: it is essential that we recurse into child plans AFTER we set
711 712
	 * subplan references in this plan's tlist and quals.  If we did the
	 * reference-adjustments bottom-up, then we would fail to match this
B
Bruce Momjian 已提交
713
	 * plan's var nodes against the already-modified nodes of the children.
714
	 */
715 716
	plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
	plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
717 718 719 720

	return plan;
}

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
/*
 * set_indexonlyscan_references
 *		Do set_plan_references processing on an IndexOnlyScan
 *
 * This is unlike the handling of a plain IndexScan because we have to
 * convert Vars referencing the heap into Vars referencing the index.
 * We can use the fix_upper_expr machinery for that, by working from a
 * targetlist describing the index columns.
 */
static Plan *
set_indexonlyscan_references(PlannerInfo *root,
							 IndexOnlyScan *plan,
							 int rtoffset)
{
	indexed_tlist *index_itlist;

	index_itlist = build_tlist_index(plan->indextlist);

	plan->scan.scanrelid += rtoffset;
	plan->scan.plan.targetlist = (List *)
		fix_upper_expr(root,
					   (Node *) plan->scan.plan.targetlist,
					   index_itlist,
					   INDEX_VAR,
					   rtoffset);
	plan->scan.plan.qual = (List *)
		fix_upper_expr(root,
					   (Node *) plan->scan.plan.qual,
					   index_itlist,
					   INDEX_VAR,
					   rtoffset);
	/* indexqual is already transformed to reference index columns */
	plan->indexqual = fix_scan_list(root, plan->indexqual, rtoffset);
	/* indexorderby is already transformed to reference index columns */
	plan->indexorderby = fix_scan_list(root, plan->indexorderby, rtoffset);
	/* indextlist must NOT be transformed to reference index columns */
	plan->indextlist = fix_scan_list(root, plan->indextlist, rtoffset);

	pfree(index_itlist);

	return (Plan *) plan;
}

764 765 766 767 768 769 770 771
/*
 * set_subqueryscan_references
 *		Do set_plan_references processing on a SubqueryScan
 *
 * We try to strip out the SubqueryScan entirely; if we can't, we have
 * to do the normal processing on it.
 */
static Plan *
772
set_subqueryscan_references(PlannerInfo *root,
773 774
							SubqueryScan *plan,
							int rtoffset)
775
{
776
	RelOptInfo *rel;
777 778
	Plan	   *result;

779 780 781
	/* Need to look up the subquery's RelOptInfo, since we need its subroot */
	rel = find_base_rel(root, plan->scan.scanrelid);
	Assert(rel->subplan == plan->subplan);
782

783 784
	/* Recursively process the subplan */
	plan->subplan = set_plan_references(rel->subroot, plan->subplan);
785 786 787 788

	if (trivial_subqueryscan(plan))
	{
		/*
789
		 * We can omit the SubqueryScan node and just pull up the subplan.
790
		 */
791 792
		ListCell   *lp,
				   *lc;
793

794
		result = plan->subplan;
795

796
		/* We have to be sure we don't lose any initplans */
797 798
		result->initPlan = list_concat(plan->scan.plan.initPlan,
									   result->initPlan);
799 800

		/*
801
		 * We also have to transfer the SubqueryScan's result-column names
802
		 * into the subplan, else columns sent to client will be improperly
803 804
		 * labeled if this is the topmost plan level.  Copy the "source
		 * column" information too.
805 806 807 808 809 810 811
		 */
		forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
		{
			TargetEntry *ptle = (TargetEntry *) lfirst(lp);
			TargetEntry *ctle = (TargetEntry *) lfirst(lc);

			ctle->resname = ptle->resname;
812 813
			ctle->resorigtbl = ptle->resorigtbl;
			ctle->resorigcol = ptle->resorigcol;
814
		}
815 816 817 818
	}
	else
	{
		/*
B
Bruce Momjian 已提交
819 820
		 * Keep the SubqueryScan node.	We have to do the processing that
		 * set_plan_references would otherwise have done on it.  Notice we do
821
		 * not do set_upper_references() here, because a SubqueryScan will
B
Bruce Momjian 已提交
822 823
		 * always have been created with correct references to its subplan's
		 * outputs to begin with.
824
		 */
825 826
		plan->scan.scanrelid += rtoffset;
		plan->scan.plan.targetlist =
827
			fix_scan_list(root, plan->scan.plan.targetlist, rtoffset);
828
		plan->scan.plan.qual =
829
			fix_scan_list(root, plan->scan.plan.qual, rtoffset);
830

831
		result = (Plan *) plan;
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
	}

	return result;
}

/*
 * trivial_subqueryscan
 *		Detect whether a SubqueryScan can be deleted from the plan tree.
 *
 * We can delete it if it has no qual to check and the targetlist just
 * regurgitates the output of the child plan.
 */
static bool
trivial_subqueryscan(SubqueryScan *plan)
{
	int			attrno;
	ListCell   *lp,
			   *lc;

	if (plan->scan.plan.qual != NIL)
		return false;

854 855 856 857
	if (list_length(plan->scan.plan.targetlist) !=
		list_length(plan->subplan->targetlist))
		return false;			/* tlists not same length */

858 859 860 861 862 863 864 865
	attrno = 1;
	forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
	{
		TargetEntry *ptle = (TargetEntry *) lfirst(lp);
		TargetEntry *ctle = (TargetEntry *) lfirst(lc);

		if (ptle->resjunk != ctle->resjunk)
			return false;		/* tlist doesn't match junk status */
866 867

		/*
B
Bruce Momjian 已提交
868 869 870
		 * We accept either a Var referencing the corresponding element of the
		 * subplan tlist, or a Const equaling the subplan element. See
		 * generate_setop_tlist() for motivation.
871 872 873
		 */
		if (ptle->expr && IsA(ptle->expr, Var))
		{
B
Bruce Momjian 已提交
874
			Var		   *var = (Var *) ptle->expr;
875 876 877 878 879 880 881 882 883 884 885 886 887 888

			Assert(var->varno == plan->scan.scanrelid);
			Assert(var->varlevelsup == 0);
			if (var->varattno != attrno)
				return false;	/* out of order */
		}
		else if (ptle->expr && IsA(ptle->expr, Const))
		{
			if (!equal(ptle->expr, ctle->expr))
				return false;
		}
		else
			return false;

889 890 891 892 893 894
		attrno++;
	}

	return true;
}

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
/*
 * copyVar
 *		Copy a Var node.
 *
 * fix_scan_expr and friends do this enough times that it's worth having
 * a bespoke routine instead of using the generic copyObject() function.
 */
static inline Var *
copyVar(Var *var)
{
	Var		   *newvar = (Var *) palloc(sizeof(Var));

	*newvar = *var;
	return newvar;
}

911 912 913 914 915 916
/*
 * fix_expr_common
 *		Do generic set_plan_references processing on an expression node
 *
 * This is code that is common to all variants of expression-fixing.
 * We must look up operator opcode info for OpExpr and related nodes,
917 918
 * add OIDs from regclass Const nodes into root->glob->relationOids, and
 * add catalog TIDs for user-defined functions into root->glob->invalItems.
919 920 921 922 923
 *
 * We assume it's okay to update opcode info in-place.  So this could possibly
 * scribble on the planner's input data structures, but it's OK.
 */
static void
924
fix_expr_common(PlannerInfo *root, Node *node)
925 926 927 928
{
	/* We assume callers won't call us on a NULL pointer */
	if (IsA(node, Aggref))
	{
929
		record_plan_function_dependency(root,
930 931
										((Aggref *) node)->aggfnoid);
	}
T
Tom Lane 已提交
932 933
	else if (IsA(node, WindowFunc))
	{
934
		record_plan_function_dependency(root,
T
Tom Lane 已提交
935 936
										((WindowFunc *) node)->winfnoid);
	}
937 938
	else if (IsA(node, FuncExpr))
	{
939
		record_plan_function_dependency(root,
940 941 942 943 944
										((FuncExpr *) node)->funcid);
	}
	else if (IsA(node, OpExpr))
	{
		set_opfuncid((OpExpr *) node);
945
		record_plan_function_dependency(root,
946 947 948 949 950
										((OpExpr *) node)->opfuncid);
	}
	else if (IsA(node, DistinctExpr))
	{
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
951
		record_plan_function_dependency(root,
952 953 954 955 956
										((DistinctExpr *) node)->opfuncid);
	}
	else if (IsA(node, NullIfExpr))
	{
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
957
		record_plan_function_dependency(root,
958 959 960 961 962
										((NullIfExpr *) node)->opfuncid);
	}
	else if (IsA(node, ScalarArrayOpExpr))
	{
		set_sa_opfuncid((ScalarArrayOpExpr *) node);
963
		record_plan_function_dependency(root,
964
									 ((ScalarArrayOpExpr *) node)->opfuncid);
965 966 967 968
	}
	else if (IsA(node, ArrayCoerceExpr))
	{
		if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
969
			record_plan_function_dependency(root,
970
									 ((ArrayCoerceExpr *) node)->elemfuncid);
971 972 973 974 975 976 977
	}
	else if (IsA(node, Const))
	{
		Const	   *con = (Const *) node;

		/* Check for regclass reference */
		if (ISREGCLASSCONST(con))
978 979
			root->glob->relationOids =
				lappend_oid(root->glob->relationOids,
980 981 982 983
							DatumGetObjectId(con->constvalue));
	}
}

984
/*
985 986
 * fix_scan_expr
 *		Do set_plan_references processing on a scan-level expression
987
 *
988 989
 * This consists of incrementing all Vars' varnos by rtoffset,
 * looking up operator opcode info for OpExpr and related nodes,
990
 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
991
 */
992
static Node *
993
fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset)
994
{
995 996
	fix_scan_expr_context context;

997
	context.root = root;
998
	context.rtoffset = rtoffset;
999

1000
	if (rtoffset != 0 || root->glob->lastPHId != 0)
1001 1002 1003 1004 1005 1006
	{
		return fix_scan_expr_mutator(node, &context);
	}
	else
	{
		/*
1007 1008 1009
		 * If rtoffset == 0, we don't need to change any Vars, and if there
		 * are no placeholders anywhere we won't need to remove them.  Then
		 * it's OK to just scribble on the input node tree instead of copying
1010 1011
		 * (since the only change, filling in any unset opfuncid fields, is
		 * harmless).  This saves just enough cycles to be noticeable on
1012 1013 1014 1015 1016
		 * trivial queries.
		 */
		(void) fix_scan_expr_walker(node, &context);
		return node;
	}
1017 1018
}

1019
static Node *
1020
fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
1021 1022
{
	if (node == NULL)
1023
		return NULL;
1024 1025
	if (IsA(node, Var))
	{
1026
		Var		   *var = copyVar((Var *) node);
1027 1028

		Assert(var->varlevelsup == 0);
B
Bruce Momjian 已提交
1029

1030
		/*
1031 1032
		 * We should not see any Vars marked INNER_VAR or OUTER_VAR.  But an
		 * indexqual expression could contain INDEX_VAR Vars.
1033
		 */
1034 1035 1036 1037
		Assert(var->varno != INNER_VAR);
		Assert(var->varno != OUTER_VAR);
		if (!IS_SPECIAL_VARNO(var->varno))
			var->varno += context->rtoffset;
1038
		if (var->varnoold > 0)
1039 1040
			var->varnoold += context->rtoffset;
		return (Node *) var;
1041
	}
1042 1043 1044 1045
	if (IsA(node, CurrentOfExpr))
	{
		CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);

1046 1047 1048 1049
		Assert(cexpr->cvarno != INNER_VAR);
		Assert(cexpr->cvarno != OUTER_VAR);
		if (!IS_SPECIAL_VARNO(cexpr->cvarno))
			cexpr->cvarno += context->rtoffset;
1050 1051
		return (Node *) cexpr;
	}
1052 1053 1054 1055 1056 1057 1058
	if (IsA(node, PlaceHolderVar))
	{
		/* At scan level, we should always just evaluate the contained expr */
		PlaceHolderVar *phv = (PlaceHolderVar *) node;

		return fix_scan_expr_mutator((Node *) phv->phexpr, context);
	}
1059
	fix_expr_common(context->root, node);
1060 1061
	return expression_tree_mutator(node, fix_scan_expr_mutator,
								   (void *) context);
1062 1063
}

1064 1065 1066 1067 1068
static bool
fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
{
	if (node == NULL)
		return false;
1069
	Assert(!IsA(node, PlaceHolderVar));
1070
	fix_expr_common(context->root, node);
1071 1072 1073 1074
	return expression_tree_walker(node, fix_scan_expr_walker,
								  (void *) context);
}

1075
/*
1076
 * set_join_references
1077
 *	  Modify the target list and quals of a join node to reference its
1078 1079 1080
 *	  subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
 *	  attno values to the result domain number of either the corresponding
 *	  outer or inner join tuple item.  Also perform opcode lookup for these
1081
 *	  expressions. and add regclass OIDs to root->glob->relationOids.
1082 1083
 */
static void
1084
set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1085
{
1086 1087
	Plan	   *outer_plan = join->plan.lefttree;
	Plan	   *inner_plan = join->plan.righttree;
1088 1089
	indexed_tlist *outer_itlist;
	indexed_tlist *inner_itlist;
1090

1091 1092
	outer_itlist = build_tlist_index(outer_plan->targetlist);
	inner_itlist = build_tlist_index(inner_plan->targetlist);
1093

1094
	/* All join plans have tlist, qual, and joinqual */
1095
	join->plan.targetlist = fix_join_expr(root,
1096
										  join->plan.targetlist,
1097 1098 1099 1100
										  outer_itlist,
										  inner_itlist,
										  (Index) 0,
										  rtoffset);
1101
	join->plan.qual = fix_join_expr(root,
1102
									join->plan.qual,
1103 1104 1105 1106
									outer_itlist,
									inner_itlist,
									(Index) 0,
									rtoffset);
1107
	join->joinqual = fix_join_expr(root,
1108
								   join->joinqual,
1109 1110 1111 1112
								   outer_itlist,
								   inner_itlist,
								   (Index) 0,
								   rtoffset);
1113 1114 1115 1116

	/* Now do join-type-specific stuff */
	if (IsA(join, NestLoop))
	{
1117 1118 1119 1120 1121 1122 1123
		NestLoop   *nl = (NestLoop *) join;
		ListCell   *lc;

		foreach(lc, nl->nestParams)
		{
			NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);

1124
			nlp->paramval = (Var *) fix_upper_expr(root,
1125 1126
												   (Node *) nlp->paramval,
												   outer_itlist,
1127
												   OUTER_VAR,
1128
												   rtoffset);
1129 1130 1131 1132
			/* Check we replaced any PlaceHolderVar with simple Var */
			if (!(IsA(nlp->paramval, Var) &&
				  nlp->paramval->varno == OUTER_VAR))
				elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1133
		}
1134 1135 1136 1137 1138
	}
	else if (IsA(join, MergeJoin))
	{
		MergeJoin  *mj = (MergeJoin *) join;

1139
		mj->mergeclauses = fix_join_expr(root,
1140
										 mj->mergeclauses,
1141 1142 1143 1144
										 outer_itlist,
										 inner_itlist,
										 (Index) 0,
										 rtoffset);
1145 1146 1147 1148 1149
	}
	else if (IsA(join, HashJoin))
	{
		HashJoin   *hj = (HashJoin *) join;

1150
		hj->hashclauses = fix_join_expr(root,
1151
										hj->hashclauses,
1152 1153 1154 1155
										outer_itlist,
										inner_itlist,
										(Index) 0,
										rtoffset);
1156
	}
1157 1158 1159

	pfree(outer_itlist);
	pfree(inner_itlist);
1160 1161
}

1162
/*
1163
 * set_upper_references
1164 1165
 *	  Update the targetlist and quals of an upper-level plan node
 *	  to refer to the tuples returned by its lefttree subplan.
1166
 *	  Also perform opcode lookup for these expressions, and
1167
 *	  add regclass OIDs to root->glob->relationOids.
1168
 *
1169
 * This is used for single-input plan types like Agg, Group, Result.
1170 1171 1172 1173 1174
 *
 * In most cases, we have to match up individual Vars in the tlist and
 * qual expressions with elements of the subplan's tlist (which was
 * generated by flatten_tlist() from these selfsame expressions, so it
 * should have all the required variables).  There is an important exception,
1175 1176 1177 1178
 * however: GROUP BY and ORDER BY expressions will have been pushed into the
 * subplan tlist unflattened.  If these values are also needed in the output
 * then we want to reference the subplan tlist element rather than recomputing
 * the expression.
1179 1180
 */
static void
1181
set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
1182
{
1183
	Plan	   *subplan = plan->lefttree;
1184 1185
	indexed_tlist *subplan_itlist;
	List	   *output_targetlist;
1186
	ListCell   *l;
1187

1188
	subplan_itlist = build_tlist_index(subplan->targetlist);
1189 1190 1191 1192 1193 1194 1195

	output_targetlist = NIL;
	foreach(l, plan->targetlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);
		Node	   *newexpr;

1196 1197 1198 1199 1200 1201 1202
		/* If it's a non-Var sort/group item, first try to match by sortref */
		if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
		{
			newexpr = (Node *)
				search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
													  tle->ressortgroupref,
													  subplan_itlist,
1203
													  OUTER_VAR);
1204
			if (!newexpr)
1205
				newexpr = fix_upper_expr(root,
1206 1207
										 (Node *) tle->expr,
										 subplan_itlist,
1208
										 OUTER_VAR,
1209 1210 1211
										 rtoffset);
		}
		else
1212
			newexpr = fix_upper_expr(root,
1213 1214
									 (Node *) tle->expr,
									 subplan_itlist,
1215
									 OUTER_VAR,
1216
									 rtoffset);
1217 1218 1219
		tle = flatCopyTargetEntry(tle);
		tle->expr = (Expr *) newexpr;
		output_targetlist = lappend(output_targetlist, tle);
1220 1221
	}
	plan->targetlist = output_targetlist;
1222 1223

	plan->qual = (List *)
1224
		fix_upper_expr(root,
1225
					   (Node *) plan->qual,
1226
					   subplan_itlist,
1227
					   OUTER_VAR,
1228
					   rtoffset);
1229 1230

	pfree(subplan_itlist);
1231 1232
}

1233 1234 1235
/*
 * set_dummy_tlist_references
 *	  Replace the targetlist of an upper-level plan node with a simple
1236
 *	  list of OUTER_VAR references to its child.
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
 *
 * This is used for plan types like Sort and Append that don't evaluate
 * their targetlists.  Although the executor doesn't care at all what's in
 * the tlist, EXPLAIN needs it to be realistic.
 *
 * Note: we could almost use set_upper_references() here, but it fails for
 * Append for lack of a lefttree subplan.  Single-purpose code is faster
 * anyway.
 */
static void
set_dummy_tlist_references(Plan *plan, int rtoffset)
{
	List	   *output_targetlist;
	ListCell   *l;

	output_targetlist = NIL;
	foreach(l, plan->targetlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);
		Var		   *oldvar = (Var *) tle->expr;
		Var		   *newvar;

1259
		newvar = makeVar(OUTER_VAR,
1260 1261 1262
						 tle->resno,
						 exprType((Node *) oldvar),
						 exprTypmod((Node *) oldvar),
P
Peter Eisentraut 已提交
1263
						 exprCollation((Node *) oldvar),
1264 1265 1266 1267 1268 1269 1270 1271
						 0);
		if (IsA(oldvar, Var))
		{
			newvar->varnoold = oldvar->varno + rtoffset;
			newvar->varoattno = oldvar->varattno;
		}
		else
		{
B
Bruce Momjian 已提交
1272
			newvar->varnoold = 0;		/* wasn't ever a plain Var */
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
			newvar->varoattno = 0;
		}

		tle = flatCopyTargetEntry(tle);
		tle->expr = (Expr *) newvar;
		output_targetlist = lappend(output_targetlist, tle);
	}
	plan->targetlist = output_targetlist;

	/* We don't touch plan->qual here */
}


1286
/*
1287
 * build_tlist_index --- build an index data structure for a child tlist
1288
 *
1289 1290
 * In most cases, subplan tlists will be "flat" tlists with only Vars,
 * so we try to optimize that case by extracting information about Vars
B
Bruce Momjian 已提交
1291
 * in advance.	Matching a parent tlist to a child is still an O(N^2)
1292 1293 1294 1295 1296 1297
 * operation, but at least with a much smaller constant factor than plain
 * tlist_member() searches.
 *
 * The result of this function is an indexed_tlist struct to pass to
 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
 * When done, the indexed_tlist may be freed with a single pfree().
1298
 */
1299 1300
static indexed_tlist *
build_tlist_index(List *tlist)
1301
{
1302 1303
	indexed_tlist *itlist;
	tlist_vinfo *vinfo;
1304
	ListCell   *l;
1305

1306 1307 1308 1309 1310 1311
	/* Create data structure with enough slots for all tlist entries */
	itlist = (indexed_tlist *)
		palloc(offsetof(indexed_tlist, vars) +
			   list_length(tlist) * sizeof(tlist_vinfo));

	itlist->tlist = tlist;
1312
	itlist->has_ph_vars = false;
1313 1314 1315 1316
	itlist->has_non_vars = false;

	/* Find the Vars and fill in the index array */
	vinfo = itlist->vars;
1317 1318 1319 1320
	foreach(l, tlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);

1321 1322
		if (tle->expr && IsA(tle->expr, Var))
		{
B
Bruce Momjian 已提交
1323
			Var		   *var = (Var *) tle->expr;
1324 1325 1326 1327 1328 1329

			vinfo->varno = var->varno;
			vinfo->varattno = var->varattno;
			vinfo->resno = tle->resno;
			vinfo++;
		}
1330 1331
		else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
			itlist->has_ph_vars = true;
1332 1333 1334 1335 1336 1337 1338 1339 1340
		else
			itlist->has_non_vars = true;
	}

	itlist->num_vars = (vinfo - itlist->vars);

	return itlist;
}

1341 1342 1343 1344
/*
 * build_tlist_index_other_vars --- build a restricted tlist index
 *
 * This is like build_tlist_index, but we only index tlist entries that
1345 1346 1347
 * are Vars belonging to some rel other than the one specified.  We will set
 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
 * (so nothing other than Vars and PlaceHolderVars can be matched).
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
 */
static indexed_tlist *
build_tlist_index_other_vars(List *tlist, Index ignore_rel)
{
	indexed_tlist *itlist;
	tlist_vinfo *vinfo;
	ListCell   *l;

	/* Create data structure with enough slots for all tlist entries */
	itlist = (indexed_tlist *)
		palloc(offsetof(indexed_tlist, vars) +
			   list_length(tlist) * sizeof(tlist_vinfo));

	itlist->tlist = tlist;
1362
	itlist->has_ph_vars = false;
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
	itlist->has_non_vars = false;

	/* Find the desired Vars and fill in the index array */
	vinfo = itlist->vars;
	foreach(l, tlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);

		if (tle->expr && IsA(tle->expr, Var))
		{
			Var		   *var = (Var *) tle->expr;

			if (var->varno != ignore_rel)
			{
				vinfo->varno = var->varno;
				vinfo->varattno = var->varattno;
				vinfo->resno = tle->resno;
				vinfo++;
			}
		}
1383 1384
		else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
			itlist->has_ph_vars = true;
1385 1386 1387 1388 1389 1390 1391
	}

	itlist->num_vars = (vinfo - itlist->vars);

	return itlist;
}

1392 1393 1394 1395 1396
/*
 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
 *
 * If a match is found, return a copy of the given Var with suitably
 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1397
 * Also ensure that varnoold is incremented by rtoffset.
1398 1399 1400
 * If no match, return NULL.
 */
static Var *
1401 1402
search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
							 Index newvarno, int rtoffset)
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
{
	Index		varno = var->varno;
	AttrNumber	varattno = var->varattno;
	tlist_vinfo *vinfo;
	int			i;

	vinfo = itlist->vars;
	i = itlist->num_vars;
	while (i-- > 0)
	{
		if (vinfo->varno == varno && vinfo->varattno == varattno)
		{
			/* Found a match */
1416
			Var		   *newvar = copyVar(var);
1417 1418 1419

			newvar->varno = newvarno;
			newvar->varattno = vinfo->resno;
1420 1421
			if (newvar->varnoold > 0)
				newvar->varnoold += rtoffset;
1422 1423 1424
			return newvar;
		}
		vinfo++;
1425
	}
1426 1427 1428 1429 1430 1431 1432 1433 1434
	return NULL;				/* no match */
}

/*
 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
 *
 * If a match is found, return a Var constructed to reference the tlist item.
 * If no match, return NULL.
 *
1435 1436
 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
 * itlist->has_non_vars
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
 */
static Var *
search_indexed_tlist_for_non_var(Node *node,
								 indexed_tlist *itlist, Index newvarno)
{
	TargetEntry *tle;

	tle = tlist_member(node, itlist->tlist);
	if (tle)
	{
		/* Found a matching subplan output expression */
		Var		   *newvar;

1450
		newvar = makeVarFromTargetEntry(newvarno, tle);
B
Bruce Momjian 已提交
1451
		newvar->varnoold = 0;	/* wasn't ever a plain Var */
1452 1453 1454 1455
		newvar->varoattno = 0;
		return newvar;
	}
	return NULL;				/* no match */
1456 1457
}

1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
/*
 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
 *		(which is assumed not to be just a Var)
 *
 * If a match is found, return a Var constructed to reference the tlist item.
 * If no match, return NULL.
 *
 * This is needed to ensure that we select the right subplan TLE in cases
 * where there are multiple textually-equal()-but-volatile sort expressions.
 * And it's also faster than search_indexed_tlist_for_non_var.
 */
static Var *
search_indexed_tlist_for_sortgroupref(Node *node,
									  Index sortgroupref,
									  indexed_tlist *itlist,
									  Index newvarno)
{
	ListCell   *lc;

	foreach(lc, itlist->tlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(lc);

		/* The equal() check should be redundant, but let's be paranoid */
		if (tle->ressortgroupref == sortgroupref &&
			equal(node, tle->expr))
		{
			/* Found a matching subplan output expression */
			Var		   *newvar;

1488
			newvar = makeVarFromTargetEntry(newvarno, tle);
B
Bruce Momjian 已提交
1489
			newvar->varnoold = 0;		/* wasn't ever a plain Var */
1490 1491 1492 1493 1494 1495 1496
			newvar->varoattno = 0;
			return newvar;
		}
	}
	return NULL;				/* no match */
}

1497
/*
1498 1499
 * fix_join_expr
 *	   Create a new set of targetlist entries or join qual clauses by
1500 1501
 *	   changing the varno/varattno values of variables in the clauses
 *	   to reference target list values from the outer and inner join
1502
 *	   relation target lists.  Also perform opcode lookup and add
1503
 *	   regclass OIDs to root->glob->relationOids.
1504
 *
1505 1506 1507 1508 1509 1510
 * This is used in two different scenarios: a normal join clause, where all
 * the Vars in the clause *must* be replaced by OUTER_VAR or INNER_VAR
 * references; and a RETURNING clause, which may contain both Vars of the
 * target relation and Vars of other relations.  In the latter case we want
 * to replace the other-relation Vars by OUTER_VAR references, while leaving
 * target Vars alone.
1511 1512
 *
 * For a normal join, acceptable_rel should be zero so that any failure to
1513 1514
 * match a Var will be reported as an error.  For the RETURNING case, pass
 * inner_itlist = NULL and acceptable_rel = the ID of the target relation.
1515 1516
 *
 * 'clauses' is the targetlist or list of join clauses
1517 1518 1519
 * 'outer_itlist' is the indexed target list of the outer join relation
 * 'inner_itlist' is the indexed target list of the inner join relation,
 *		or NULL
1520
 * 'acceptable_rel' is either zero or the rangetable index of a relation
1521 1522
 *		whose Vars may appear in the clause without provoking an error
 * 'rtoffset': how much to increment varnoold by
1523
 *
1524
 * Returns the new expression tree.  The original clause structure is
1525
 * not modified.
1526
 */
1527
static List *
1528
fix_join_expr(PlannerInfo *root,
1529
			  List *clauses,
1530 1531 1532 1533
			  indexed_tlist *outer_itlist,
			  indexed_tlist *inner_itlist,
			  Index acceptable_rel,
			  int rtoffset)
1534
{
1535
	fix_join_expr_context context;
B
Bruce Momjian 已提交
1536

1537
	context.root = root;
1538 1539
	context.outer_itlist = outer_itlist;
	context.inner_itlist = inner_itlist;
1540
	context.acceptable_rel = acceptable_rel;
1541 1542
	context.rtoffset = rtoffset;
	return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1543 1544
}

1545
static Node *
1546
fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1547
{
1548 1549
	Var		   *newvar;

1550 1551 1552 1553 1554
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
1555

1556
		/* First look for the var in the input tlists */
1557 1558
		newvar = search_indexed_tlist_for_var(var,
											  context->outer_itlist,
1559
											  OUTER_VAR,
1560
											  context->rtoffset);
1561
		if (newvar)
1562
			return (Node *) newvar;
1563
		if (context->inner_itlist)
1564
		{
1565 1566
			newvar = search_indexed_tlist_for_var(var,
												  context->inner_itlist,
1567
												  INNER_VAR,
1568
												  context->rtoffset);
1569 1570
			if (newvar)
				return (Node *) newvar;
1571
		}
1572

1573
		/* If it's for acceptable_rel, adjust and return it */
1574
		if (var->varno == context->acceptable_rel)
1575
		{
1576
			var = copyVar(var);
1577
			var->varno += context->rtoffset;
1578 1579
			if (var->varnoold > 0)
				var->varnoold += context->rtoffset;
1580 1581
			return (Node *) var;
		}
1582 1583

		/* No referent found for Var */
1584
		elog(ERROR, "variable not found in subplan target lists");
1585
	}
1586 1587 1588 1589 1590 1591 1592 1593 1594
	if (IsA(node, PlaceHolderVar))
	{
		PlaceHolderVar *phv = (PlaceHolderVar *) node;

		/* See if the PlaceHolderVar has bubbled up from a lower plan node */
		if (context->outer_itlist->has_ph_vars)
		{
			newvar = search_indexed_tlist_for_non_var((Node *) phv,
													  context->outer_itlist,
1595
													  OUTER_VAR);
1596 1597 1598 1599 1600 1601 1602
			if (newvar)
				return (Node *) newvar;
		}
		if (context->inner_itlist && context->inner_itlist->has_ph_vars)
		{
			newvar = search_indexed_tlist_for_non_var((Node *) phv,
													  context->inner_itlist,
1603
													  INNER_VAR);
1604 1605 1606 1607 1608 1609 1610
			if (newvar)
				return (Node *) newvar;
		}

		/* If not supplied by input plans, evaluate the contained expr */
		return fix_join_expr_mutator((Node *) phv->phexpr, context);
	}
1611
	/* Try matching more complex expressions too, if tlists have any */
1612
	if (context->outer_itlist->has_non_vars)
1613
	{
1614 1615
		newvar = search_indexed_tlist_for_non_var(node,
												  context->outer_itlist,
1616
												  OUTER_VAR);
1617
		if (newvar)
1618
			return (Node *) newvar;
1619 1620 1621 1622 1623
	}
	if (context->inner_itlist && context->inner_itlist->has_non_vars)
	{
		newvar = search_indexed_tlist_for_non_var(node,
												  context->inner_itlist,
1624
												  INNER_VAR);
1625
		if (newvar)
1626 1627
			return (Node *) newvar;
	}
1628
	fix_expr_common(context->root, node);
1629
	return expression_tree_mutator(node,
1630
								   fix_join_expr_mutator,
1631
								   (void *) context);
1632 1633
}

1634
/*
1635 1636
 * fix_upper_expr
 *		Modifies an expression tree so that all Var nodes reference outputs
1637
 *		of a subplan.  Also performs opcode lookup, and adds regclass OIDs to
1638
 *		root->glob->relationOids.
1639 1640
 *
 * This is used to fix up target and qual expressions of non-join upper-level
1641
 * plan nodes, as well as index-only scan nodes.
1642
 *
1643 1644 1645
 * An error is raised if no matching var can be found in the subplan tlist
 * --- so this routine should only be applied to nodes whose subplans'
 * targetlists were generated via flatten_tlist() or some such method.
1646
 *
1647
 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1648 1649 1650 1651 1652 1653
 * against elements of the subplan tlist, so that we can avoid recomputing
 * expressions that were already computed by the subplan.  (This is relatively
 * expensive, so we don't want to try it in the common case where the
 * subplan tlist is just a flattened list of Vars.)
 *
 * 'node': the tree to be fixed (a target item or qual)
1654 1655
 * 'subplan_itlist': indexed target list for subplan (or index)
 * 'newvarno': varno to use for Vars referencing tlist elements
1656
 * 'rtoffset': how much to increment varnoold by
1657
 *
1658
 * The resulting tree is a copy of the original in which all Var nodes have
1659
 * varno = newvarno, varattno = resno of corresponding targetlist element.
1660
 * The original tree is not modified.
1661
 */
1662
static Node *
1663
fix_upper_expr(PlannerInfo *root,
1664
			   Node *node,
1665
			   indexed_tlist *subplan_itlist,
1666
			   Index newvarno,
1667
			   int rtoffset)
1668
{
1669
	fix_upper_expr_context context;
1670

1671
	context.root = root;
1672
	context.subplan_itlist = subplan_itlist;
1673
	context.newvarno = newvarno;
1674 1675
	context.rtoffset = rtoffset;
	return fix_upper_expr_mutator(node, &context);
1676
}
B
Bruce Momjian 已提交
1677

1678
static Node *
1679
fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1680
{
1681 1682
	Var		   *newvar;

1683
	if (node == NULL)
1684
		return NULL;
1685 1686 1687
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
1688

1689 1690
		newvar = search_indexed_tlist_for_var(var,
											  context->subplan_itlist,
1691
											  context->newvarno,
1692
											  context->rtoffset);
1693
		if (!newvar)
1694
			elog(ERROR, "variable not found in subplan target list");
1695 1696
		return (Node *) newvar;
	}
1697 1698 1699 1700 1701 1702 1703 1704 1705
	if (IsA(node, PlaceHolderVar))
	{
		PlaceHolderVar *phv = (PlaceHolderVar *) node;

		/* See if the PlaceHolderVar has bubbled up from a lower plan node */
		if (context->subplan_itlist->has_ph_vars)
		{
			newvar = search_indexed_tlist_for_non_var((Node *) phv,
													  context->subplan_itlist,
1706
													  context->newvarno);
1707 1708 1709 1710 1711 1712
			if (newvar)
				return (Node *) newvar;
		}
		/* If not supplied by input plan, evaluate the contained expr */
		return fix_upper_expr_mutator((Node *) phv->phexpr, context);
	}
1713
	/* Try matching more complex expressions too, if tlist has any */
1714
	if (context->subplan_itlist->has_non_vars)
1715
	{
1716 1717
		newvar = search_indexed_tlist_for_non_var(node,
												  context->subplan_itlist,
1718
												  context->newvarno);
1719
		if (newvar)
1720 1721
			return (Node *) newvar;
	}
1722
	fix_expr_common(context->root, node);
1723
	return expression_tree_mutator(node,
1724
								   fix_upper_expr_mutator,
1725
								   (void *) context);
1726 1727
}

1728 1729 1730 1731 1732 1733
/*
 * set_returning_clause_references
 *		Perform setrefs.c's work on a RETURNING targetlist
 *
 * If the query involves more than just the result table, we have to
 * adjust any Vars that refer to other tables to reference junk tlist
1734
 * entries in the top subplan's targetlist.  Vars referencing the result
1735
 * table should be left alone, however (the executor will evaluate them
B
Bruce Momjian 已提交
1736
 * using the actual heap tuple, after firing triggers if any).	In the
1737 1738
 * adjusted RETURNING list, result-table Vars will have their original
 * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
1739
 *
1740
 * We also must perform opcode lookup and add regclass OIDs to
1741
 * root->glob->relationOids.
1742 1743
 *
 * 'rlist': the RETURNING targetlist to be fixed
1744
 * 'topplan': the top subplan node that will be just below the ModifyTable
1745
 *		node (note it's not yet passed through set_plan_refs)
1746
 * 'resultRelation': RT index of the associated result relation
1747
 * 'rtoffset': how much to increment varnos by
1748
 *
1749 1750 1751 1752 1753 1754
 * Note: the given 'root' is for the parent query level, not the 'topplan'.
 * This does not matter currently since we only access the dependency-item
 * lists in root->glob, but it would need some hacking if we wanted a root
 * that actually matches the subplan.
 *
 * Note: resultRelation is not yet adjusted by rtoffset.
1755
 */
1756
static List *
1757
set_returning_clause_references(PlannerInfo *root,
1758
								List *rlist,
1759
								Plan *topplan,
1760 1761
								Index resultRelation,
								int rtoffset)
1762 1763 1764 1765
{
	indexed_tlist *itlist;

	/*
1766
	 * We can perform the desired Var fixup by abusing the fix_join_expr
1767
	 * machinery that formerly handled inner indexscan fixup.  We search the
B
Bruce Momjian 已提交
1768
	 * top plan's targetlist for Vars of non-result relations, and use
B
Bruce Momjian 已提交
1769 1770
	 * fix_join_expr to convert RETURNING Vars into references to those tlist
	 * entries, while leaving result-rel Vars as-is.
1771 1772
	 *
	 * PlaceHolderVars will also be sought in the targetlist, but no
1773 1774 1775 1776 1777
	 * more-complex expressions will be.  Note that it is not possible for a
	 * PlaceHolderVar to refer to the result relation, since the result is
	 * never below an outer join.  If that case could happen, we'd have to be
	 * prepared to pick apart the PlaceHolderVar and evaluate its contained
	 * expression instead.
1778 1779 1780
	 */
	itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);

1781
	rlist = fix_join_expr(root,
1782
						  rlist,
1783 1784 1785
						  itlist,
						  NULL,
						  resultRelation,
1786
						  rtoffset);
1787 1788 1789 1790 1791 1792

	pfree(itlist);

	return rlist;
}

1793
/*****************************************************************************
1794
 *					OPERATOR REGPROC LOOKUP
1795 1796
 *****************************************************************************/

1797
/*
1798 1799
 * fix_opfuncids
 *	  Calculate opfuncid field from opno for each OpExpr node in given tree.
1800
 *	  The given tree can be anything expression_tree_walker handles.
1801
 *
1802 1803 1804
 * The argument is modified in-place.  (This is OK since we'd want the
 * same change for any node, even if it gets visited more than once due to
 * shared structure.)
1805
 */
1806
void
1807
fix_opfuncids(Node *node)
1808
{
1809
	/* This tree walk requires no special setup, so away we go... */
1810
	fix_opfuncids_walker(node, NULL);
1811
}
B
Bruce Momjian 已提交
1812

1813
static bool
1814
fix_opfuncids_walker(Node *node, void *context)
1815 1816 1817
{
	if (node == NULL)
		return false;
1818 1819 1820
	if (IsA(node, OpExpr))
		set_opfuncid((OpExpr *) node);
	else if (IsA(node, DistinctExpr))
B
Bruce Momjian 已提交
1821
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
1822
	else if (IsA(node, NullIfExpr))
B
Bruce Momjian 已提交
1823
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
1824 1825
	else if (IsA(node, ScalarArrayOpExpr))
		set_sa_opfuncid((ScalarArrayOpExpr *) node);
1826
	return expression_tree_walker(node, fix_opfuncids_walker, context);
1827
}
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837

/*
 * set_opfuncid
 *		Set the opfuncid (procedure OID) in an OpExpr node,
 *		if it hasn't been set already.
 *
 * Because of struct equivalence, this can also be used for
 * DistinctExpr and NullIfExpr nodes.
 */
void
1838
set_opfuncid(OpExpr *opexpr)
1839 1840 1841 1842 1843 1844 1845 1846 1847
{
	if (opexpr->opfuncid == InvalidOid)
		opexpr->opfuncid = get_opcode(opexpr->opno);
}

/*
 * set_sa_opfuncid
 *		As above, for ScalarArrayOpExpr nodes.
 */
1848
void
1849
set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1850 1851 1852 1853
{
	if (opexpr->opfuncid == InvalidOid)
		opexpr->opfuncid = get_opcode(opexpr->opno);
}
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866

/*****************************************************************************
 *					QUERY DEPENDENCY MANAGEMENT
 *****************************************************************************/

/*
 * record_plan_function_dependency
 *		Mark the current plan as depending on a particular function.
 *
 * This is exported so that the function-inlining code can record a
 * dependency on a function that it's removed from the plan tree.
 */
void
1867
record_plan_function_dependency(PlannerInfo *root, Oid funcid)
1868 1869 1870 1871 1872 1873
{
	/*
	 * For performance reasons, we don't bother to track built-in functions;
	 * we just assume they'll never change (or at least not in ways that'd
	 * invalidate plans using them).  For this purpose we can consider a
	 * built-in function to be one with OID less than FirstBootstrapObjectId.
1874 1875
	 * Note that the OID generator guarantees never to generate such an OID
	 * after startup, even at OID wraparound.
1876 1877 1878
	 */
	if (funcid >= (Oid) FirstBootstrapObjectId)
	{
1879
		PlanInvalItem *inval_item = makeNode(PlanInvalItem);
1880 1881

		/*
1882 1883
		 * It would work to use any syscache on pg_proc, but the easiest is
		 * PROCOID since we already have the function's OID at hand.  Note
1884
		 * that plancache.c knows we use PROCOID.
1885 1886
		 */
		inval_item->cacheId = PROCOID;
1887 1888
		inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
													  ObjectIdGetDatum(funcid));
1889

1890
		root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
1891 1892 1893 1894 1895
	}
}

/*
 * extract_query_dependencies
1896 1897 1898
 *		Given a not-yet-planned query or queries (i.e. a Query node or list
 *		of Query nodes), extract dependencies just as set_plan_references
 *		would do.
1899 1900 1901 1902 1903
 *
 * This is needed by plancache.c to handle invalidation of cached unplanned
 * queries.
 */
void
1904
extract_query_dependencies(Node *query,
1905 1906 1907 1908
						   List **relationOids,
						   List **invalItems)
{
	PlannerGlobal glob;
1909
	PlannerInfo root;
1910

1911
	/* Make up dummy planner state so we can use this module's machinery */
1912 1913 1914 1915 1916
	MemSet(&glob, 0, sizeof(glob));
	glob.type = T_PlannerGlobal;
	glob.relationOids = NIL;
	glob.invalItems = NIL;

1917 1918 1919 1920 1921
	MemSet(&root, 0, sizeof(root));
	root.type = T_PlannerInfo;
	root.glob = &glob;

	(void) extract_query_dependencies_walker(query, &root);
1922 1923 1924 1925 1926 1927

	*relationOids = glob.relationOids;
	*invalItems = glob.invalItems;
}

static bool
1928
extract_query_dependencies_walker(Node *node, PlannerInfo *context)
1929 1930 1931
{
	if (node == NULL)
		return false;
1932
	Assert(!IsA(node, PlaceHolderVar));
1933 1934 1935 1936 1937 1938 1939
	/* Extract function dependencies and check for regclass Consts */
	fix_expr_common(context, node);
	if (IsA(node, Query))
	{
		Query	   *query = (Query *) node;
		ListCell   *lc;

1940
		while (query->commandType == CMD_UTILITY)
1941
		{
1942 1943 1944 1945 1946 1947
			/*
			 * Ignore utility statements, except those (such as EXPLAIN) that
			 * contain a parsed-but-not-planned query.
			 */
			query = UtilityContainsQuery(query->utilityStmt);
			if (query == NULL)
1948 1949 1950
				return false;
		}

1951 1952 1953 1954 1955 1956
		/* Collect relation OIDs in this Query's rtable */
		foreach(lc, query->rtable)
		{
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);

			if (rte->rtekind == RTE_RELATION)
1957 1958
				context->glob->relationOids =
					lappend_oid(context->glob->relationOids, rte->relid);
1959 1960 1961 1962 1963 1964 1965 1966 1967
		}

		/* And recurse into the query's subexpressions */
		return query_tree_walker(query, extract_query_dependencies_walker,
								 (void *) context, 0);
	}
	return expression_tree_walker(node, extract_query_dependencies_walker,
								  (void *) context);
}