setrefs.c 57.6 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-2010, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9 10 11
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
12
 *	  $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.160 2010/02/26 02:00:45 momjian Exp $
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 23 24
#include "optimizer/clauses.h"
#include "optimizer/planmain.h"
#include "optimizer/tlist.h"
25
#include "parser/parsetree.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
	PlannerGlobal *glob;
50
	int			rtoffset;
51
} fix_scan_expr_context;
52

53 54
typedef struct
{
55
	PlannerGlobal *glob;
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
	PlannerGlobal *glob;
65
	indexed_tlist *subplan_itlist;
66
	int			rtoffset;
67
} fix_upper_expr_context;
68

69 70 71 72 73 74 75 76 77 78 79
/*
 * 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)

80 81
#define fix_scan_list(glob, lst, rtoffset) \
	((List *) fix_scan_expr(glob, (Node *) (lst), rtoffset))
82

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

125 126

/*****************************************************************************
127 128 129
 *
 *		SUBPLAN REFERENCES
 *
130 131
 *****************************************************************************/

132
/*
133
 * set_plan_references
134
 *
B
Bruce Momjian 已提交
135
 * This is the final processing pass of the planner/optimizer.	The plan
136
 * tree is complete; we just have to adjust some representational details
137 138 139 140 141 142 143 144 145 146 147 148
 * 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).
149
 *
150
 * 5. We create lists of specific objects that the plan depends on.
151
 * This will be used by plancache.c to drive invalidation of cached plans.
152 153 154 155
 * 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.
156
 *
157 158 159 160
 * 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
161 162
 * 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
163
 * serves a necessary function as a buffer between outer query and subquery
164
 * variable numbering ... but after we've flattened the rangetable this is
165
 * no longer a problem, since then there's only one rtindex namespace.
166 167 168
 *
 * set_plan_references recursively traverses the whole plan tree.
 *
169 170 171 172
 * Inputs:
 *	glob: global data for planner run
 *	plan: the topmost node of the plan
 *	rtable: the rangetable for the current subquery
173
 *	rowmarks: the PlanRowMark list for the current subquery
174
 *
175 176 177
 * 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.
 *
178 179 180
 * The flattened rangetable entries are appended to glob->finalrtable,
 * and we also append rowmarks entries to glob->finalrowmarks.
 * Plan dependencies are appended to glob->relationOids (for relations)
181
 * and glob->invalItems (for everything else).
182 183
 *
 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
B
Bruce Momjian 已提交
184
 * to process targetlist and qual expressions.	We can assume that the Plan
185 186
 * 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.
187
 */
188
Plan *
189 190
set_plan_references(PlannerGlobal *glob, Plan *plan,
					List *rtable, List *rowmarks)
191 192 193 194 195
{
	int			rtoffset = list_length(glob->finalrtable);
	ListCell   *lc;

	/*
B
Bruce Momjian 已提交
196 197 198
	 * 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
199
	 * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
200 201
	 * which are needed for executor-startup permissions checking and for
	 * trigger event checking.
202 203 204
	 */
	foreach(lc, rtable)
	{
B
Bruce Momjian 已提交
205 206
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
		RangeTblEntry *newrte;
207 208 209 210 211

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

212
		/* zap unneeded sub-structure */
213
		newrte->subquery = NULL;
214
		newrte->joinaliasvars = NIL;
215 216 217 218
		newrte->funcexpr = NULL;
		newrte->funccoltypes = NIL;
		newrte->funccoltypmods = NIL;
		newrte->values_lists = NIL;
219 220
		newrte->ctecoltypes = NIL;
		newrte->ctecoltypmods = NIL;
221 222

		glob->finalrtable = lappend(glob->finalrtable, newrte);
223 224 225 226

		/*
		 * If it's a plain relation RTE, add the table to relationOids.
		 *
B
Bruce Momjian 已提交
227 228 229 230 231
		 * 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.
232 233 234 235 236 237 238
		 *
		 * 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);
239 240
	}

241
	/*
242
	 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
243 244 245
	 */
	foreach(lc, rowmarks)
	{
246 247
		PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
		PlanRowMark *newrc;
248

249 250 251 252 253
		Assert(IsA(rc, PlanRowMark));

		/* flat copy is enough since all fields are scalars */
		newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
		memcpy(newrc, rc, sizeof(PlanRowMark));
254 255 256 257 258 259 260 261

		/* adjust indexes */
		newrc->rti += rtoffset;
		newrc->prti += rtoffset;

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

262 263 264 265 266 267 268 269
	/* Now fix the Plan tree */
	return set_plan_refs(glob, plan, rtoffset);
}

/*
 * set_plan_refs: recurse through the Plan nodes of a single subquery level
 */
static Plan *
270
set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
271
{
B
Bruce Momjian 已提交
272
	ListCell   *l;
273

274
	if (plan == NULL)
275
		return NULL;
276

277 278 279 280 281 282
	/*
	 * Plan-type-specific fixes
	 */
	switch (nodeTag(plan))
	{
		case T_SeqScan:
283
			{
B
Bruce Momjian 已提交
284
				SeqScan    *splan = (SeqScan *) plan;
285 286 287

				splan->scanrelid += rtoffset;
				splan->plan.targetlist =
288
					fix_scan_list(glob, splan->plan.targetlist, rtoffset);
289
				splan->plan.qual =
290
					fix_scan_list(glob, splan->plan.qual, rtoffset);
291
			}
292 293
			break;
		case T_IndexScan:
294
			{
B
Bruce Momjian 已提交
295
				IndexScan  *splan = (IndexScan *) plan;
296 297 298

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
299
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
300
				splan->scan.plan.qual =
301
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
302
				splan->indexqual =
303
					fix_scan_list(glob, splan->indexqual, rtoffset);
304
				splan->indexqualorig =
305
					fix_scan_list(glob, splan->indexqualorig, rtoffset);
306
			}
307
			break;
308
		case T_BitmapIndexScan:
309 310 311 312 313 314 315 316
			{
				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 =
317
					fix_scan_list(glob, splan->indexqual, rtoffset);
318
				splan->indexqualorig =
319
					fix_scan_list(glob, splan->indexqualorig, rtoffset);
320
			}
321 322
			break;
		case T_BitmapHeapScan:
323 324 325 326 327
			{
				BitmapHeapScan *splan = (BitmapHeapScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
328
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
329
				splan->scan.plan.qual =
330
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
331
				splan->bitmapqualorig =
332
					fix_scan_list(glob, splan->bitmapqualorig, rtoffset);
333
			}
334
			break;
335
		case T_TidScan:
336
			{
B
Bruce Momjian 已提交
337
				TidScan    *splan = (TidScan *) plan;
338 339 340

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
341
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
342
				splan->scan.plan.qual =
343
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
344
				splan->tidquals =
345
					fix_scan_list(glob, splan->tidquals, rtoffset);
346
			}
347
			break;
348
		case T_SubqueryScan:
349
			/* Needs special treatment, see comments below */
350 351 352
			return set_subqueryscan_references(glob,
											   (SubqueryScan *) plan,
											   rtoffset);
353
		case T_FunctionScan:
354 355 356 357 358
			{
				FunctionScan *splan = (FunctionScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
359
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
360
				splan->scan.plan.qual =
361
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
362
				splan->funcexpr =
363
					fix_scan_expr(glob, splan->funcexpr, rtoffset);
364
			}
365
			break;
366
		case T_ValuesScan:
367 368 369 370 371
			{
				ValuesScan *splan = (ValuesScan *) plan;

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
372
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
373
				splan->scan.plan.qual =
374
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
375
				splan->values_lists =
376
					fix_scan_list(glob, splan->values_lists, rtoffset);
377
			}
378
			break;
379 380
		case T_CteScan:
			{
381
				CteScan    *splan = (CteScan *) plan;
382 383 384 385 386 387 388 389 390 391 392

				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
				splan->scan.plan.qual =
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
			}
			break;
		case T_WorkTableScan:
			{
				WorkTableScan *splan = (WorkTableScan *) plan;
393

394 395 396 397 398 399 400
				splan->scan.scanrelid += rtoffset;
				splan->scan.plan.targetlist =
					fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
				splan->scan.plan.qual =
					fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
			}
			break;
401 402 403
		case T_NestLoop:
		case T_MergeJoin:
		case T_HashJoin:
404
			set_join_references(glob, (Join *) plan, rtoffset);
405
			break;
406

407
		case T_Hash:
408 409 410
		case T_Material:
		case T_Sort:
		case T_Unique:
411
		case T_SetOp:
412 413 414

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

422
			/*
B
Bruce Momjian 已提交
423 424
			 * Since these plan types don't check quals either, we should not
			 * find any qual expression attached to them.
425
			 */
426
			Assert(plan->qual == NIL);
427
			break;
428 429 430 431 432 433
		case T_LockRows:
			{
				LockRows   *splan = (LockRows *) plan;

				/*
				 * Like the plan types above, LockRows doesn't evaluate its
B
Bruce Momjian 已提交
434 435
				 * tlist or quals.	But we have to fix up the RT indexes in
				 * its rowmarks.
436 437 438 439 440 441
				 */
				set_dummy_tlist_references(plan, rtoffset);
				Assert(splan->plan.qual == NIL);

				foreach(l, splan->rowMarks)
				{
442
					PlanRowMark *rc = (PlanRowMark *) lfirst(l);
443 444 445 446 447 448

					rc->rti += rtoffset;
					rc->prti += rtoffset;
				}
			}
			break;
449
		case T_Limit:
450
			{
B
Bruce Momjian 已提交
451
				Limit	   *splan = (Limit *) plan;
452 453 454 455

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

462
				splan->limitOffset =
463
					fix_scan_expr(glob, splan->limitOffset, rtoffset);
464
				splan->limitCount =
465
					fix_scan_expr(glob, splan->limitCount, rtoffset);
466
			}
467
			break;
468 469
		case T_Agg:
		case T_Group:
470
			set_upper_references(glob, plan, rtoffset);
471
			break;
472 473
		case T_WindowAgg:
			{
B
Bruce Momjian 已提交
474
				WindowAgg  *wplan = (WindowAgg *) plan;
475 476 477 478 479 480 481 482 483 484 485 486 487 488

				set_upper_references(glob, plan, rtoffset);

				/*
				 * 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 =
					fix_scan_expr(glob, wplan->startOffset, rtoffset);
				wplan->endOffset =
					fix_scan_expr(glob, wplan->endOffset, rtoffset);
			}
			break;
489
		case T_Result:
490
			{
B
Bruce Momjian 已提交
491
				Result	   *splan = (Result *) plan;
492 493 494 495 496 497

				/*
				 * 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)
498
					set_upper_references(glob, plan, rtoffset);
499 500 501
				else
				{
					splan->plan.targetlist =
502
						fix_scan_list(glob, splan->plan.targetlist, rtoffset);
503
					splan->plan.qual =
504
						fix_scan_list(glob, splan->plan.qual, rtoffset);
505 506 507
				}
				/* resconstantqual can't contain any subplan variable refs */
				splan->resconstantqual =
508
					fix_scan_expr(glob, splan->resconstantqual, rtoffset);
509
			}
510
			break;
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
		case T_ModifyTable:
			{
				ModifyTable *splan = (ModifyTable *) plan;

				/*
				 * planner.c already called set_returning_clause_references,
				 * so we should not process either the targetlist or the
				 * returningLists.
				 */
				Assert(splan->plan.qual == NIL);

				foreach(l, splan->resultRelations)
				{
					lfirst_int(l) += rtoffset;
				}
526 527 528 529 530 531 532
				foreach(l, splan->rowMarks)
				{
					PlanRowMark *rc = (PlanRowMark *) lfirst(l);

					rc->rti += rtoffset;
					rc->prti += rtoffset;
				}
533 534 535 536 537 538 539 540
				foreach(l, splan->plans)
				{
					lfirst(l) = set_plan_refs(glob,
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
			break;
541
		case T_Append:
542
			{
B
Bruce Momjian 已提交
543
				Append	   *splan = (Append *) plan;
544 545 546 547 548

				/*
				 * Append, like Sort et al, doesn't actually evaluate its
				 * targetlist or check quals.
				 */
549
				set_dummy_tlist_references(plan, rtoffset);
550 551 552 553 554 555 556 557
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->appendplans)
				{
					lfirst(l) = set_plan_refs(glob,
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
558
			break;
559 560 561 562 563
		case T_RecursiveUnion:
			/* This doesn't evaluate targetlist or check quals either */
			set_dummy_tlist_references(plan, rtoffset);
			Assert(plan->qual == NIL);
			break;
564
		case T_BitmapAnd:
565
			{
B
Bruce Momjian 已提交
566
				BitmapAnd  *splan = (BitmapAnd *) plan;
567 568 569 570 571 572 573 574 575 576 577

				/* BitmapAnd works like Append, but has no tlist */
				Assert(splan->plan.targetlist == NIL);
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->bitmapplans)
				{
					lfirst(l) = set_plan_refs(glob,
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
578 579
			break;
		case T_BitmapOr:
580
			{
B
Bruce Momjian 已提交
581
				BitmapOr   *splan = (BitmapOr *) plan;
582 583 584 585 586 587 588 589 590 591 592

				/* BitmapOr works like Append, but has no tlist */
				Assert(splan->plan.targetlist == NIL);
				Assert(splan->plan.qual == NIL);
				foreach(l, splan->bitmapplans)
				{
					lfirst(l) = set_plan_refs(glob,
											  (Plan *) lfirst(l),
											  rtoffset);
				}
			}
593
			break;
594
		default:
595 596
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(plan));
597 598
			break;
	}
599

600
	/*
601
	 * Now recurse into child plans, if any
602
	 *
603
	 * NOTE: it is essential that we recurse into child plans AFTER we set
604 605
	 * 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 已提交
606
	 * plan's var nodes against the already-modified nodes of the children.
607
	 */
608 609
	plan->lefttree = set_plan_refs(glob, plan->lefttree, rtoffset);
	plan->righttree = set_plan_refs(glob, plan->righttree, rtoffset);
610 611 612 613 614 615 616 617 618 619 620 621

	return plan;
}

/*
 * 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 *
622
set_subqueryscan_references(PlannerGlobal *glob,
623 624
							SubqueryScan *plan,
							int rtoffset)
625 626 627 628
{
	Plan	   *result;

	/* First, recursively process the subplan */
629 630
	plan->subplan = set_plan_references(glob, plan->subplan,
										plan->subrtable, plan->subrowmark);
631

632
	/* subrtable/subrowmark are no longer needed in the plan tree */
633
	plan->subrtable = NIL;
634
	plan->subrowmark = NIL;
635 636 637 638

	if (trivial_subqueryscan(plan))
	{
		/*
639
		 * We can omit the SubqueryScan node and just pull up the subplan.
640
		 */
641 642
		ListCell   *lp,
				   *lc;
643

644
		result = plan->subplan;
645

646
		/* We have to be sure we don't lose any initplans */
647 648
		result->initPlan = list_concat(plan->scan.plan.initPlan,
									   result->initPlan);
649 650

		/*
651
		 * We also have to transfer the SubqueryScan's result-column names
652
		 * into the subplan, else columns sent to client will be improperly
653 654
		 * labeled if this is the topmost plan level.  Copy the "source
		 * column" information too.
655 656 657 658 659 660 661
		 */
		forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
		{
			TargetEntry *ptle = (TargetEntry *) lfirst(lp);
			TargetEntry *ctle = (TargetEntry *) lfirst(lc);

			ctle->resname = ptle->resname;
662 663
			ctle->resorigtbl = ptle->resorigtbl;
			ctle->resorigcol = ptle->resorigcol;
664
		}
665 666 667 668
	}
	else
	{
		/*
B
Bruce Momjian 已提交
669 670
		 * Keep the SubqueryScan node.	We have to do the processing that
		 * set_plan_references would otherwise have done on it.  Notice we do
671
		 * not do set_upper_references() here, because a SubqueryScan will
B
Bruce Momjian 已提交
672 673
		 * always have been created with correct references to its subplan's
		 * outputs to begin with.
674
		 */
675 676
		plan->scan.scanrelid += rtoffset;
		plan->scan.plan.targetlist =
677
			fix_scan_list(glob, plan->scan.plan.targetlist, rtoffset);
678
		plan->scan.plan.qual =
679
			fix_scan_list(glob, plan->scan.plan.qual, rtoffset);
680

681
		result = (Plan *) plan;
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
	}

	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;

704 705 706 707
	if (list_length(plan->scan.plan.targetlist) !=
		list_length(plan->subplan->targetlist))
		return false;			/* tlists not same length */

708 709 710 711 712 713 714 715
	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 */
716 717

		/*
B
Bruce Momjian 已提交
718 719 720
		 * 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.
721 722 723
		 */
		if (ptle->expr && IsA(ptle->expr, Var))
		{
B
Bruce Momjian 已提交
724
			Var		   *var = (Var *) ptle->expr;
725 726 727 728 729 730 731 732 733 734 735 736 737 738

			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;

739 740 741 742 743 744
		attrno++;
	}

	return true;
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
/*
 * 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;
}

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
/*
 * 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,
 * add OIDs from regclass Const nodes into glob->relationOids,
 * and add catalog TIDs for user-defined functions into glob->invalItems.
 *
 * 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
fix_expr_common(PlannerGlobal *glob, Node *node)
{
	/* We assume callers won't call us on a NULL pointer */
	if (IsA(node, Aggref))
	{
		record_plan_function_dependency(glob,
										((Aggref *) node)->aggfnoid);
	}
T
Tom Lane 已提交
782 783 784 785 786
	else if (IsA(node, WindowFunc))
	{
		record_plan_function_dependency(glob,
										((WindowFunc *) node)->winfnoid);
	}
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	else if (IsA(node, FuncExpr))
	{
		record_plan_function_dependency(glob,
										((FuncExpr *) node)->funcid);
	}
	else if (IsA(node, OpExpr))
	{
		set_opfuncid((OpExpr *) node);
		record_plan_function_dependency(glob,
										((OpExpr *) node)->opfuncid);
	}
	else if (IsA(node, DistinctExpr))
	{
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
		record_plan_function_dependency(glob,
										((DistinctExpr *) node)->opfuncid);
	}
	else if (IsA(node, NullIfExpr))
	{
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
		record_plan_function_dependency(glob,
										((NullIfExpr *) node)->opfuncid);
	}
	else if (IsA(node, ScalarArrayOpExpr))
	{
		set_sa_opfuncid((ScalarArrayOpExpr *) node);
		record_plan_function_dependency(glob,
814
									 ((ScalarArrayOpExpr *) node)->opfuncid);
815 816 817 818 819
	}
	else if (IsA(node, ArrayCoerceExpr))
	{
		if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
			record_plan_function_dependency(glob,
820
									 ((ArrayCoerceExpr *) node)->elemfuncid);
821 822 823 824 825 826 827 828 829 830 831 832 833
	}
	else if (IsA(node, Const))
	{
		Const	   *con = (Const *) node;

		/* Check for regclass reference */
		if (ISREGCLASSCONST(con))
			glob->relationOids =
				lappend_oid(glob->relationOids,
							DatumGetObjectId(con->constvalue));
	}
}

834
/*
835 836
 * fix_scan_expr
 *		Do set_plan_references processing on a scan-level expression
837
 *
838 839 840
 * This consists of incrementing all Vars' varnos by rtoffset,
 * looking up operator opcode info for OpExpr and related nodes,
 * and adding OIDs from regclass Const nodes into glob->relationOids.
841
 */
842
static Node *
843
fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset)
844
{
845 846
	fix_scan_expr_context context;

847
	context.glob = glob;
848
	context.rtoffset = rtoffset;
849

850
	if (rtoffset != 0 || glob->lastPHId != 0)
851 852 853 854 855 856
	{
		return fix_scan_expr_mutator(node, &context);
	}
	else
	{
		/*
857 858 859
		 * 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
860 861
		 * (since the only change, filling in any unset opfuncid fields, is
		 * harmless).  This saves just enough cycles to be noticeable on
862 863 864 865 866
		 * trivial queries.
		 */
		(void) fix_scan_expr_walker(node, &context);
		return node;
	}
867 868
}

869
static Node *
870
fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
871 872
{
	if (node == NULL)
873
		return NULL;
874 875
	if (IsA(node, Var))
	{
876
		Var		   *var = copyVar((Var *) node);
877 878

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

880 881
		/*
		 * We should not see any Vars marked INNER, but in a nestloop inner
B
Bruce Momjian 已提交
882
		 * scan there could be OUTER Vars.	Leave them alone.
883 884 885 886
		 */
		Assert(var->varno != INNER);
		if (var->varno > 0 && var->varno != OUTER)
			var->varno += context->rtoffset;
887
		if (var->varnoold > 0)
888 889
			var->varnoold += context->rtoffset;
		return (Node *) var;
890
	}
891 892 893 894 895 896 897 898 899
	if (IsA(node, CurrentOfExpr))
	{
		CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);

		Assert(cexpr->cvarno != INNER);
		Assert(cexpr->cvarno != OUTER);
		cexpr->cvarno += context->rtoffset;
		return (Node *) cexpr;
	}
900 901 902 903 904 905 906
	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);
	}
907
	fix_expr_common(context->glob, node);
908 909
	return expression_tree_mutator(node, fix_scan_expr_mutator,
								   (void *) context);
910 911
}

912 913 914 915 916
static bool
fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
{
	if (node == NULL)
		return false;
917
	Assert(!IsA(node, PlaceHolderVar));
918
	fix_expr_common(context->glob, node);
919 920 921 922
	return expression_tree_walker(node, fix_scan_expr_walker,
								  (void *) context);
}

923
/*
924
 * set_join_references
925
 *	  Modify the target list and quals of a join node to reference its
926 927
 *	  subplans, by setting the varnos to OUTER or INNER and setting attno
 *	  values to the result domain number of either the corresponding outer
928
 *	  or inner join tuple item.  Also perform opcode lookup for these
929
 *	  expressions. and add regclass OIDs to glob->relationOids.
930
 *
931 932
 * In the case of a nestloop with inner indexscan, we will also need to
 * apply the same transformation to any outer vars appearing in the
933
 * quals of the child indexscan.  set_inner_join_references does that.
934 935
 */
static void
936
set_join_references(PlannerGlobal *glob, Join *join, int rtoffset)
937
{
938 939
	Plan	   *outer_plan = join->plan.lefttree;
	Plan	   *inner_plan = join->plan.righttree;
940 941
	indexed_tlist *outer_itlist;
	indexed_tlist *inner_itlist;
942

943 944
	outer_itlist = build_tlist_index(outer_plan->targetlist);
	inner_itlist = build_tlist_index(inner_plan->targetlist);
945

946
	/* All join plans have tlist, qual, and joinqual */
947 948
	join->plan.targetlist = fix_join_expr(glob,
										  join->plan.targetlist,
949 950 951 952
										  outer_itlist,
										  inner_itlist,
										  (Index) 0,
										  rtoffset);
953 954
	join->plan.qual = fix_join_expr(glob,
									join->plan.qual,
955 956 957 958
									outer_itlist,
									inner_itlist,
									(Index) 0,
									rtoffset);
959 960
	join->joinqual = fix_join_expr(glob,
								   join->joinqual,
961 962 963 964
								   outer_itlist,
								   inner_itlist,
								   (Index) 0,
								   rtoffset);
965 966 967 968

	/* Now do join-type-specific stuff */
	if (IsA(join, NestLoop))
	{
969
		/* This processing is split out to handle possible recursion */
970
		set_inner_join_references(glob, inner_plan, outer_itlist);
971 972 973 974 975
	}
	else if (IsA(join, MergeJoin))
	{
		MergeJoin  *mj = (MergeJoin *) join;

976 977
		mj->mergeclauses = fix_join_expr(glob,
										 mj->mergeclauses,
978 979 980 981
										 outer_itlist,
										 inner_itlist,
										 (Index) 0,
										 rtoffset);
982 983 984 985 986
	}
	else if (IsA(join, HashJoin))
	{
		HashJoin   *hj = (HashJoin *) join;

987 988
		hj->hashclauses = fix_join_expr(glob,
										hj->hashclauses,
989 990 991 992
										outer_itlist,
										inner_itlist,
										(Index) 0,
										rtoffset);
993
	}
994 995 996

	pfree(outer_itlist);
	pfree(inner_itlist);
997 998
}

999 1000 1001 1002 1003
/*
 * set_inner_join_references
 *		Handle join references appearing in an inner indexscan's quals
 *
 * To handle bitmap-scan plan trees, we have to be able to recurse down
1004
 * to the bottom BitmapIndexScan nodes; likewise, appendrel indexscans
B
Bruce Momjian 已提交
1005
 * require recursing through Append nodes.	This is split out as a separate
1006
 * function so that it can recurse.
1007 1008 1009 1010
 *
 * Note we do *not* apply any rtoffset for non-join Vars; this is because
 * the quals will be processed again by fix_scan_expr when the set_plan_refs
 * recursion reaches the inner indexscan, and so we'd have done it twice.
1011 1012
 */
static void
1013
set_inner_join_references(PlannerGlobal *glob, Plan *inner_plan,
1014
						  indexed_tlist *outer_itlist)
1015 1016 1017 1018
{
	if (IsA(inner_plan, IndexScan))
	{
		/*
B
Bruce Momjian 已提交
1019 1020 1021 1022
		 * An index is being used to reduce the number of tuples scanned in
		 * the inner relation.	If there are join clauses being used with the
		 * index, we must update their outer-rel var nodes to refer to the
		 * outer side of the join.
1023 1024
		 */
		IndexScan  *innerscan = (IndexScan *) inner_plan;
1025
		List	   *indexqualorig = innerscan->indexqualorig;
1026

1027 1028
		/* No work needed if indexqual refers only to its own rel... */
		if (NumRelids((Node *) indexqualorig) > 1)
1029 1030 1031 1032
		{
			Index		innerrel = innerscan->scan.scanrelid;

			/* only refs to outer vars get changed in the inner qual */
1033 1034
			innerscan->indexqualorig = fix_join_expr(glob,
													 indexqualorig,
1035 1036 1037 1038
													 outer_itlist,
													 NULL,
													 innerrel,
													 0);
1039 1040
			innerscan->indexqual = fix_join_expr(glob,
												 innerscan->indexqual,
1041 1042 1043 1044
												 outer_itlist,
												 NULL,
												 innerrel,
												 0);
1045 1046

			/*
B
Bruce Momjian 已提交
1047 1048 1049
			 * We must fix the inner qpqual too, if it has join clauses (this
			 * could happen if special operators are involved: some indexquals
			 * may get rechecked as qpquals).
1050 1051
			 */
			if (NumRelids((Node *) inner_plan->qual) > 1)
1052 1053
				inner_plan->qual = fix_join_expr(glob,
												 inner_plan->qual,
1054 1055 1056 1057
												 outer_itlist,
												 NULL,
												 innerrel,
												 0);
1058 1059 1060 1061 1062 1063 1064 1065
		}
	}
	else if (IsA(inner_plan, BitmapIndexScan))
	{
		/*
		 * Same, but index is being used within a bitmap plan.
		 */
		BitmapIndexScan *innerscan = (BitmapIndexScan *) inner_plan;
1066
		List	   *indexqualorig = innerscan->indexqualorig;
1067

1068 1069
		/* No work needed if indexqual refers only to its own rel... */
		if (NumRelids((Node *) indexqualorig) > 1)
1070 1071 1072 1073
		{
			Index		innerrel = innerscan->scan.scanrelid;

			/* only refs to outer vars get changed in the inner qual */
1074 1075
			innerscan->indexqualorig = fix_join_expr(glob,
													 indexqualorig,
1076 1077 1078 1079
													 outer_itlist,
													 NULL,
													 innerrel,
													 0);
1080 1081
			innerscan->indexqual = fix_join_expr(glob,
												 innerscan->indexqual,
1082 1083 1084 1085
												 outer_itlist,
												 NULL,
												 innerrel,
												 0);
1086 1087 1088 1089 1090 1091 1092
			/* no need to fix inner qpqual */
			Assert(inner_plan->qual == NIL);
		}
	}
	else if (IsA(inner_plan, BitmapHeapScan))
	{
		/*
B
Bruce Momjian 已提交
1093 1094
		 * The inner side is a bitmap scan plan.  Fix the top node, and
		 * recurse to get the lower nodes.
1095
		 *
1096 1097
		 * Note: create_bitmap_scan_plan removes clauses from bitmapqualorig
		 * if they are duplicated in qpqual, so must test these independently.
1098 1099
		 */
		BitmapHeapScan *innerscan = (BitmapHeapScan *) inner_plan;
1100
		Index		innerrel = innerscan->scan.scanrelid;
1101 1102
		List	   *bitmapqualorig = innerscan->bitmapqualorig;

1103
		/* only refs to outer vars get changed in the inner qual */
1104
		if (NumRelids((Node *) bitmapqualorig) > 1)
1105 1106
			innerscan->bitmapqualorig = fix_join_expr(glob,
													  bitmapqualorig,
1107 1108 1109 1110
													  outer_itlist,
													  NULL,
													  innerrel,
													  0);
1111

1112
		/*
B
Bruce Momjian 已提交
1113 1114 1115
		 * We must fix the inner qpqual too, if it has join clauses (this
		 * could happen if special operators are involved: some indexquals may
		 * get rechecked as qpquals).
1116 1117
		 */
		if (NumRelids((Node *) inner_plan->qual) > 1)
1118 1119
			inner_plan->qual = fix_join_expr(glob,
											 inner_plan->qual,
1120 1121 1122 1123
											 outer_itlist,
											 NULL,
											 innerrel,
											 0);
1124 1125

		/* Now recurse */
1126
		set_inner_join_references(glob, inner_plan->lefttree, outer_itlist);
1127 1128 1129 1130
	}
	else if (IsA(inner_plan, BitmapAnd))
	{
		/* All we need do here is recurse */
B
Bruce Momjian 已提交
1131 1132
		BitmapAnd  *innerscan = (BitmapAnd *) inner_plan;
		ListCell   *l;
1133 1134 1135

		foreach(l, innerscan->bitmapplans)
		{
1136
			set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1137 1138 1139 1140 1141
		}
	}
	else if (IsA(inner_plan, BitmapOr))
	{
		/* All we need do here is recurse */
B
Bruce Momjian 已提交
1142 1143
		BitmapOr   *innerscan = (BitmapOr *) inner_plan;
		ListCell   *l;
1144 1145 1146

		foreach(l, innerscan->bitmapplans)
		{
1147
			set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1148 1149
		}
	}
1150 1151 1152 1153 1154
	else if (IsA(inner_plan, TidScan))
	{
		TidScan    *innerscan = (TidScan *) inner_plan;
		Index		innerrel = innerscan->scan.scanrelid;

1155 1156
		innerscan->tidquals = fix_join_expr(glob,
											innerscan->tidquals,
1157 1158 1159 1160 1161
											outer_itlist,
											NULL,
											innerrel,
											0);
	}
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
	else if (IsA(inner_plan, Append))
	{
		/*
		 * The inner side is an append plan.  Recurse to see if it contains
		 * indexscans that need to be fixed.
		 */
		Append	   *appendplan = (Append *) inner_plan;
		ListCell   *l;

		foreach(l, appendplan->appendplans)
		{
1173
			set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1174 1175
		}
	}
1176 1177 1178 1179 1180 1181
	else if (IsA(inner_plan, Result))
	{
		/* Recurse through a gating Result node (similar to Append case) */
		Result	   *result = (Result *) inner_plan;

		if (result->plan.lefttree)
1182
			set_inner_join_references(glob, result->plan.lefttree, outer_itlist);
1183
	}
1184 1185
}

1186
/*
1187
 * set_upper_references
1188 1189
 *	  Update the targetlist and quals of an upper-level plan node
 *	  to refer to the tuples returned by its lefttree subplan.
1190 1191
 *	  Also perform opcode lookup for these expressions, and
 *	  add regclass OIDs to glob->relationOids.
1192
 *
1193
 * This is used for single-input plan types like Agg, Group, Result.
1194 1195 1196 1197 1198
 *
 * 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,
1199 1200 1201 1202
 * 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.
1203 1204
 */
static void
1205
set_upper_references(PlannerGlobal *glob, Plan *plan, int rtoffset)
1206
{
1207
	Plan	   *subplan = plan->lefttree;
1208 1209
	indexed_tlist *subplan_itlist;
	List	   *output_targetlist;
1210
	ListCell   *l;
1211

1212
	subplan_itlist = build_tlist_index(subplan->targetlist);
1213 1214 1215 1216 1217 1218 1219

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

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
		/* 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,
													  OUTER);
			if (!newexpr)
				newexpr = fix_upper_expr(glob,
										 (Node *) tle->expr,
										 subplan_itlist,
										 rtoffset);
		}
		else
			newexpr = fix_upper_expr(glob,
									 (Node *) tle->expr,
									 subplan_itlist,
									 rtoffset);
1239 1240 1241
		tle = flatCopyTargetEntry(tle);
		tle->expr = (Expr *) newexpr;
		output_targetlist = lappend(output_targetlist, tle);
1242 1243
	}
	plan->targetlist = output_targetlist;
1244 1245

	plan->qual = (List *)
1246 1247
		fix_upper_expr(glob,
					   (Node *) plan->qual,
1248 1249
					   subplan_itlist,
					   rtoffset);
1250 1251

	pfree(subplan_itlist);
1252 1253
}

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
/*
 * set_dummy_tlist_references
 *	  Replace the targetlist of an upper-level plan node with a simple
 *	  list of OUTER references to its child.
 *
 * 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;

		newvar = makeVar(OUTER,
						 tle->resno,
						 exprType((Node *) oldvar),
						 exprTypmod((Node *) oldvar),
						 0);
		if (IsA(oldvar, Var))
		{
			newvar->varnoold = oldvar->varno + rtoffset;
			newvar->varoattno = oldvar->varattno;
		}
		else
		{
B
Bruce Momjian 已提交
1292
			newvar->varnoold = 0;		/* wasn't ever a plain Var */
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
			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 */
}


1306
/*
1307
 * build_tlist_index --- build an index data structure for a child tlist
1308
 *
1309 1310
 * 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 已提交
1311
 * in advance.	Matching a parent tlist to a child is still an O(N^2)
1312 1313 1314 1315 1316 1317
 * 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().
1318
 */
1319 1320
static indexed_tlist *
build_tlist_index(List *tlist)
1321
{
1322 1323
	indexed_tlist *itlist;
	tlist_vinfo *vinfo;
1324
	ListCell   *l;
1325

1326 1327 1328 1329 1330 1331
	/* 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;
1332
	itlist->has_ph_vars = false;
1333 1334 1335 1336
	itlist->has_non_vars = false;

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

1341 1342
		if (tle->expr && IsA(tle->expr, Var))
		{
B
Bruce Momjian 已提交
1343
			Var		   *var = (Var *) tle->expr;
1344 1345 1346 1347 1348 1349

			vinfo->varno = var->varno;
			vinfo->varattno = var->varattno;
			vinfo->resno = tle->resno;
			vinfo++;
		}
1350 1351
		else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
			itlist->has_ph_vars = true;
1352 1353 1354 1355 1356 1357 1358 1359 1360
		else
			itlist->has_non_vars = true;
	}

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

	return itlist;
}

1361 1362 1363 1364
/*
 * build_tlist_index_other_vars --- build a restricted tlist index
 *
 * This is like build_tlist_index, but we only index tlist entries that
1365 1366 1367
 * 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).
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
 */
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;
1382
	itlist->has_ph_vars = false;
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
	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++;
			}
		}
1403 1404
		else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
			itlist->has_ph_vars = true;
1405 1406 1407 1408 1409 1410 1411
	}

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

	return itlist;
}

1412 1413 1414 1415 1416
/*
 * 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).
1417
 * Also ensure that varnoold is incremented by rtoffset.
1418 1419 1420
 * If no match, return NULL.
 */
static Var *
1421 1422
search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
							 Index newvarno, int rtoffset)
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
{
	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 */
1436
			Var		   *newvar = copyVar(var);
1437 1438 1439

			newvar->varno = newvarno;
			newvar->varattno = vinfo->resno;
1440 1441
			if (newvar->varnoold > 0)
				newvar->varnoold += rtoffset;
1442 1443 1444
			return newvar;
		}
		vinfo++;
1445
	}
1446 1447 1448 1449 1450 1451 1452 1453 1454
	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.
 *
1455 1456
 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
 * itlist->has_non_vars
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
 */
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;

		newvar = makeVar(newvarno,
						 tle->resno,
						 exprType((Node *) tle->expr),
						 exprTypmod((Node *) tle->expr),
						 0);
B
Bruce Momjian 已提交
1475
		newvar->varnoold = 0;	/* wasn't ever a plain Var */
1476 1477 1478 1479
		newvar->varoattno = 0;
		return newvar;
	}
	return NULL;				/* no match */
1480 1481
}

1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
/*
 * 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;

			newvar = makeVar(newvarno,
							 tle->resno,
							 exprType((Node *) tle->expr),
							 exprTypmod((Node *) tle->expr),
							 0);
B
Bruce Momjian 已提交
1517
			newvar->varnoold = 0;		/* wasn't ever a plain Var */
1518 1519 1520 1521 1522 1523 1524
			newvar->varoattno = 0;
			return newvar;
		}
	}
	return NULL;				/* no match */
}

1525
/*
1526 1527
 * fix_join_expr
 *	   Create a new set of targetlist entries or join qual clauses by
1528 1529
 *	   changing the varno/varattno values of variables in the clauses
 *	   to reference target list values from the outer and inner join
1530 1531
 *	   relation target lists.  Also perform opcode lookup and add
 *	   regclass OIDs to glob->relationOids.
1532 1533 1534 1535 1536
 *
 * This is used in two different scenarios: a normal join clause, where
 * all the Vars in the clause *must* be replaced by OUTER or INNER references;
 * and an indexscan being used on the inner side of a nestloop join.
 * In the latter case we want to replace the outer-relation Vars by OUTER
1537 1538
 * references, while Vars of the inner relation should be adjusted by rtoffset.
 * (We also implement RETURNING clause fixup using this second scenario.)
1539 1540 1541
 *
 * For a normal join, acceptable_rel should be zero so that any failure to
 * match a Var will be reported as an error.  For the indexscan case,
1542 1543
 * pass inner_itlist = NULL and acceptable_rel = the (not-offseted-yet) ID
 * of the inner relation.
1544 1545
 *
 * 'clauses' is the targetlist or list of join clauses
1546 1547 1548
 * '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
1549 1550
 * 'acceptable_rel' is either zero or the rangetable index of a relation
 *		whose Vars may appear in the clause without provoking an error.
1551
 * 'rtoffset' is what to add to varno for Vars of acceptable_rel.
1552
 *
1553
 * Returns the new expression tree.  The original clause structure is
1554
 * not modified.
1555
 */
1556
static List *
1557
fix_join_expr(PlannerGlobal *glob,
1558
			  List *clauses,
1559 1560 1561 1562
			  indexed_tlist *outer_itlist,
			  indexed_tlist *inner_itlist,
			  Index acceptable_rel,
			  int rtoffset)
1563
{
1564
	fix_join_expr_context context;
B
Bruce Momjian 已提交
1565

1566
	context.glob = glob;
1567 1568
	context.outer_itlist = outer_itlist;
	context.inner_itlist = inner_itlist;
1569
	context.acceptable_rel = acceptable_rel;
1570 1571
	context.rtoffset = rtoffset;
	return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1572 1573
}

1574
static Node *
1575
fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1576
{
1577 1578
	Var		   *newvar;

1579 1580 1581 1582 1583
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
1584

1585
		/* First look for the var in the input tlists */
1586 1587
		newvar = search_indexed_tlist_for_var(var,
											  context->outer_itlist,
1588 1589
											  OUTER,
											  context->rtoffset);
1590
		if (newvar)
1591
			return (Node *) newvar;
1592
		if (context->inner_itlist)
1593
		{
1594 1595
			newvar = search_indexed_tlist_for_var(var,
												  context->inner_itlist,
1596 1597
												  INNER,
												  context->rtoffset);
1598 1599
			if (newvar)
				return (Node *) newvar;
1600
		}
1601

1602
		/* If it's for acceptable_rel, adjust and return it */
1603
		if (var->varno == context->acceptable_rel)
1604
		{
1605
			var = copyVar(var);
1606 1607 1608 1609
			var->varno += context->rtoffset;
			var->varnoold += context->rtoffset;
			return (Node *) var;
		}
1610 1611

		/* No referent found for Var */
1612
		elog(ERROR, "variable not found in subplan target lists");
1613
	}
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
	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,
													  OUTER);
			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,
													  INNER);
			if (newvar)
				return (Node *) newvar;
		}

		/* If not supplied by input plans, evaluate the contained expr */
		return fix_join_expr_mutator((Node *) phv->phexpr, context);
	}
1639
	/* Try matching more complex expressions too, if tlists have any */
1640
	if (context->outer_itlist->has_non_vars)
1641
	{
1642 1643 1644 1645
		newvar = search_indexed_tlist_for_non_var(node,
												  context->outer_itlist,
												  OUTER);
		if (newvar)
1646
			return (Node *) newvar;
1647 1648 1649 1650 1651 1652 1653
	}
	if (context->inner_itlist && context->inner_itlist->has_non_vars)
	{
		newvar = search_indexed_tlist_for_non_var(node,
												  context->inner_itlist,
												  INNER);
		if (newvar)
1654 1655
			return (Node *) newvar;
	}
1656
	fix_expr_common(context->glob, node);
1657
	return expression_tree_mutator(node,
1658
								   fix_join_expr_mutator,
1659
								   (void *) context);
1660 1661
}

1662
/*
1663 1664
 * fix_upper_expr
 *		Modifies an expression tree so that all Var nodes reference outputs
1665 1666
 *		of a subplan.  Also performs opcode lookup, and adds regclass OIDs to
 *		glob->relationOids.
1667 1668 1669
 *
 * This is used to fix up target and qual expressions of non-join upper-level
 * plan nodes.
1670
 *
1671 1672 1673
 * 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.
1674
 *
1675
 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1676 1677 1678 1679 1680 1681
 * 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)
1682
 * 'subplan_itlist': indexed target list for subplan
1683
 * 'rtoffset': how much to increment varnoold by
1684
 *
1685
 * The resulting tree is a copy of the original in which all Var nodes have
1686
 * varno = OUTER, varattno = resno of corresponding subplan target.
1687
 * The original tree is not modified.
1688
 */
1689
static Node *
1690
fix_upper_expr(PlannerGlobal *glob,
1691
			   Node *node,
1692 1693
			   indexed_tlist *subplan_itlist,
			   int rtoffset)
1694
{
1695
	fix_upper_expr_context context;
1696

1697
	context.glob = glob;
1698
	context.subplan_itlist = subplan_itlist;
1699 1700
	context.rtoffset = rtoffset;
	return fix_upper_expr_mutator(node, &context);
1701
}
B
Bruce Momjian 已提交
1702

1703
static Node *
1704
fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1705
{
1706 1707
	Var		   *newvar;

1708
	if (node == NULL)
1709
		return NULL;
1710 1711 1712
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
1713

1714 1715
		newvar = search_indexed_tlist_for_var(var,
											  context->subplan_itlist,
1716
											  OUTER,
1717
											  context->rtoffset);
1718
		if (!newvar)
1719
			elog(ERROR, "variable not found in subplan target list");
1720 1721
		return (Node *) newvar;
	}
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
	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,
													  OUTER);
			if (newvar)
				return (Node *) newvar;
		}
		/* If not supplied by input plan, evaluate the contained expr */
		return fix_upper_expr_mutator((Node *) phv->phexpr, context);
	}
1738
	/* Try matching more complex expressions too, if tlist has any */
1739
	if (context->subplan_itlist->has_non_vars)
1740
	{
1741 1742
		newvar = search_indexed_tlist_for_non_var(node,
												  context->subplan_itlist,
1743
												  OUTER);
1744
		if (newvar)
1745 1746
			return (Node *) newvar;
	}
1747
	fix_expr_common(context->glob, node);
1748
	return expression_tree_mutator(node,
1749
								   fix_upper_expr_mutator,
1750
								   (void *) context);
1751 1752
}

1753 1754 1755 1756 1757 1758
/*
 * 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
1759
 * entries in the top subplan's targetlist.  Vars referencing the result
1760
 * table should be left alone, however (the executor will evaluate them
B
Bruce Momjian 已提交
1761
 * using the actual heap tuple, after firing triggers if any).	In the
1762 1763 1764
 * adjusted RETURNING list, result-table Vars will still have their
 * original varno, but Vars for other rels will have varno OUTER.
 *
1765 1766
 * We also must perform opcode lookup and add regclass OIDs to
 * glob->relationOids.
1767 1768
 *
 * 'rlist': the RETURNING targetlist to be fixed
1769 1770
 * 'topplan': the top subplan node that will be just below the ModifyTable
 *		node (note it's not yet passed through set_plan_references)
1771 1772 1773 1774
 * 'resultRelation': RT index of the associated result relation
 *
 * Note: we assume that result relations will have rtoffset zero, that is,
 * they are not coming from a subplan.
1775 1776
 */
List *
1777
set_returning_clause_references(PlannerGlobal *glob,
1778
								List *rlist,
1779 1780 1781 1782 1783 1784
								Plan *topplan,
								Index resultRelation)
{
	indexed_tlist *itlist;

	/*
1785
	 * We can perform the desired Var fixup by abusing the fix_join_expr
B
Bruce Momjian 已提交
1786 1787
	 * machinery that normally handles inner indexscan fixup.  We search the
	 * top plan's targetlist for Vars of non-result relations, and use
B
Bruce Momjian 已提交
1788 1789
	 * fix_join_expr to convert RETURNING Vars into references to those tlist
	 * entries, while leaving result-rel Vars as-is.
1790 1791
	 *
	 * PlaceHolderVars will also be sought in the targetlist, but no
1792 1793 1794 1795 1796
	 * 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.
1797 1798 1799
	 */
	itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);

1800 1801
	rlist = fix_join_expr(glob,
						  rlist,
1802 1803 1804 1805
						  itlist,
						  NULL,
						  resultRelation,
						  0);
1806 1807 1808 1809 1810 1811

	pfree(itlist);

	return rlist;
}

1812
/*****************************************************************************
1813
 *					OPERATOR REGPROC LOOKUP
1814 1815
 *****************************************************************************/

1816
/*
1817 1818
 * fix_opfuncids
 *	  Calculate opfuncid field from opno for each OpExpr node in given tree.
1819
 *	  The given tree can be anything expression_tree_walker handles.
1820
 *
1821 1822 1823
 * 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.)
1824
 */
1825
void
1826
fix_opfuncids(Node *node)
1827
{
1828
	/* This tree walk requires no special setup, so away we go... */
1829
	fix_opfuncids_walker(node, NULL);
1830
}
B
Bruce Momjian 已提交
1831

1832
static bool
1833
fix_opfuncids_walker(Node *node, void *context)
1834 1835 1836
{
	if (node == NULL)
		return false;
1837 1838 1839
	if (IsA(node, OpExpr))
		set_opfuncid((OpExpr *) node);
	else if (IsA(node, DistinctExpr))
B
Bruce Momjian 已提交
1840
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
1841
	else if (IsA(node, NullIfExpr))
B
Bruce Momjian 已提交
1842
		set_opfuncid((OpExpr *) node);	/* rely on struct equivalence */
1843 1844
	else if (IsA(node, ScalarArrayOpExpr))
		set_sa_opfuncid((ScalarArrayOpExpr *) node);
1845
	return expression_tree_walker(node, fix_opfuncids_walker, context);
1846
}
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

/*
 * 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
1857
set_opfuncid(OpExpr *opexpr)
1858 1859 1860 1861 1862 1863 1864 1865 1866
{
	if (opexpr->opfuncid == InvalidOid)
		opexpr->opfuncid = get_opcode(opexpr->opno);
}

/*
 * set_sa_opfuncid
 *		As above, for ScalarArrayOpExpr nodes.
 */
1867
void
1868
set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1869 1870 1871 1872
{
	if (opexpr->opfuncid == InvalidOid)
		opexpr->opfuncid = get_opcode(opexpr->opno);
}
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

/*****************************************************************************
 *					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
record_plan_function_dependency(PlannerGlobal *glob, Oid funcid)
{
	/*
	 * 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.
1893 1894
	 * Note that the OID generator guarantees never to generate such an OID
	 * after startup, even at OID wraparound.
1895 1896 1897 1898 1899 1900
	 */
	if (funcid >= (Oid) FirstBootstrapObjectId)
	{
		HeapTuple	func_tuple;
		PlanInvalItem *inval_item;

1901
		func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
		if (!HeapTupleIsValid(func_tuple))
			elog(ERROR, "cache lookup failed for function %u", funcid);

		inval_item = makeNode(PlanInvalItem);

		/*
		 * It would work to use any syscache on pg_proc, but plancache.c
		 * expects us to use PROCOID.
		 */
		inval_item->cacheId = PROCOID;
		inval_item->tupleId = func_tuple->t_self;

		glob->invalItems = lappend(glob->invalItems, inval_item);

		ReleaseSysCache(func_tuple);
	}
}

/*
 * extract_query_dependencies
1922 1923 1924
 *		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.
1925 1926 1927 1928 1929
 *
 * This is needed by plancache.c to handle invalidation of cached unplanned
 * queries.
 */
void
1930
extract_query_dependencies(Node *query,
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
						   List **relationOids,
						   List **invalItems)
{
	PlannerGlobal glob;

	/* Make up a dummy PlannerGlobal so we can use this module's machinery */
	MemSet(&glob, 0, sizeof(glob));
	glob.type = T_PlannerGlobal;
	glob.relationOids = NIL;
	glob.invalItems = NIL;

1942
	(void) extract_query_dependencies_walker(query, &glob);
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952

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

static bool
extract_query_dependencies_walker(Node *node, PlannerGlobal *context)
{
	if (node == NULL)
		return false;
1953
	Assert(!IsA(node, PlaceHolderVar));
1954 1955 1956 1957 1958 1959 1960
	/* Extract function dependencies and check for regclass Consts */
	fix_expr_common(context, node);
	if (IsA(node, Query))
	{
		Query	   *query = (Query *) node;
		ListCell   *lc;

1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
		if (query->commandType == CMD_UTILITY)
		{
			/* Ignore utility statements, except EXPLAIN */
			if (IsA(query->utilityStmt, ExplainStmt))
			{
				query = (Query *) ((ExplainStmt *) query->utilityStmt)->query;
				Assert(IsA(query, Query));
				Assert(query->commandType != CMD_UTILITY);
			}
			else
				return false;
		}

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
		/* Collect relation OIDs in this Query's rtable */
		foreach(lc, query->rtable)
		{
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);

			if (rte->rtekind == RTE_RELATION)
				context->relationOids = lappend_oid(context->relationOids,
													rte->relid);
		}

		/* 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);
}