execMain.c 49.8 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * execMain.c
4
 *	  top level executor interface routines
5 6
 *
 * INTERFACE ROUTINES
7 8 9
 *	ExecutorStart()
 *	ExecutorRun()
 *	ExecutorEnd()
10
 *
11 12 13 14
 *	The old ExecutorMain() has been replaced by ExecutorStart(),
 *	ExecutorRun() and ExecutorEnd()
 *
 *	These three procedures are the external interfaces to the executor.
15
 *	In each case, the query descriptor is required as an argument.
16
 *
17
 *	ExecutorStart() must be called at the beginning of execution of any
18 19 20
 *	query plan and ExecutorEnd() should always be called at the end of
 *	execution of a plan.
 *
21
 *	ExecutorRun accepts direction and count arguments that specify whether
22
 *	the plan is to be executed forwards, backwards, and for how many tuples.
23
 *
B
Bruce Momjian 已提交
24
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
25
 * Portions Copyright (c) 1994, Regents of the University of California
26 27 28
 *
 *
 * IDENTIFICATION
29
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.194 2002/12/15 21:01:34 tgl Exp $
30 31 32
 *
 *-------------------------------------------------------------------------
 */
33 34
#include "postgres.h"

35 36
#include "access/heapam.h"
#include "catalog/heap.h"
37
#include "catalog/namespace.h"
38
#include "commands/tablecmds.h"
39
#include "commands/trigger.h"
B
Bruce Momjian 已提交
40 41 42 43 44 45
#include "executor/execdebug.h"
#include "executor/execdefs.h"
#include "miscadmin.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "utils/acl.h"
46
#include "utils/lsyscache.h"
47

48 49

/* decls for local routines only used within this module */
50
static void InitPlan(QueryDesc *queryDesc);
51
static void initResultRelInfo(ResultRelInfo *resultRelInfo,
B
Bruce Momjian 已提交
52 53 54
				  Index resultRelationIndex,
				  List *rangeTable,
				  CmdType operation);
55
static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
B
Bruce Momjian 已提交
56 57 58 59
			CmdType operation,
			long numberTuples,
			ScanDirection direction,
			DestReceiver *destfunc);
60
static void ExecSelect(TupleTableSlot *slot,
B
Bruce Momjian 已提交
61 62
		   DestReceiver *destfunc,
		   EState *estate);
63
static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
64
		   EState *estate);
65
static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
66
		   EState *estate);
67
static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
68
		   EState *estate);
69
static TupleTableSlot *EvalPlanQualNext(EState *estate);
70
static void EndEvalPlanQual(EState *estate);
71
static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
72

73 74
/* end of local decls */

75

76
/* ----------------------------------------------------------------
77 78 79 80 81
 *		ExecutorStart
 *
 *		This routine must be called at the beginning of any execution of any
 *		query plan
 *
82 83 84 85
 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
 * clear why we bother to separate the two functions, but...).  The tupDesc
 * field of the QueryDesc is filled in to describe the tuples that will be
 * returned, and the internal fields (estate and planstate) are set up.
86
 *
87 88
 * NB: the CurrentMemoryContext when this is called will become the parent
 * of the per-query context used for this Executor invocation.
89 90
 * ----------------------------------------------------------------
 */
91 92
void
ExecutorStart(QueryDesc *queryDesc)
93
{
94
	EState	   *estate;
95
	MemoryContext oldcontext;
96

97
	/* sanity checks: queryDesc must not be started already */
98
	Assert(queryDesc != NULL);
99 100 101
	Assert(queryDesc->estate == NULL);

	/*
102
	 * Build EState, switch into per-query memory context for startup.
103 104 105 106
	 */
	estate = CreateExecutorState();
	queryDesc->estate = estate;

107 108 109 110 111
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	/*
	 * Fill in parameters, if any, from queryDesc
	 */
112
	estate->es_param_list_info = queryDesc->params;
113

V
Vadim B. Mikheev 已提交
114
	if (queryDesc->plantree->nParamExec > 0)
115
		estate->es_param_exec_vals = (ParamExecData *)
116
			palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
117

118 119
	estate->es_instrument = queryDesc->doInstrument;

120
	/*
121 122
	 * Make our own private copy of the current query snapshot data.
	 *
B
Bruce Momjian 已提交
123 124 125
	 * This "freezes" our idea of which tuples are good and which are not for
	 * the life of this query, even if it outlives the current command and
	 * current snapshot.
126
	 */
127
	estate->es_snapshot = CopyQuerySnapshot();
128

129
	/*
130
	 * Initialize the plan state tree
131
	 */
132
	InitPlan(queryDesc);
133 134

	MemoryContextSwitchTo(oldcontext);
135 136 137
}

/* ----------------------------------------------------------------
138 139 140 141 142 143 144
 *		ExecutorRun
 *
 *		This is the main routine of the executor module. It accepts
 *		the query descriptor from the traffic cop and executes the
 *		query plan.
 *
 *		ExecutorStart must have been called already.
145
 *
146 147 148
 *		If direction is NoMovementScanDirection then nothing is done
 *		except to start up/shut down the destination.  Otherwise,
 *		we retrieve up to 'count' tuples in the specified direction.
149
 *
150 151
 *		Note: count = 0 is interpreted as no portal limit, e.g. run to
 *		completion.
152
 *
153 154
 * ----------------------------------------------------------------
 */
155
TupleTableSlot *
156
ExecutorRun(QueryDesc *queryDesc,
157
			ScanDirection direction, long count)
158
{
159
	EState	   *estate;
160
	CmdType		operation;
B
Bruce Momjian 已提交
161 162
	CommandDest dest;
	DestReceiver *destfunc;
163
	TupleTableSlot *result;
164 165 166 167 168 169 170 171
	MemoryContext oldcontext;

	/* sanity checks */
	Assert(queryDesc != NULL);

	estate = queryDesc->estate;

	Assert(estate != NULL);
172

B
Bruce Momjian 已提交
173
	/*
174
	 * Switch into per-query memory context
175
	 */
176
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
177

B
Bruce Momjian 已提交
178
	/*
B
Bruce Momjian 已提交
179 180
	 * extract information from the query descriptor and the query
	 * feature.
181
	 */
182 183 184
	operation = queryDesc->operation;
	dest = queryDesc->dest;

B
Bruce Momjian 已提交
185
	/*
186
	 * startup tuple receiver
187
	 */
188 189
	estate->es_processed = 0;
	estate->es_lastoid = InvalidOid;
190

191 192 193
	destfunc = DestToFunction(dest);
	(*destfunc->setup) (destfunc, (int) operation,
						queryDesc->portalName, queryDesc->tupDesc);
194

195 196 197 198 199 200 201
	/*
	 * run plan
	 */
	if (direction == NoMovementScanDirection)
		result = NULL;
	else
		result = ExecutePlan(estate,
202
							 queryDesc->planstate,
203 204 205 206
							 operation,
							 count,
							 direction,
							 destfunc);
207

208 209 210
	/*
	 * shutdown receiver
	 */
211 212
	(*destfunc->cleanup) (destfunc);

213 214
	MemoryContextSwitchTo(oldcontext);

215
	return result;
216 217 218
}

/* ----------------------------------------------------------------
219 220
 *		ExecutorEnd
 *
221
 *		This routine must be called at the end of execution of any
222
 *		query plan
223 224 225
 * ----------------------------------------------------------------
 */
void
226
ExecutorEnd(QueryDesc *queryDesc)
227
{
228
	EState	   *estate;
229
	MemoryContext oldcontext;
230

231 232
	/* sanity checks */
	Assert(queryDesc != NULL);
233

234 235
	estate = queryDesc->estate;

236
	Assert(estate != NULL);
237

238
	/*
239
	 * Switch into per-query memory context to run ExecEndPlan
240
	 */
241 242 243
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	ExecEndPlan(queryDesc->planstate, estate);
244

245
	/*
246
	 * Must switch out of context before destroying it
247
	 */
248
	MemoryContextSwitchTo(oldcontext);
249

250
	/*
251 252
	 * Release EState and per-query memory context.  This should release
	 * everything the executor has allocated.
253
	 */
254 255 256 257 258 259
	FreeExecutorState(estate);

	/* Reset queryDesc fields that no longer point to anything */
	queryDesc->tupDesc = NULL;
	queryDesc->estate = NULL;
	queryDesc->planstate = NULL;
260
}
261

262

263 264 265 266
/*
 * ExecCheckRTPerms
 *		Check access permissions for all relations listed in a range table.
 */
267
void
268
ExecCheckRTPerms(List *rangeTable, CmdType operation)
269 270 271 272
{
	List	   *lp;

	foreach(lp, rangeTable)
273
	{
274 275
		RangeTblEntry *rte = lfirst(lp);

276
		ExecCheckRTEPerms(rte, operation);
277 278 279 280 281 282 283 284
	}
}

/*
 * ExecCheckRTEPerms
 *		Check access permissions for a single RTE.
 */
static void
285
ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
286
{
287
	Oid			relOid;
288
	AclId		userid;
289
	AclResult	aclcheck_result;
290

B
Bruce Momjian 已提交
291
	/*
292 293 294 295 296 297 298 299 300 301 302 303
	 * If it's a subquery, recursively examine its rangetable.
	 */
	if (rte->rtekind == RTE_SUBQUERY)
	{
		ExecCheckRTPerms(rte->subquery->rtable, operation);
		return;
	}

	/*
	 * Otherwise, only plain-relation RTEs need to be checked here.
	 * Function RTEs are checked by init_fcache when the function is prepared
	 * for execution. Join and special RTEs need no checks.
B
Bruce Momjian 已提交
304
	 */
305
	if (rte->rtekind != RTE_RELATION)
306 307
		return;

308
	relOid = rte->relid;
309 310

	/*
B
Bruce Momjian 已提交
311 312
	 * userid to check as: current user unless we have a setuid
	 * indication.
313
	 *
B
Bruce Momjian 已提交
314 315
	 * Note: GetUserId() is presently fast enough that there's no harm in
	 * calling it separately for each RTE.	If that stops being true, we
316
	 * could call it once in ExecCheckRTPerms and pass the userid down
B
Bruce Momjian 已提交
317
	 * from there.	But for now, no need for the extra clutter.
318
	 */
319
	userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
320

321
#define CHECK(MODE)		pg_class_aclcheck(relOid, userid, MODE)
322

323
	if (rte->checkForRead)
324
	{
325
		aclcheck_result = CHECK(ACL_SELECT);
326
		if (aclcheck_result != ACLCHECK_OK)
327
			aclcheck_error(aclcheck_result, get_rel_name(relOid));
328 329 330 331 332 333 334 335 336
	}

	if (rte->checkForWrite)
	{
		/*
		 * Note: write access in a SELECT context means SELECT FOR UPDATE.
		 * Right now we don't distinguish that from true update as far as
		 * permissions checks are concerned.
		 */
337 338 339
		switch (operation)
		{
			case CMD_INSERT:
340
				aclcheck_result = CHECK(ACL_INSERT);
341
				break;
342
			case CMD_SELECT:
343
			case CMD_UPDATE:
344 345 346 347
				aclcheck_result = CHECK(ACL_UPDATE);
				break;
			case CMD_DELETE:
				aclcheck_result = CHECK(ACL_DELETE);
348 349 350 351
				break;
			default:
				elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
					 operation);
352
				aclcheck_result = ACLCHECK_OK;	/* keep compiler quiet */
353 354
				break;
		}
355
		if (aclcheck_result != ACLCHECK_OK)
356
			aclcheck_error(aclcheck_result, get_rel_name(relOid));
357
	}
358 359
}

360

361 362 363 364 365 366 367
/* ===============================================================
 * ===============================================================
						 static routines follow
 * ===============================================================
 * ===============================================================
 */

368 369 370
typedef struct execRowMark
{
	Relation	relation;
371
	Index		rti;
372
	char		resname[32];
373
} execRowMark;
374

375 376
typedef struct evalPlanQual
{
377 378
	Plan	   *plan;			/* XXX temporary */
	PlanState  *planstate;
B
Bruce Momjian 已提交
379 380 381
	Index		rti;
	EState		estate;
	struct evalPlanQual *free;
382
} evalPlanQual;
383

384
/* ----------------------------------------------------------------
385 386 387 388
 *		InitPlan
 *
 *		Initializes the query plan: open files, allocate storage
 *		and start up the rule manager
389 390
 * ----------------------------------------------------------------
 */
391 392
static void
InitPlan(QueryDesc *queryDesc)
393
{
394 395 396 397 398
	CmdType		operation = queryDesc->operation;
	Query *parseTree = queryDesc->parsetree;
	Plan *plan = queryDesc->plantree;
	EState *estate = queryDesc->estate;
	PlanState  *planstate;
B
Bruce Momjian 已提交
399 400 401
	List	   *rangeTable;
	Relation	intoRelationDesc;
	TupleDesc	tupType;
402

403
	/*
404 405 406
	 * Do permissions checks.  It's sufficient to examine the query's
	 * top rangetable here --- subplan RTEs will be checked during
	 * ExecInitSubPlan().
407
	 */
408
	ExecCheckRTPerms(parseTree->rtable, operation);
409

B
Bruce Momjian 已提交
410
	/*
B
Bruce Momjian 已提交
411
	 * get information from query descriptor
412
	 */
413
	rangeTable = parseTree->rtable;
414

B
Bruce Momjian 已提交
415
	/*
B
Bruce Momjian 已提交
416
	 * initialize the node's execution state
417
	 */
418 419
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
420
	/*
421
	 * if there is a result relation, initialize result relation stuff
422
	 */
423
	if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
424
	{
425 426 427
		List	   *resultRelations = parseTree->resultRelations;
		int			numResultRelations;
		ResultRelInfo *resultRelInfos;
B
Bruce Momjian 已提交
428

429 430 431 432 433 434 435
		if (resultRelations != NIL)
		{
			/*
			 * Multiple result relations (due to inheritance)
			 * parseTree->resultRelations identifies them all
			 */
			ResultRelInfo *resultRelInfo;
436

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
			numResultRelations = length(resultRelations);
			resultRelInfos = (ResultRelInfo *)
				palloc(numResultRelations * sizeof(ResultRelInfo));
			resultRelInfo = resultRelInfos;
			while (resultRelations != NIL)
			{
				initResultRelInfo(resultRelInfo,
								  lfirsti(resultRelations),
								  rangeTable,
								  operation);
				resultRelInfo++;
				resultRelations = lnext(resultRelations);
			}
		}
		else
		{
			/*
B
Bruce Momjian 已提交
454 455
			 * Single result relation identified by
			 * parseTree->resultRelation
456 457 458 459 460 461 462 463
			 */
			numResultRelations = 1;
			resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
			initResultRelInfo(resultRelInfos,
							  parseTree->resultRelation,
							  rangeTable,
							  operation);
		}
464

465 466 467 468
		estate->es_result_relations = resultRelInfos;
		estate->es_num_result_relations = numResultRelations;
		/* Initialize to first or only result rel */
		estate->es_result_relation_info = resultRelInfos;
469
	}
470 471
	else
	{
B
Bruce Momjian 已提交
472
		/*
B
Bruce Momjian 已提交
473
		 * if no result relation, then set state appropriately
474
		 */
475 476
		estate->es_result_relations = NULL;
		estate->es_num_result_relations = 0;
477 478 479
		estate->es_result_relation_info = NULL;
	}

480 481 482
	/*
	 * Have to lock relations selected for update
	 */
483 484
	estate->es_rowMark = NIL;
	if (parseTree->rowMarks != NIL)
485
	{
B
Bruce Momjian 已提交
486
		List	   *l;
487

488
		foreach(l, parseTree->rowMarks)
489
		{
490 491
			Index		rti = lfirsti(l);
			Oid			relid = getrelid(rti, rangeTable);
492 493 494 495
			Relation	relation;
			execRowMark *erm;

			relation = heap_open(relid, RowShareLock);
B
Bruce Momjian 已提交
496
			erm = (execRowMark *) palloc(sizeof(execRowMark));
497
			erm->relation = relation;
498
			erm->rti = rti;
499
			snprintf(erm->resname, 32, "ctid%u", rti);
500 501 502
			estate->es_rowMark = lappend(estate->es_rowMark, erm);
		}
	}
503

B
Bruce Momjian 已提交
504
	/*
505
	 * initialize the executor "tuple" table.  We need slots for all the
506 507 508
	 * plan nodes, plus possibly output slots for the junkfilter(s). At
	 * this point we aren't sure if we need junkfilters, so just add slots
	 * for them unconditionally.
509 510
	 */
	{
511
		int			nSlots = ExecCountSlotsNode(plan);
512

513 514 515 516 517
		if (parseTree->resultRelations != NIL)
			nSlots += length(parseTree->resultRelations);
		else
			nSlots += 1;
		estate->es_tupleTable = ExecCreateTupleTable(nSlots);
518
	}
519

520 521 522 523 524 525 526
	/* mark EvalPlanQual not active */
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_evTupleNull = NULL;
	estate->es_useEvalPlan = false;

B
Bruce Momjian 已提交
527
	/*
B
Bruce Momjian 已提交
528 529
	 * initialize the private state information for all the nodes in the
	 * query tree.	This opens files, allocates storage and leaves us
530
	 * ready to start processing tuples.
531
	 */
532
	planstate = ExecInitNode(plan, estate);
533

B
Bruce Momjian 已提交
534
	/*
535
	 * Get the tuple descriptor describing the type of tuples to return.
B
Bruce Momjian 已提交
536
	 * (this is especially important if we are creating a relation with
537
	 * "SELECT INTO")
538
	 */
539
	tupType = ExecGetTupType(planstate);
540

B
Bruce Momjian 已提交
541
	/*
B
Bruce Momjian 已提交
542 543 544 545
	 * Initialize the junk filter if needed. SELECT and INSERT queries
	 * need a filter if there are any junk attrs in the tlist.	UPDATE and
	 * DELETE always need one, since there's always a junk 'ctid'
	 * attribute present --- no need to look first.
546 547
	 */
	{
548 549 550
		bool		junk_filter_needed = false;
		List	   *tlist;

551
		switch (operation)
552
		{
553 554
			case CMD_SELECT:
			case CMD_INSERT:
555
				foreach(tlist, plan->targetlist)
556
				{
557 558 559 560 561 562 563
					TargetEntry *tle = (TargetEntry *) lfirst(tlist);

					if (tle->resdom->resjunk)
					{
						junk_filter_needed = true;
						break;
					}
564
				}
565 566 567 568 569 570 571
				break;
			case CMD_UPDATE:
			case CMD_DELETE:
				junk_filter_needed = true;
				break;
			default:
				break;
572 573
		}

574
		if (junk_filter_needed)
575
		{
576
			/*
B
Bruce Momjian 已提交
577 578 579 580
			 * If there are multiple result relations, each one needs its
			 * own junk filter.  Note this is only possible for
			 * UPDATE/DELETE, so we can't be fooled by some needing a
			 * filter and some not.
581 582 583
			 */
			if (parseTree->resultRelations != NIL)
			{
584 585
				PlanState **appendplans;
				int			as_nplans;
586
				ResultRelInfo *resultRelInfo;
587
				int			i;
588 589 590 591

				/* Top plan had better be an Append here. */
				Assert(IsA(plan, Append));
				Assert(((Append *) plan)->isTarget);
592 593 594 595
				Assert(IsA(planstate, AppendState));
				appendplans = ((AppendState *) planstate)->appendplans;
				as_nplans = ((AppendState *) planstate)->as_nplans;
				Assert(as_nplans == estate->es_num_result_relations);
596
				resultRelInfo = estate->es_result_relations;
597
				for (i = 0; i < as_nplans; i++)
598
				{
599
					PlanState  *subplan = appendplans[i];
600 601
					JunkFilter *j;

602
					j = ExecInitJunkFilter(subplan->plan->targetlist,
603
										   ExecGetTupType(subplan),
604
							  ExecAllocTableSlot(estate->es_tupleTable));
605 606 607
					resultRelInfo->ri_junkFilter = j;
					resultRelInfo++;
				}
B
Bruce Momjian 已提交
608

609 610 611 612 613 614 615 616 617 618
				/*
				 * Set active junkfilter too; at this point ExecInitAppend
				 * has already selected an active result relation...
				 */
				estate->es_junkFilter =
					estate->es_result_relation_info->ri_junkFilter;
			}
			else
			{
				/* Normal case with just one JunkFilter */
619
				JunkFilter *j;
620

621
				j = ExecInitJunkFilter(planstate->plan->targetlist,
622
									   tupType,
623
							  ExecAllocTableSlot(estate->es_tupleTable));
624 625 626
				estate->es_junkFilter = j;
				if (estate->es_result_relation_info)
					estate->es_result_relation_info->ri_junkFilter = j;
627

628 629 630 631
				/* For SELECT, want to return the cleaned tuple type */
				if (operation == CMD_SELECT)
					tupType = j->jf_cleanTupType;
			}
632 633 634 635
		}
		else
			estate->es_junkFilter = NULL;
	}
636

B
Bruce Momjian 已提交
637
	/*
B
Bruce Momjian 已提交
638
	 * initialize the "into" relation
639 640 641 642 643 644 645 646
	 */
	intoRelationDesc = (Relation) NULL;

	if (operation == CMD_SELECT)
	{
		if (!parseTree->isPortal)
		{
			/*
647
			 * a select into table --- need to create the "into" table
648 649 650
			 */
			if (parseTree->into != NULL)
			{
651 652
				char	   *intoName;
				Oid			namespaceId;
653
				AclResult	aclresult;
654 655 656
				Oid			intoRelationId;
				TupleDesc	tupdesc;

B
Bruce Momjian 已提交
657
				/*
658
				 * find namespace to create in, check permissions
659
				 */
660
				intoName = parseTree->into->relname;
661
				namespaceId = RangeVarGetCreationNamespace(parseTree->into);
662

663 664 665 666 667
				aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
												  ACL_CREATE);
				if (aclresult != ACLCHECK_OK)
					aclcheck_error(aclresult,
								   get_namespace_name(namespaceId));
668

669 670 671 672 673
				/*
				 * have to copy tupType to get rid of constraints
				 */
				tupdesc = CreateTupleDescCopy(tupType);

674 675 676 677 678 679 680 681
				/*
				 * Formerly we forced the output table to have OIDs, but
				 * as of 7.3 it will not have OIDs, because it's too late
				 * here to change the tupdescs of the already-initialized
				 * plan tree.  (Perhaps we could recurse and change them
				 * all, but it's not really worth the trouble IMHO...)
				 */

682 683
				intoRelationId =
					heap_create_with_catalog(intoName,
684
											 namespaceId,
685
											 tupdesc,
686
											 RELKIND_RELATION,
687
											 false,
688
											 ONCOMMIT_NOOP,
689
											 allowSystemTableMods);
690

691 692
				FreeTupleDesc(tupdesc);

B
Bruce Momjian 已提交
693
				/*
694 695
				 * Advance command counter so that the newly-created
				 * relation's catalog tuples will be visible to heap_open.
696
				 */
697
				CommandCounterIncrement();
698

699
				/*
B
Bruce Momjian 已提交
700 701 702 703
				 * If necessary, create a TOAST table for the into
				 * relation. Note that AlterTableCreateToastTable ends
				 * with CommandCounterIncrement(), so that the TOAST table
				 * will be visible for insertion.
704
				 */
705
				AlterTableCreateToastTable(intoRelationId, true);
706

707 708
				intoRelationDesc = heap_open(intoRelationId,
											 AccessExclusiveLock);
709 710 711 712 713 714
			}
		}
	}

	estate->es_into_relation_descriptor = intoRelationDesc;

715 716
	queryDesc->tupDesc = tupType;
	queryDesc->planstate = planstate;
717 718
}

719 720 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
/*
 * Initialize ResultRelInfo data for one result relation
 */
static void
initResultRelInfo(ResultRelInfo *resultRelInfo,
				  Index resultRelationIndex,
				  List *rangeTable,
				  CmdType operation)
{
	Oid			resultRelationOid;
	Relation	resultRelationDesc;

	resultRelationOid = getrelid(resultRelationIndex, rangeTable);
	resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);

	switch (resultRelationDesc->rd_rel->relkind)
	{
		case RELKIND_SEQUENCE:
			elog(ERROR, "You can't change sequence relation %s",
				 RelationGetRelationName(resultRelationDesc));
			break;
		case RELKIND_TOASTVALUE:
			elog(ERROR, "You can't change toast relation %s",
				 RelationGetRelationName(resultRelationDesc));
			break;
		case RELKIND_VIEW:
			elog(ERROR, "You can't change view relation %s",
				 RelationGetRelationName(resultRelationDesc));
			break;
	}

	MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
	resultRelInfo->type = T_ResultRelInfo;
	resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
	resultRelInfo->ri_RelationDesc = resultRelationDesc;
	resultRelInfo->ri_NumIndices = 0;
	resultRelInfo->ri_IndexRelationDescs = NULL;
	resultRelInfo->ri_IndexRelationInfo = NULL;
757 758
	/* make a copy so as not to depend on relcache info not changing... */
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
759
	resultRelInfo->ri_TrigFunctions = NULL;
760 761 762 763 764 765
	resultRelInfo->ri_ConstraintExprs = NULL;
	resultRelInfo->ri_junkFilter = NULL;

	/*
	 * If there are indices on the result relation, open them and save
	 * descriptors in the result relation info, so that we can add new
B
Bruce Momjian 已提交
766 767
	 * index entries for the tuples we add/update.	We need not do this
	 * for a DELETE, however, since deletion doesn't affect indexes.
768 769 770 771 772 773
	 */
	if (resultRelationDesc->rd_rel->relhasindex &&
		operation != CMD_DELETE)
		ExecOpenIndices(resultRelInfo);
}

774
/* ----------------------------------------------------------------
775
 *		ExecEndPlan
776
 *
777
 *		Cleans up the query plan -- closes files and frees up storage
778 779 780 781 782 783
 *
 * NOTE: we are no longer very worried about freeing storage per se
 * in this code; FreeExecutorState should be guaranteed to release all
 * memory that needs to be released.  What we are worried about doing
 * is closing relations and dropping buffer pins.  Thus, for example,
 * tuple tables must be cleared or dropped to ensure pins are released.
784 785
 * ----------------------------------------------------------------
 */
786 787
void
ExecEndPlan(PlanState *planstate, EState *estate)
788
{
789 790
	ResultRelInfo *resultRelInfo;
	int			i;
791
	List	   *l;
792

793 794 795 796 797 798
	/*
	 * shut down any PlanQual processing we were doing
	 */
	if (estate->es_evalPlanQual != NULL)
		EndEvalPlanQual(estate);

B
Bruce Momjian 已提交
799
	/*
800
	 * shut down the node-type-specific query processing
801
	 */
802
	ExecEndNode(planstate);
803

B
Bruce Momjian 已提交
804
	/*
B
Bruce Momjian 已提交
805
	 * destroy the executor "tuple" table.
806
	 */
807 808
	ExecDropTupleTable(estate->es_tupleTable, true);
	estate->es_tupleTable = NULL;
809

B
Bruce Momjian 已提交
810
	/*
B
Bruce Momjian 已提交
811
	 * close the result relation(s) if any, but hold locks until xact
812
	 * commit.
813
	 */
814 815
	resultRelInfo = estate->es_result_relations;
	for (i = estate->es_num_result_relations; i > 0; i--)
816
	{
817 818 819 820
		/* Close indices and then the relation itself */
		ExecCloseIndices(resultRelInfo);
		heap_close(resultRelInfo->ri_RelationDesc, NoLock);
		resultRelInfo++;
821 822
	}

B
Bruce Momjian 已提交
823
	/*
824
	 * close the "into" relation if necessary, again keeping lock
825
	 */
826 827
	if (estate->es_into_relation_descriptor != NULL)
		heap_close(estate->es_into_relation_descriptor, NoLock);
828 829 830 831 832 833 834 835 836 837

	/*
	 * close any relations selected FOR UPDATE, again keeping locks
	 */
	foreach(l, estate->es_rowMark)
	{
		execRowMark *erm = lfirst(l);

		heap_close(erm->relation, NoLock);
	}
838 839 840
}

/* ----------------------------------------------------------------
841 842
 *		ExecutePlan
 *
843
 *		processes the query plan to retrieve 'numberTuples' tuples in the
844
 *		direction specified.
845
 *		Retrieves all tuples if numberTuples is 0
846
 *
847
 *		result is either a slot containing the last tuple in the case
848
 *		of a SELECT or NULL otherwise.
849
 *
850 851
 * Note: the ctid attribute is a 'junk' attribute that is removed before the
 * user can see it
852 853 854
 * ----------------------------------------------------------------
 */
static TupleTableSlot *
855
ExecutePlan(EState *estate,
856
			PlanState *planstate,
857
			CmdType operation,
858
			long numberTuples,
859
			ScanDirection direction,
860
			DestReceiver *destfunc)
861
{
862 863 864 865 866 867
	JunkFilter			*junkfilter;
	TupleTableSlot		*slot;
	ItemPointer			 tupleid = NULL;
	ItemPointerData		 tuple_ctid;
	long				 current_tuple_count;
	TupleTableSlot		*result;
868

B
Bruce Momjian 已提交
869
	/*
B
Bruce Momjian 已提交
870
	 * initialize local variables
871
	 */
872 873 874 875
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
876 877
	/*
	 * Set the direction.
878
	 */
879 880
	estate->es_direction = direction;

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
	/*
	 * Process BEFORE EACH STATEMENT triggers
	 */
	switch (operation)
	{
		case CMD_UPDATE:
			ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_DELETE:
			ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_INSERT:
			ExecBSInsertTriggers(estate, estate->es_result_relation_info);
			break;
		default:
			/* do nothing */
897
			break;
898 899
	}

B
Bruce Momjian 已提交
900
	/*
B
Bruce Momjian 已提交
901
	 * Loop until we've processed the proper number of tuples from the
902
	 * plan.
903 904 905 906
	 */

	for (;;)
	{
907 908
		/* Reset the per-output-tuple exprcontext */
		ResetPerTupleExprContext(estate);
B
Bruce Momjian 已提交
909

B
Bruce Momjian 已提交
910
		/*
B
Bruce Momjian 已提交
911
		 * Execute the plan and obtain a tuple
912
		 */
B
Bruce Momjian 已提交
913
lnext:	;
914 915 916 917
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
918
				slot = ExecProcNode(planstate);
919 920
		}
		else
921
			slot = ExecProcNode(planstate);
922

B
Bruce Momjian 已提交
923
		/*
B
Bruce Momjian 已提交
924 925
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
926 927 928 929 930
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
931 932
		}

B
Bruce Momjian 已提交
933
		/*
B
Bruce Momjian 已提交
934 935
		 * if we have a junk filter, then project a new tuple with the
		 * junk removed.
936
		 *
937 938 939
		 * Store this new "clean" tuple in the junkfilter's resultSlot.
		 * (Formerly, we stored it back over the "dirty" tuple, which is
		 * WRONG because that tuple slot has the wrong descriptor.)
940
		 *
B
Bruce Momjian 已提交
941
		 * Also, extract all the junk information we need.
942 943 944
		 */
		if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
		{
945 946 947
			Datum		datum;
			HeapTuple	newTuple;
			bool		isNull;
948

B
Bruce Momjian 已提交
949
			/*
950 951 952 953 954 955 956 957 958
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
959
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
960

961
				/* shouldn't ever get a null result... */
962
				if (isNull)
963
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
964 965 966 967 968 969

				tupleid = (ItemPointer) DatumGetPointer(datum);
				tuple_ctid = *tupleid;	/* make sure we don't free the
										 * ctid!! */
				tupleid = &tuple_ctid;
			}
970
			else if (estate->es_rowMark != NIL)
971
			{
B
Bruce Momjian 已提交
972
				List	   *l;
973

B
Bruce Momjian 已提交
974 975
		lmark:	;
				foreach(l, estate->es_rowMark)
976
				{
977 978 979 980 981 982
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

983 984 985 986 987
					if (!ExecGetJunkAttribute(junkfilter,
											  slot,
											  erm->resname,
											  &datum,
											  &isNull))
988 989
						elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
							 erm->resname);
990

991
					/* shouldn't ever get a null result... */
992
					if (isNull)
993 994
						elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
							 erm->resname);
995 996

					tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
997 998
					test = heap_mark4update(erm->relation, &tuple, &buffer,
											estate->es_snapshot->curcid);
999 1000 1001 1002
					ReleaseBuffer(buffer);
					switch (test)
					{
						case HeapTupleSelfUpdated:
1003 1004 1005
							/* treat it as deleted; do not process */
							goto lnext;

1006 1007 1008 1009 1010 1011
						case HeapTupleMayBeUpdated:
							break;

						case HeapTupleUpdated:
							if (XactIsoLevel == XACT_SERIALIZABLE)
								elog(ERROR, "Can't serialize access due to concurrent update");
1012
							if (!(ItemPointerEquals(&(tuple.t_self),
B
Bruce Momjian 已提交
1013
								  (ItemPointer) DatumGetPointer(datum))))
1014
							{
B
Bruce Momjian 已提交
1015
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1016 1017 1018 1019 1020 1021 1022
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1023 1024 1025

							/*
							 * if tuple was deleted or PlanQual failed for
1026
							 * updated tuple - we must not return this
B
Bruce Momjian 已提交
1027
							 * tuple!
1028 1029
							 */
							goto lnext;
1030 1031 1032

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
1033
							return (NULL);
1034 1035 1036
					}
				}
			}
1037

B
Bruce Momjian 已提交
1038
			/*
1039 1040 1041 1042 1043 1044
			 * Finally create a new "clean" tuple with all junk attributes
			 * removed
			 */
			newTuple = ExecRemoveJunk(junkfilter, slot);

			slot = ExecStoreTuple(newTuple,		/* tuple to store */
1045
								  junkfilter->jf_resultSlot,	/* dest slot */
B
Bruce Momjian 已提交
1046 1047
								  InvalidBuffer,		/* this tuple has no
														 * buffer */
1048
								  true);		/* tuple should be pfreed */
1049
		}
1050

B
Bruce Momjian 已提交
1051
		/*
B
Bruce Momjian 已提交
1052 1053
		 * now that we have a tuple, do the appropriate thing with it..
		 * either return it to the user, add it to a relation someplace,
B
Bruce Momjian 已提交
1054
		 * delete it from a relation, or modify some of its attributes.
1055 1056 1057
		 */
		switch (operation)
		{
1058
			case CMD_SELECT:
B
Bruce Momjian 已提交
1059 1060 1061
				ExecSelect(slot,	/* slot containing tuple */
						   destfunc,	/* destination's tuple-receiver
										 * obj */
1062
						   estate);
1063 1064
				result = slot;
				break;
1065

1066
			case CMD_INSERT:
1067
				ExecInsert(slot, tupleid, estate);
1068 1069
				result = NULL;
				break;
1070

1071 1072 1073 1074
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1075

1076
			case CMD_UPDATE:
1077
				ExecUpdate(slot, tupleid, estate);
1078 1079
				result = NULL;
				break;
1080

1081
			default:
1082
				elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1083
				result = NULL;
1084
				break;
1085
		}
B
Bruce Momjian 已提交
1086

B
Bruce Momjian 已提交
1087
		/*
1088
		 * check our tuple count.. if we've processed the proper number
1089 1090
		 * then quit, else loop again and process more tuples.  Zero
		 * number_tuples means no limit.
1091
		 */
1092
		current_tuple_count++;
1093 1094
		if (numberTuples == current_tuple_count)
			break;
1095
	}
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
	/*
	 * Process AFTER EACH STATEMENT triggers
	 */
	switch (operation)
	{
		case CMD_UPDATE:
			ExecASUpdateTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_DELETE:
			ExecASDeleteTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_INSERT:
			ExecASInsertTriggers(estate, estate->es_result_relation_info);
			break;
		default:
			/* do nothing */
1113
			break;
1114 1115
	}

B
Bruce Momjian 已提交
1116
	/*
B
Bruce Momjian 已提交
1117
	 * here, result is either a slot containing a tuple in the case of a
1118
	 * SELECT or NULL otherwise.
1119
	 */
1120
	return result;
1121 1122 1123
}

/* ----------------------------------------------------------------
1124
 *		ExecSelect
1125
 *
1126
 *		SELECTs are easy.. we just pass the tuple to the appropriate
1127
 *		print function.  The only complexity is when we do a
1128
 *		"SELECT INTO", in which case we insert the tuple into
1129 1130
 *		the appropriate relation (note: this is a newly created relation
 *		so we don't need to worry about indices or locks.)
1131 1132 1133
 * ----------------------------------------------------------------
 */
static void
1134 1135 1136
ExecSelect(TupleTableSlot *slot,
		   DestReceiver *destfunc,
		   EState *estate)
1137
{
1138 1139
	HeapTuple	tuple;
	TupleDesc	attrtype;
1140

B
Bruce Momjian 已提交
1141
	/*
B
Bruce Momjian 已提交
1142
	 * get the heap tuple out of the tuple table slot
1143 1144 1145 1146
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1147
	/*
B
Bruce Momjian 已提交
1148
	 * insert the tuple into the "into relation"
1149 1150 1151
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
1152 1153
		heap_insert(estate->es_into_relation_descriptor, tuple,
					estate->es_snapshot->curcid);
1154 1155 1156
		IncrAppended();
	}

B
Bruce Momjian 已提交
1157
	/*
B
Bruce Momjian 已提交
1158
	 * send the tuple to the front end (or the screen)
1159
	 */
1160
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1161 1162
	IncrRetrieved();
	(estate->es_processed)++;
1163 1164 1165
}

/* ----------------------------------------------------------------
1166
 *		ExecInsert
1167
 *
1168
 *		INSERTs are trickier.. we have to insert the tuple into
1169 1170
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1171 1172 1173
 * ----------------------------------------------------------------
 */
static void
1174
ExecInsert(TupleTableSlot *slot,
1175
		   ItemPointer tupleid,
1176
		   EState *estate)
1177
{
1178
	HeapTuple	tuple;
1179
	ResultRelInfo *resultRelInfo;
1180 1181 1182
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1183

B
Bruce Momjian 已提交
1184
	/*
B
Bruce Momjian 已提交
1185
	 * get the heap tuple out of the tuple table slot
1186 1187 1188
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1189
	/*
1190
	 * get information on the (current) result relation
1191
	 */
1192 1193
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1194 1195

	/* BEFORE ROW INSERT Triggers */
1196
	if (resultRelInfo->ri_TrigDesc &&
1197
		resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1198
	{
1199
		HeapTuple	newtuple;
1200

1201
		newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1202 1203 1204 1205 1206 1207

		if (newtuple == NULL)	/* "do nothing" */
			return;

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
1208 1209 1210
			/*
			 * Insert modified tuple into tuple table slot, replacing the
			 * original.  We assume that it was allocated in per-tuple
B
Bruce Momjian 已提交
1211 1212
			 * memory context, and therefore will go away by itself. The
			 * tuple table slot should not try to clear it.
1213 1214 1215
			 */
			ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
			tuple = newtuple;
1216 1217 1218
		}
	}

B
Bruce Momjian 已提交
1219
	/*
1220
	 * Check the constraints of the tuple
1221 1222
	 */
	if (resultRelationDesc->rd_att->constr)
1223
		ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1224

B
Bruce Momjian 已提交
1225
	/*
B
Bruce Momjian 已提交
1226
	 * insert the tuple
1227
	 */
1228 1229
	newId = heap_insert(resultRelationDesc, tuple,
						estate->es_snapshot->curcid);
1230

1231
	IncrAppended();
1232 1233
	(estate->es_processed)++;
	estate->es_lastoid = newId;
T
Tom Lane 已提交
1234
	setLastTid(&(tuple->t_self));
1235

B
Bruce Momjian 已提交
1236
	/*
B
Bruce Momjian 已提交
1237
	 * process indices
1238
	 *
B
Bruce Momjian 已提交
1239 1240 1241
	 * Note: heap_insert adds a new tuple to a relation.  As a side effect,
	 * the tupleid of the new tuple is placed in the new tuple's t_ctid
	 * field.
1242
	 */
1243
	numIndices = resultRelInfo->ri_NumIndices;
1244
	if (numIndices > 0)
1245
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1246 1247

	/* AFTER ROW INSERT Triggers */
1248
	ExecARInsertTriggers(estate, resultRelInfo, tuple);
1249 1250 1251
}

/* ----------------------------------------------------------------
1252
 *		ExecDelete
1253
 *
1254
 *		DELETE is like UPDATE, we delete the tuple and its
1255
 *		index tuples.
1256 1257 1258
 * ----------------------------------------------------------------
 */
static void
1259
ExecDelete(TupleTableSlot *slot,
1260
		   ItemPointer tupleid,
1261
		   EState *estate)
1262
{
1263
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
1264 1265 1266
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1267

B
Bruce Momjian 已提交
1268
	/*
1269
	 * get information on the (current) result relation
1270
	 */
1271 1272
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1273 1274

	/* BEFORE ROW DELETE Triggers */
1275
	if (resultRelInfo->ri_TrigDesc &&
1276
	  resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1277
	{
1278
		bool		dodelete;
1279

1280
		dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1281 1282 1283 1284 1285

		if (!dodelete)			/* "do nothing" */
			return;
	}

V
Vadim B. Mikheev 已提交
1286
	/*
B
Bruce Momjian 已提交
1287
	 * delete the tuple
1288
	 */
1289
ldelete:;
1290 1291 1292
	result = heap_delete(resultRelationDesc, tupleid,
						 &ctid,
						 estate->es_snapshot->curcid);
V
Vadim B. Mikheev 已提交
1293 1294 1295
	switch (result)
	{
		case HeapTupleSelfUpdated:
1296
			/* already deleted by self; nothing to do */
V
Vadim B. Mikheev 已提交
1297 1298 1299 1300 1301 1302
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1303 1304
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1305 1306
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1307
				TupleTableSlot *epqslot = EvalPlanQual(estate,
B
Bruce Momjian 已提交
1308
							   resultRelInfo->ri_RangeTableIndex, &ctid);
1309

V
Vadim B. Mikheev 已提交
1310
				if (!TupIsNull(epqslot))
1311 1312 1313 1314 1315
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
1316
			/* tuple already deleted; nothing to do */
V
Vadim B. Mikheev 已提交
1317 1318 1319 1320 1321 1322
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1323 1324 1325 1326

	IncrDeleted();
	(estate->es_processed)++;

B
Bruce Momjian 已提交
1327
	/*
B
Bruce Momjian 已提交
1328 1329
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1330
	 *
B
Bruce Momjian 已提交
1331 1332 1333
	 * ... but in POSTGRES, we have no need to do this because the vacuum
	 * daemon automatically opens an index scan and deletes index tuples
	 * when it finds deleted heap tuples. -cim 9/27/89
1334 1335 1336
	 */

	/* AFTER ROW DELETE Triggers */
1337
	ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1338 1339 1340
}

/* ----------------------------------------------------------------
1341
 *		ExecUpdate
1342
 *
1343 1344 1345 1346
 *		note: we can't run UPDATE queries with transactions
 *		off because UPDATEs are actually INSERTs and our
 *		scan will mistakenly loop forever, updating the tuple
 *		it just inserted..	This should be fixed but until it
1347 1348
 *		is, we don't want to get stuck in an infinite loop
 *		which corrupts your database..
1349 1350 1351
 * ----------------------------------------------------------------
 */
static void
1352
ExecUpdate(TupleTableSlot *slot,
B
Bruce Momjian 已提交
1353 1354
		   ItemPointer tupleid,
		   EState *estate)
1355
{
B
Bruce Momjian 已提交
1356
	HeapTuple	tuple;
1357
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
1358 1359 1360 1361
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
	int			numIndices;
1362

B
Bruce Momjian 已提交
1363
	/*
B
Bruce Momjian 已提交
1364
	 * abort the operation if not running transactions
1365 1366 1367
	 */
	if (IsBootstrapProcessingMode())
	{
1368
		elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1369 1370 1371
		return;
	}

B
Bruce Momjian 已提交
1372
	/*
B
Bruce Momjian 已提交
1373
	 * get the heap tuple out of the tuple table slot
1374 1375 1376
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1377
	/*
1378
	 * get information on the (current) result relation
1379
	 */
1380 1381
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1382 1383

	/* BEFORE ROW UPDATE Triggers */
1384
	if (resultRelInfo->ri_TrigDesc &&
1385
	  resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1386
	{
1387
		HeapTuple	newtuple;
1388

1389 1390
		newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
										tupleid, tuple);
1391 1392 1393 1394 1395 1396

		if (newtuple == NULL)	/* "do nothing" */
			return;

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
1397 1398 1399
			/*
			 * Insert modified tuple into tuple table slot, replacing the
			 * original.  We assume that it was allocated in per-tuple
B
Bruce Momjian 已提交
1400 1401
			 * memory context, and therefore will go away by itself. The
			 * tuple table slot should not try to clear it.
1402 1403 1404
			 */
			ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
			tuple = newtuple;
1405 1406 1407
		}
	}

B
Bruce Momjian 已提交
1408
	/*
1409
	 * Check the constraints of the tuple
1410
	 *
1411 1412 1413 1414 1415
	 * If we generate a new candidate tuple after EvalPlanQual testing, we
	 * must loop back here and recheck constraints.  (We don't need to
	 * redo triggers, however.	If there are any BEFORE triggers then
	 * trigger.c will have done mark4update to lock the correct tuple, so
	 * there's no need to do them again.)
1416
	 */
1417
lreplace:;
1418
	if (resultRelationDesc->rd_att->constr)
1419
		ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1420

V
Vadim B. Mikheev 已提交
1421
	/*
B
Bruce Momjian 已提交
1422
	 * replace the heap tuple
1423
	 */
1424 1425 1426
	result = heap_update(resultRelationDesc, tupleid, tuple,
						 &ctid,
						 estate->es_snapshot->curcid);
V
Vadim B. Mikheev 已提交
1427 1428 1429
	switch (result)
	{
		case HeapTupleSelfUpdated:
1430
			/* already deleted by self; nothing to do */
V
Vadim B. Mikheev 已提交
1431 1432 1433 1434 1435 1436
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1437 1438
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1439 1440
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1441
				TupleTableSlot *epqslot = EvalPlanQual(estate,
B
Bruce Momjian 已提交
1442
							   resultRelInfo->ri_RangeTableIndex, &ctid);
1443

V
Vadim B. Mikheev 已提交
1444
				if (!TupIsNull(epqslot))
1445 1446
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1447
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1448
					slot = ExecStoreTuple(tuple,
1449
									estate->es_junkFilter->jf_resultSlot,
1450
										  InvalidBuffer, true);
1451 1452 1453
					goto lreplace;
				}
			}
1454
			/* tuple already deleted; nothing to do */
V
Vadim B. Mikheev 已提交
1455 1456 1457
			return;

		default:
1458
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1459
			return;
1460 1461 1462 1463 1464
	}

	IncrReplaced();
	(estate->es_processed)++;

B
Bruce Momjian 已提交
1465
	/*
B
Bruce Momjian 已提交
1466
	 * Note: instead of having to update the old index tuples associated
B
Bruce Momjian 已提交
1467
	 * with the heap tuple, all we do is form and insert new index tuples.
1468
	 * This is because UPDATEs are actually DELETEs and INSERTs and index
B
Bruce Momjian 已提交
1469 1470
	 * tuple deletion is done automagically by the vacuum daemon. All we
	 * do is insert new index tuples.  -cim 9/27/89
1471 1472
	 */

B
Bruce Momjian 已提交
1473
	/*
B
Bruce Momjian 已提交
1474
	 * process indices
1475
	 *
1476
	 * heap_update updates a tuple in the base relation by invalidating it
1477
	 * and then inserting a new tuple to the relation.	As a side effect,
B
Bruce Momjian 已提交
1478 1479 1480
	 * the tupleid of the new tuple is placed in the new tuple's t_ctid
	 * field.  So we now insert index tuples using the new tupleid stored
	 * there.
1481 1482
	 */

1483
	numIndices = resultRelInfo->ri_NumIndices;
1484
	if (numIndices > 0)
1485
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1486 1487

	/* AFTER ROW UPDATE Triggers */
1488
	ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1489
}
V
Vadim B. Mikheev 已提交
1490

1491
static char *
1492 1493
ExecRelCheck(ResultRelInfo *resultRelInfo,
			 TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
1494
{
1495
	Relation	rel = resultRelInfo->ri_RelationDesc;
1496 1497
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
1498
	ExprContext *econtext;
1499
	MemoryContext oldContext;
1500 1501
	List	   *qual;
	int			i;
1502

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
	/*
	 * If first time through for this result relation, build expression
	 * nodetrees for rel's constraint expressions.  Keep them in the
	 * per-query memory context so they'll survive throughout the query.
	 */
	if (resultRelInfo->ri_ConstraintExprs == NULL)
	{
		oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
		resultRelInfo->ri_ConstraintExprs =
			(List **) palloc(ncheck * sizeof(List *));
		for (i = 0; i < ncheck; i++)
		{
			qual = (List *) stringToNode(check[i].ccbin);
1516
			resultRelInfo->ri_ConstraintExprs[i] = (List *)
1517
				ExecPrepareExpr((Expr *) qual, estate);
1518 1519 1520 1521
		}
		MemoryContextSwitchTo(oldContext);
	}

1522
	/*
B
Bruce Momjian 已提交
1523 1524
	 * We will use the EState's per-tuple context for evaluating
	 * constraint expressions (creating it if it's not already there).
1525
	 */
1526
	econtext = GetPerTupleExprContext(estate);
1527

1528 1529 1530 1531
	/* Arrange for econtext's scan tuple to be the tuple under test */
	econtext->ecxt_scantuple = slot;

	/* And evaluate the constraints */
1532 1533
	for (i = 0; i < ncheck; i++)
	{
1534
		qual = resultRelInfo->ri_ConstraintExprs[i];
1535

1536 1537
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
1538 1539
		 * expression is not to be treated as a failure.  Therefore, tell
		 * ExecQual to return TRUE for NULL.
1540
		 */
1541
		if (!ExecQual(qual, econtext, true))
1542
			return check[i].ccname;
1543 1544
	}

1545
	/* NULL result means no error */
1546
	return (char *) NULL;
V
Vadim B. Mikheev 已提交
1547 1548
}

1549
void
1550
ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1551
				TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
1552
{
1553
	Relation	rel = resultRelInfo->ri_RelationDesc;
1554 1555 1556 1557
	HeapTuple	tuple = slot->val;
	TupleConstr *constr = rel->rd_att->constr;

	Assert(constr);
1558

1559
	if (constr->has_not_null)
V
Vadim B. Mikheev 已提交
1560
	{
1561
		int			natts = rel->rd_att->natts;
1562
		int			attrChk;
1563

1564
		for (attrChk = 1; attrChk <= natts; attrChk++)
1565
		{
B
Bruce Momjian 已提交
1566
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1567
				heap_attisnull(tuple, attrChk))
1568
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
B
Bruce Momjian 已提交
1569
					 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1570 1571 1572
		}
	}

1573
	if (constr->num_check > 0)
1574
	{
1575
		char	   *failed;
1576

1577
		if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
B
Bruce Momjian 已提交
1578 1579
			elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
				 caller, failed, RelationGetRelationName(rel));
1580
	}
V
Vadim B. Mikheev 已提交
1581
}
1582

1583 1584 1585 1586 1587 1588
/*
 * Check a modified tuple to see if we want to process its updated version
 * under READ COMMITTED rules.
 *
 * See backend/executor/README for some info about how this works.
 */
B
Bruce Momjian 已提交
1589
TupleTableSlot *
1590 1591
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
1592 1593
	evalPlanQual *epq;
	EState	   *epqstate;
B
Bruce Momjian 已提交
1594 1595
	Relation	relation;
	HeapTupleData tuple;
1596 1597 1598
	HeapTuple	copyTuple = NULL;
	int			rtsize;
	bool		endNode;
1599 1600 1601

	Assert(rti != 0);

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
	/*
	 * find relation containing target tuple
	 */
	if (estate->es_result_relation_info != NULL &&
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
		List	   *l;

		relation = NULL;
		foreach(l, estate->es_rowMark)
		{
			if (((execRowMark *) lfirst(l))->rti == rti)
			{
				relation = ((execRowMark *) lfirst(l))->relation;
				break;
			}
		}
		if (relation == NULL)
			elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
	}

	/*
	 * fetch tid tuple
	 *
	 * Loop here to deal with updated or busy tuples
	 */
	tuple.t_self = *tid;
	for (;;)
	{
		Buffer		buffer;

1635
		if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
				elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");

			/*
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}

			/*
			 * We got tuple - now copy it for use by recheck query.
			 */
			copyTuple = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}

		/*
		 * Oops! Invalid tuple. Have to check is it updated or deleted.
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
		 */
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			/* updated, so look at the updated copy */
			tuple.t_self = SnapshotDirty->tid;
			continue;
		}

		/*
		 * Deleted or updated by this transaction; forget it.
		 */
		return NULL;
	}

	/*
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
	 */
	*tid = tuple.t_self;

	/*
1687
	 * Need to run a recheck subquery.	Find or create a PQ stack entry.
1688 1689 1690 1691 1692
	 */
	epq = (evalPlanQual *) estate->es_evalPlanQual;
	rtsize = length(estate->es_range_table);
	endNode = true;

1693 1694
	if (epq != NULL && epq->rti == 0)
	{
1695
		/* Top PQ stack entry is idle, so re-use it */
B
Bruce Momjian 已提交
1696 1697
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1698 1699 1700 1701 1702 1703
		epq->rti = rti;
		endNode = false;
	}

	/*
	 * If this is request for another RTE - Ra, - then we have to check
B
Bruce Momjian 已提交
1704 1705 1706
	 * wasn't PlanQual requested for Ra already and if so then Ra' row was
	 * updated again and we have to re-start old execution for Ra and
	 * forget all what we done after Ra was suspended. Cool? -:))
1707
	 */
B
Bruce Momjian 已提交
1708
	if (epq != NULL && epq->rti != rti &&
1709 1710 1711 1712
		epq->estate.es_evTuple[rti - 1] != NULL)
	{
		do
		{
1713 1714
			evalPlanQual *oldepq;

1715 1716
			/* pop previous PlanQual from the stack */
			epqstate = &(epq->estate);
B
Bruce Momjian 已提交
1717
			oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1718 1719
			Assert(oldepq->rti != 0);
			/* stop execution */
1720
			ExecEndNode(epq->planstate);
1721 1722
			ExecDropTupleTable(epqstate->es_tupleTable, true);
			epqstate->es_tupleTable = NULL;
1723
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1724 1725 1726 1727
			epqstate->es_evTuple[epq->rti - 1] = NULL;
			/* push current PQ to freePQ stack */
			oldepq->free = epq;
			epq = oldepq;
1728
			estate->es_evalPlanQual = (Pointer) epq;
1729 1730 1731
		} while (epq->rti != rti);
	}

B
Bruce Momjian 已提交
1732
	/*
1733 1734 1735 1736 1737 1738
	 * If we are requested for another RTE then we have to suspend
	 * execution of current PlanQual and start execution for new one.
	 */
	if (epq == NULL || epq->rti != rti)
	{
		/* try to reuse plan used previously */
B
Bruce Momjian 已提交
1739
		evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1740

1741
		if (newepq == NULL)		/* first call or freePQ stack is empty */
1742
		{
B
Bruce Momjian 已提交
1743
			newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1744
			newepq->free = NULL;
1745

1746
			/*
1747
			 * Each stack level has its own copy of the plan tree.	This
1748 1749
			 * is wasteful, but necessary until plan trees are fully
			 * read-only.
1750 1751
			 */
			newepq->plan = copyObject(estate->es_origPlan);
1752

1753 1754
			/*
			 * Init stack level's EState.  We share top level's copy of
1755 1756
			 * es_result_relations array and other non-changing status. We
			 * need our own tupletable, es_param_exec_vals, and other
1757 1758
			 * changeable state.
			 */
1759
			epqstate = &(newepq->estate);
1760
			memcpy(epqstate, estate, sizeof(EState));
1761 1762 1763
			epqstate->es_direction = ForwardScanDirection;
			if (estate->es_origPlan->nParamExec > 0)
				epqstate->es_param_exec_vals = (ParamExecData *)
B
Bruce Momjian 已提交
1764 1765
					palloc(estate->es_origPlan->nParamExec *
						   sizeof(ParamExecData));
1766 1767
			epqstate->es_tupleTable = NULL;
			epqstate->es_per_tuple_exprcontext = NULL;
1768

1769
			/*
1770 1771 1772 1773
			 * Each epqstate must have its own es_evTupleNull state, but
			 * all the stack entries share es_evTuple state.  This allows
			 * sub-rechecks to inherit the value being examined by an
			 * outer recheck.
1774 1775 1776 1777
			 */
			epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
			if (epq == NULL)
				/* first PQ stack entry */
B
Bruce Momjian 已提交
1778
				epqstate->es_evTuple = (HeapTuple *)
1779
					palloc0(rtsize * sizeof(HeapTuple));
1780
			else
1781
				/* later stack entries share the same storage */
1782 1783 1784
				epqstate->es_evTuple = epq->estate.es_evTuple;
		}
		else
1785 1786
		{
			/* recycle previously used EState */
1787
			epqstate = &(newepq->estate);
1788
		}
1789 1790
		/* push current PQ to the stack */
		epqstate->es_evalPlanQual = (Pointer) epq;
1791 1792
		epq = newepq;
		estate->es_evalPlanQual = (Pointer) epq;
1793 1794 1795 1796
		epq->rti = rti;
		endNode = false;
	}

1797
	Assert(epq->rti == rti);
1798 1799 1800
	epqstate = &(epq->estate);

	/*
1801 1802
	 * Ok - we're requested for the same RTE.  Unfortunately we still have
	 * to end and restart execution of the plan, because ExecReScan
1803
	 * wouldn't ensure that upper plan nodes would reset themselves.  We
1804 1805 1806
	 * could make that work if insertion of the target tuple were
	 * integrated with the Param mechanism somehow, so that the upper plan
	 * nodes know that their children's outputs have changed.
1807 1808
	 */
	if (endNode)
1809
	{
1810
		/* stop execution */
1811
		ExecEndNode(epq->planstate);
1812 1813
		ExecDropTupleTable(epqstate->es_tupleTable, true);
		epqstate->es_tupleTable = NULL;
1814
	}
1815

1816
	/*
1817 1818
	 * free old RTE' tuple, if any, and store target tuple where
	 * relation's scan node will see it
1819 1820 1821 1822
	 */
	if (epqstate->es_evTuple[rti - 1] != NULL)
		heap_freetuple(epqstate->es_evTuple[rti - 1]);
	epqstate->es_evTuple[rti - 1] = copyTuple;
1823

1824 1825 1826 1827 1828 1829
	/*
	 * Initialize for new recheck query; be careful to copy down state
	 * that might have changed in top EState.
	 */
	epqstate->es_result_relation_info = estate->es_result_relation_info;
	epqstate->es_junkFilter = estate->es_junkFilter;
1830
	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1831 1832
		memset(epqstate->es_param_exec_vals, 0,
			   estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1833 1834 1835 1836 1837
	memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
	epqstate->es_useEvalPlan = false;
	Assert(epqstate->es_tupleTable == NULL);
	epqstate->es_tupleTable =
		ExecCreateTupleTable(estate->es_tupleTable->size);
1838

1839
	epq->planstate = ExecInitNode(epq->plan, epqstate);
1840

1841
	return EvalPlanQualNext(estate);
1842 1843
}

B
Bruce Momjian 已提交
1844
static TupleTableSlot *
1845 1846
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1847 1848 1849 1850
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1851 1852 1853 1854

	Assert(epq->rti != 0);

lpqnext:;
1855
	slot = ExecProcNode(epq->planstate);
1856 1857 1858 1859 1860 1861

	/*
	 * No more tuples for this PQ. Continue previous one.
	 */
	if (TupIsNull(slot))
	{
1862
		/* stop execution */
1863
		ExecEndNode(epq->planstate);
1864 1865
		ExecDropTupleTable(epqstate->es_tupleTable, true);
		epqstate->es_tupleTable = NULL;
1866
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1867 1868
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1869 1870
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
1871
		{
1872 1873 1874
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free and	  */
			return (NULL);		/* continue Query execution   */
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
		epqstate = &(epq->estate);
		estate->es_evalPlanQual = (Pointer) epq;
		goto lpqnext;
	}

	return (slot);
}
1887 1888 1889 1890 1891 1892 1893 1894

static void
EndEvalPlanQual(EState *estate)
{
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;

1895 1896 1897
	if (epq->rti == 0)			/* plans already shutdowned */
	{
		Assert(epq->estate.es_evalPlanQual == NULL);
1898
		return;
1899
	}
1900 1901 1902

	for (;;)
	{
1903
		/* stop execution */
1904
		ExecEndNode(epq->planstate);
1905 1906
		ExecDropTupleTable(epqstate->es_tupleTable, true);
		epqstate->es_tupleTable = NULL;
1907 1908 1909 1910 1911
		if (epqstate->es_evTuple[epq->rti - 1] != NULL)
		{
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
			epqstate->es_evTuple[epq->rti - 1] = NULL;
		}
1912 1913 1914 1915
		/* pop old PQ from the stack */
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
		{
1916 1917
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free */
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
			break;
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
		epqstate = &(epq->estate);
		estate->es_evalPlanQual = (Pointer) epq;
	}
}