execMain.c 48.2 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 15 16 17 18 19 20 21 22 23
 *	The old ExecutorMain() has been replaced by ExecutorStart(),
 *	ExecutorRun() and ExecutorEnd()
 *
 *	These three procedures are the external interfaces to the executor.
 *	In each case, the query descriptor and the execution state is required
 *	 as arguments
 *
 *	ExecutorStart() must be called at the beginning of any execution of any
 *	query plan and ExecutorEnd() should always be called at the end of
 *	execution of a plan.
 *
 *	ExecutorRun accepts 'feature' and 'count' arguments that specify whether
 *	the plan is to be executed forwards, backwards, and for how many tuples.
24
 *
B
Add:  
Bruce Momjian 已提交
25 26
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
27 28 29
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
30
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.130 2000/10/16 17:08:06 momjian Exp $
31 32 33
 *
 *-------------------------------------------------------------------------
 */
34 35
#include "postgres.h"

36 37
#include "access/heapam.h"
#include "catalog/heap.h"
38
#include "commands/command.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

47 48

/* decls for local routines only used within this module */
49
static TupleDesc InitPlan(CmdType operation,
B
Bruce Momjian 已提交
50 51 52
		 Query *parseTree,
		 Plan *plan,
		 EState *estate);
53
static void EndPlan(Plan *plan, EState *estate);
54
static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
B
Bruce Momjian 已提交
55 56 57 58
			CmdType operation,
			int offsetTuples,
			int numberTuples,
			ScanDirection direction,
59
			DestReceiver *destfunc);
60
static void ExecRetrieve(TupleTableSlot *slot,
61
			 DestReceiver *destfunc,
B
Bruce Momjian 已提交
62
			 EState *estate);
63
static void ExecAppend(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 ExecReplace(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 ExecCheckQueryPerms(CmdType operation, Query *parseTree,
72 73 74 75 76
								Plan *plan);
static void ExecCheckPlanPerms(Plan *plan, List *rangeTable,
							   CmdType operation);
static void ExecCheckRTPerms(List *rangeTable, CmdType operation);
static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
77

78 79
/* end of local decls */

80

81
/* ----------------------------------------------------------------
82 83 84 85 86
 *		ExecutorStart
 *
 *		This routine must be called at the beginning of any execution of any
 *		query plan
 *
87
 *		returns a TupleDesc which describes the attributes of the tuples to
88
 *		be returned by the query.
89
 *
90 91 92
 * NB: the CurrentMemoryContext when this is called must be the context
 * to be used as the per-query context for the query plan.  ExecutorRun()
 * and ExecutorEnd() must be called in this same memory context.
93 94 95
 * ----------------------------------------------------------------
 */
TupleDesc
96
ExecutorStart(QueryDesc *queryDesc, EState *estate)
97
{
98
	TupleDesc	result;
99 100 101

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

V
Vadim B. Mikheev 已提交
103 104
	if (queryDesc->plantree->nParamExec > 0)
	{
105 106
		estate->es_param_exec_vals = (ParamExecData *)
			palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
107 108
		MemSet(estate->es_param_exec_vals, 0,
			   queryDesc->plantree->nParamExec * sizeof(ParamExecData));
V
Vadim B. Mikheev 已提交
109
	}
110

111 112 113
	/*
	 * Make our own private copy of the current queries snapshot data
	 */
114
	if (QuerySnapshot == NULL)
J
Jan Wieck 已提交
115
		estate->es_snapshot = NULL;
116
	else
117
	{
B
Bruce Momjian 已提交
118
		estate->es_snapshot = (Snapshot) palloc(sizeof(SnapshotData));
119 120 121 122
		memcpy(estate->es_snapshot, QuerySnapshot, sizeof(SnapshotData));
		if (estate->es_snapshot->xcnt > 0)
		{
			estate->es_snapshot->xip = (TransactionId *)
B
Bruce Momjian 已提交
123
				palloc(estate->es_snapshot->xcnt * sizeof(TransactionId));
124
			memcpy(estate->es_snapshot->xip, QuerySnapshot->xip,
B
Bruce Momjian 已提交
125
				   estate->es_snapshot->xcnt * sizeof(TransactionId));
126
		}
127
	}
128

129 130 131
	/*
	 * Initialize the plan
	 */
132 133 134 135 136 137
	result = InitPlan(queryDesc->operation,
					  queryDesc->parsetree,
					  queryDesc->plantree,
					  estate);

	return result;
138 139 140
}

/* ----------------------------------------------------------------
141 142 143 144 145 146 147
 *		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.
148
 *
149 150 151 152 153 154
 *		the different features supported are:
 *			 EXEC_RUN:	retrieve all tuples in the forward direction
 *			 EXEC_FOR:	retrieve 'count' number of tuples in the forward dir
 *			 EXEC_BACK: retrieve 'count' number of tuples in the backward dir
 *			 EXEC_RETONE: return one tuple but don't 'retrieve' it
 *						   used in postquel function processing
155 156 157
 *
 * ----------------------------------------------------------------
 */
158
TupleTableSlot *
B
Bruce Momjian 已提交
159 160
ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature,
			Node *limoffset, Node *limcount)
161
{
B
Bruce Momjian 已提交
162 163
	CmdType		operation;
	Plan	   *plan;
164
	TupleTableSlot *result;
B
Bruce Momjian 已提交
165 166 167 168
	CommandDest dest;
	DestReceiver *destfunc;
	int			offset = 0;
	int			count = 0;
169

B
Bruce Momjian 已提交
170
	/*
B
Bruce Momjian 已提交
171
	 * sanity checks
172
	 */
173 174
	Assert(queryDesc != NULL);

B
Bruce Momjian 已提交
175
	/*
B
Bruce Momjian 已提交
176 177
	 * extract information from the query descriptor and the query
	 * feature.
178
	 */
179 180 181
	operation = queryDesc->operation;
	plan = queryDesc->plantree;
	dest = queryDesc->dest;
182
	destfunc = DestToFunction(dest);
183 184 185
	estate->es_processed = 0;
	estate->es_lastoid = InvalidOid;

B
Bruce Momjian 已提交
186
	/*
B
Bruce Momjian 已提交
187 188 189 190
	 * FIXME: the dest setup function ought to be handed the tuple desc
	 * for the tuples to be output, but I'm not quite sure how to get that
	 * info at this point.	For now, passing NULL is OK because no
	 * existing dest setup function actually uses the pointer.
191 192 193
	 */
	(*destfunc->setup) (destfunc, (TupleDesc) NULL);

B
Bruce Momjian 已提交
194 195 196 197 198 199 200 201 202 203
	/*
	 * if given get the offset of the LIMIT clause
	 */
	if (limoffset != NULL)
	{
		Const	   *coffset;
		Param	   *poffset;
		ParamListInfo paramLI;
		int			i;

204 205 206
		switch (nodeTag(limoffset))
		{
			case T_Const:
B
Bruce Momjian 已提交
207 208
				coffset = (Const *) limoffset;
				offset = (int) (coffset->constvalue);
209
				break;
B
Bruce Momjian 已提交
210

211
			case T_Param:
B
Bruce Momjian 已提交
212
				poffset = (Param *) limoffset;
213
				paramLI = estate->es_param_list_info;
B
Bruce Momjian 已提交
214

215 216 217 218 219 220 221 222 223 224 225
				if (paramLI == NULL)
					elog(ERROR, "parameter for limit offset not in executor state");
				for (i = 0; paramLI[i].kind != PARAM_INVALID; i++)
				{
					if (paramLI[i].kind == PARAM_NUM && paramLI[i].id == poffset->paramid)
						break;
				}
				if (paramLI[i].kind == PARAM_INVALID)
					elog(ERROR, "parameter for limit offset not in executor state");
				if (paramLI[i].isnull)
					elog(ERROR, "limit offset cannot be NULL value");
B
Bruce Momjian 已提交
226 227
				offset = (int) (paramLI[i].value);

228
				break;
B
Bruce Momjian 已提交
229

230 231 232
			default:
				elog(ERROR, "unexpected node type %d as limit offset", nodeTag(limoffset));
		}
B
Bruce Momjian 已提交
233

234 235 236
		if (offset < 0)
			elog(ERROR, "limit offset cannot be negative");
	}
B
Bruce Momjian 已提交
237

B
Bruce Momjian 已提交
238
	/*
B
Bruce Momjian 已提交
239
	 * if given get the count of the LIMIT clause
240 241 242
	 */
	if (limcount != NULL)
	{
B
Bruce Momjian 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
		Const	   *ccount;
		Param	   *pcount;
		ParamListInfo paramLI;
		int			i;

		switch (nodeTag(limcount))
		{
			case T_Const:
				ccount = (Const *) limcount;
				count = (int) (ccount->constvalue);
				break;

			case T_Param:
				pcount = (Param *) limcount;
				paramLI = estate->es_param_list_info;

				if (paramLI == NULL)
					elog(ERROR, "parameter for limit count not in executor state");
				for (i = 0; paramLI[i].kind != PARAM_INVALID; i++)
				{
					if (paramLI[i].kind == PARAM_NUM && paramLI[i].id == pcount->paramid)
						break;
				}
				if (paramLI[i].kind == PARAM_INVALID)
					elog(ERROR, "parameter for limit count not in executor state");
				if (paramLI[i].isnull)
					elog(ERROR, "limit count cannot be NULL value");
				count = (int) (paramLI[i].value);

				break;

			default:
				elog(ERROR, "unexpected node type %d as limit count", nodeTag(limcount));
		}

		if (count < 0)
			elog(ERROR, "limit count cannot be negative");
280 281
	}

282 283 284
	switch (feature)
	{

285 286 287 288
		case EXEC_RUN:
			result = ExecutePlan(estate,
								 plan,
								 operation,
289 290
								 offset,
								 count,
291
								 ForwardScanDirection,
292
								 destfunc);
293 294 295 296 297
			break;
		case EXEC_FOR:
			result = ExecutePlan(estate,
								 plan,
								 operation,
298
								 offset,
299 300
								 count,
								 ForwardScanDirection,
301
								 destfunc);
302
			break;
303

B
Bruce Momjian 已提交
304
			/*
B
Bruce Momjian 已提交
305
			 * retrieve next n "backward" tuples
306 307 308 309 310
			 */
		case EXEC_BACK:
			result = ExecutePlan(estate,
								 plan,
								 operation,
311
								 offset,
312 313
								 count,
								 BackwardScanDirection,
314
								 destfunc);
315
			break;
316

B
Bruce Momjian 已提交
317
			/*
B
Bruce Momjian 已提交
318 319
			 * return one tuple but don't "retrieve" it. (this is used by
			 * the rule manager..) -cim 9/14/89
320 321 322 323 324
			 */
		case EXEC_RETONE:
			result = ExecutePlan(estate,
								 plan,
								 operation,
325
								 0,
326 327
								 ONE_TUPLE,
								 ForwardScanDirection,
328
								 destfunc);
329 330 331 332 333
			break;
		default:
			result = NULL;
			elog(DEBUG, "ExecutorRun: Unknown feature %d", feature);
			break;
334 335
	}

336 337
	(*destfunc->cleanup) (destfunc);

338
	return result;
339 340 341
}

/* ----------------------------------------------------------------
342 343 344 345 346 347 348
 *		ExecutorEnd
 *
 *		This routine must be called at the end of any execution of any
 *		query plan
 *
 *		returns (AttrInfo*) which describes the attributes of the tuples to
 *		be returned by the query.
349 350 351 352
 *
 * ----------------------------------------------------------------
 */
void
353
ExecutorEnd(QueryDesc *queryDesc, EState *estate)
354
{
355 356
	/* sanity checks */
	Assert(queryDesc != NULL);
357

358
	EndPlan(queryDesc->plantree, estate);
359

360
	/* XXX - clean up some more from ExecutorStart() - er1p */
B
Bruce Momjian 已提交
361 362 363 364 365 366 367 368 369
	if (NULL == estate->es_snapshot)
	{
		/* nothing to free */
	}
	else
	{
		if (estate->es_snapshot->xcnt > 0)
			pfree(estate->es_snapshot->xip);
		pfree(estate->es_snapshot);
370 371
	}

B
Bruce Momjian 已提交
372 373 374 375 376 377 378 379
	if (NULL == estate->es_param_exec_vals)
	{
		/* nothing to free */
	}
	else
	{
		pfree(estate->es_param_exec_vals);
		estate->es_param_exec_vals = NULL;
380
	}
381 382
}

383 384 385 386 387 388 389

/*
 * ExecCheckQueryPerms
 *		Check access permissions for all relations referenced in a query.
 */
static void
ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
390
{
391 392 393
	/*
	 * Check RTEs in the query's primary rangetable.
	 */
394
	ExecCheckRTPerms(parseTree->rtable, operation);
395

396 397 398
	/*
	 * Search for subplans and APPEND nodes to check their rangetables.
	 */
399
	ExecCheckPlanPerms(plan, parseTree->rtable, operation);
400 401 402 403 404 405 406 407 408 409 410 411
}

/*
 * ExecCheckPlanPerms
 *		Recursively scan the plan tree to check access permissions in
 *		subplans.
 *
 * We also need to look at the local rangetables in Append plan nodes,
 * which is pretty bogus --- most likely, those tables should be mentioned
 * in the query's main rangetable.  But at the moment, they're not.
 */
static void
412
ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
413 414 415 416 417 418 419 420 421 422
{
	List	   *subp;

	if (plan == NULL)
		return;

	/* Check subplans, which we assume are plain SELECT queries */

	foreach(subp, plan->initPlan)
	{
423
		SubPlan    *subplan = (SubPlan *) lfirst(subp);
424

425 426
		ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
		ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
427 428 429
	}
	foreach(subp, plan->subPlan)
	{
430
		SubPlan    *subplan = (SubPlan *) lfirst(subp);
M
Marc G. Fournier 已提交
431

432 433
		ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
		ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
434 435 436 437
	}

	/* Check lower plan nodes */

438 439
	ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
	ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
440 441 442 443 444

	/* Do node-type-specific checks */

	switch (nodeTag(plan))
	{
445 446 447 448 449 450 451 452 453 454 455
		case T_SubqueryScan:
			{
				SubqueryScan   *scan = (SubqueryScan *) plan;
				RangeTblEntry *rte;

				/* Recursively check the subquery */
				rte = rt_fetch(scan->scan.scanrelid, rangeTable);
				Assert(rte->subquery != NULL);
				ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
				break;
			}
456
		case T_Append:
457
			{
458 459
				Append	   *app = (Append *) plan;
				List	   *appendplans;
460

461
				if (app->inheritrelid > 0)
462
				{
463 464
					/* Append implements expansion of inheritance */
					ExecCheckRTPerms(app->inheritrtable, operation);
465

466
					foreach(appendplans, app->appendplans)
467
					{
468 469 470
						ExecCheckPlanPerms((Plan *) lfirst(appendplans),
										   rangeTable,
										   operation);
471 472 473
					}
				}
				else
474
				{
475
					/* Append implements UNION, which must be a SELECT */
476
					foreach(appendplans, app->appendplans)
477
					{
478
						ExecCheckPlanPerms((Plan *) lfirst(appendplans),
479
										   rangeTable,
480
										   CMD_SELECT);
481
					}
482
				}
483
				break;
484 485 486
			}

		default:
487
			break;
488
	}
489
}
490

491 492 493 494 495
/*
 * ExecCheckRTPerms
 *		Check access permissions for all relations listed in a range table.
 */
static void
496
ExecCheckRTPerms(List *rangeTable, CmdType operation)
497 498 499 500
{
	List	   *lp;

	foreach(lp, rangeTable)
501
	{
502 503
		RangeTblEntry *rte = lfirst(lp);

504
		ExecCheckRTEPerms(rte, operation);
505 506 507 508 509 510 511 512
	}
}

/*
 * ExecCheckRTEPerms
 *		Check access permissions for a single RTE.
 */
static void
513
ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
514 515
{
	char	   *relName;
516
	Oid			userid;
517 518
	int32		aclcheck_result;

519 520 521 522 523
	/*
	 * If it's a subquery RTE, ignore it --- it will be checked when
	 * ExecCheckPlanPerms finds the SubqueryScan node for it.
	 */
	if (rte->subquery)
524 525 526 527 528
		return;

	relName = rte->relname;

	/*
529 530
	 * userid to check as: current user unless we have a setuid indication.
	 *
531
	 * Note: GetUserId() is presently fast enough that there's no harm
532
	 * in calling it separately for each RTE.  If that stops being true,
533
	 * we could call it once in ExecCheckQueryPerms and pass the userid
534 535
	 * down from there.  But for now, no need for the extra clutter.
	 */
536
	userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
537

538
#define CHECK(MODE)		pg_aclcheck(relName, userid, MODE)
539

540
	if (rte->checkForRead)
541
	{
542 543 544 545 546 547 548 549 550 551 552 553 554
		aclcheck_result = CHECK(ACL_RD);
		if (aclcheck_result != ACLCHECK_OK)
			elog(ERROR, "%s: %s",
				 relName, aclcheck_error_strings[aclcheck_result]);
	}

	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.
		 */
555 556 557 558 559 560 561 562
		switch (operation)
		{
			case CMD_INSERT:
				/* Accept either APPEND or WRITE access for this */
				aclcheck_result = CHECK(ACL_AP);
				if (aclcheck_result != ACLCHECK_OK)
					aclcheck_result = CHECK(ACL_WR);
				break;
563
			case CMD_SELECT:
564 565 566 567 568 569 570
			case CMD_DELETE:
			case CMD_UPDATE:
				aclcheck_result = CHECK(ACL_WR);
				break;
			default:
				elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
					 operation);
571
				aclcheck_result = ACLCHECK_OK;	/* keep compiler quiet */
572 573
				break;
		}
574 575 576
		if (aclcheck_result != ACLCHECK_OK)
			elog(ERROR, "%s: %s",
				 relName, aclcheck_error_strings[aclcheck_result]);
577
	}
578 579
}

580

581 582 583 584 585 586 587
/* ===============================================================
 * ===============================================================
						 static routines follow
 * ===============================================================
 * ===============================================================
 */

588 589 590
typedef struct execRowMark
{
	Relation	relation;
591
	Index		rti;
592
	char		resname[32];
593
} execRowMark;
594

595 596
typedef struct evalPlanQual
{
B
Bruce Momjian 已提交
597 598 599 600
	Plan	   *plan;
	Index		rti;
	EState		estate;
	struct evalPlanQual *free;
601
} evalPlanQual;
602

603
/* ----------------------------------------------------------------
604 605 606 607
 *		InitPlan
 *
 *		Initializes the query plan: open files, allocate storage
 *		and start up the rule manager
608 609
 * ----------------------------------------------------------------
 */
610
static TupleDesc
611
InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
612
{
B
Bruce Momjian 已提交
613 614 615 616 617
	List	   *rangeTable;
	int			resultRelation;
	Relation	intoRelationDesc;
	TupleDesc	tupType;
	List	   *targetList;
618

619 620 621 622 623
	/*
	 * Do permissions checks.
	 */
	ExecCheckQueryPerms(operation, parseTree, plan);

B
Bruce Momjian 已提交
624
	/*
B
Bruce Momjian 已提交
625
	 * get information from query descriptor
626
	 */
627 628
	rangeTable = parseTree->rtable;
	resultRelation = parseTree->resultRelation;
629

B
Bruce Momjian 已提交
630
	/*
B
Bruce Momjian 已提交
631
	 * initialize the node's execution state
632
	 */
633 634
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
635
	/*
B
Bruce Momjian 已提交
636
	 * initialize result relation stuff
637
	 */
B
Bruce Momjian 已提交
638

639 640
	if (resultRelation != 0 && operation != CMD_SELECT)
	{
B
Bruce Momjian 已提交
641

B
Bruce Momjian 已提交
642
		/*
B
Bruce Momjian 已提交
643 644
		 * if we have a result relation, open it and initialize the result
		 * relation info stuff.
645
		 */
646 647 648 649
		RelationInfo *resultRelationInfo;
		Index		resultRelationIndex;
		Oid			resultRelationOid;
		Relation	resultRelationDesc;
650 651

		resultRelationIndex = resultRelation;
652
		resultRelationOid = getrelid(resultRelationIndex, rangeTable);
653
		resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
654 655

		if (resultRelationDesc->rd_rel->relkind == RELKIND_SEQUENCE)
656
			elog(ERROR, "You can't change sequence relation %s",
657
				 RelationGetRelationName(resultRelationDesc));
658

659 660 661 662
		if (resultRelationDesc->rd_rel->relkind == RELKIND_TOASTVALUE)
			elog(ERROR, "You can't change toast relation %s",
				 RelationGetRelationName(resultRelationDesc));

663 664 665 666
		if (resultRelationDesc->rd_rel->relkind == RELKIND_VIEW)
			elog(ERROR, "You can't change view relation %s",
				 RelationGetRelationName(resultRelationDesc));

667 668 669 670 671 672
		resultRelationInfo = makeNode(RelationInfo);
		resultRelationInfo->ri_RangeTableIndex = resultRelationIndex;
		resultRelationInfo->ri_RelationDesc = resultRelationDesc;
		resultRelationInfo->ri_NumIndices = 0;
		resultRelationInfo->ri_IndexRelationDescs = NULL;
		resultRelationInfo->ri_IndexRelationInfo = NULL;
673

B
Bruce Momjian 已提交
674
		/*
675 676
		 * If there are indices on the result relation, open them and save
		 * descriptors in the result relation info, so that we can add new
677 678 679
		 * index entries for the tuples we add/update.	We need not do
		 * this for a DELETE, however, since deletion doesn't affect
		 * indexes.
680
		 */
681 682
		if (resultRelationDesc->rd_rel->relhasindex &&
			operation != CMD_DELETE)
683
			ExecOpenIndices(resultRelationInfo);
684 685

		estate->es_result_relation_info = resultRelationInfo;
686
	}
687 688
	else
	{
B
Bruce Momjian 已提交
689

B
Bruce Momjian 已提交
690
		/*
B
Bruce Momjian 已提交
691
		 * if no result relation, then set state appropriately
692 693 694 695
		 */
		estate->es_result_relation_info = NULL;
	}

696 697 698
	/*
	 * Have to lock relations selected for update
	 */
699 700
	estate->es_rowMark = NIL;
	if (parseTree->rowMarks != NIL)
701
	{
B
Bruce Momjian 已提交
702
		List	   *l;
703

704
		foreach(l, parseTree->rowMarks)
705
		{
706 707
			Index		rti = lfirsti(l);
			Oid			relid = getrelid(rti, rangeTable);
708 709 710 711
			Relation	relation;
			execRowMark *erm;

			relation = heap_open(relid, RowShareLock);
B
Bruce Momjian 已提交
712
			erm = (execRowMark *) palloc(sizeof(execRowMark));
713
			erm->relation = relation;
714 715
			erm->rti = rti;
			sprintf(erm->resname, "ctid%u", rti);
716 717 718
			estate->es_rowMark = lappend(estate->es_rowMark, erm);
		}
	}
719

B
Bruce Momjian 已提交
720
	/*
B
Bruce Momjian 已提交
721
	 * initialize the executor "tuple" table.
722 723
	 */
	{
724 725
		int			nSlots = ExecCountSlotsNode(plan);
		TupleTable	tupleTable = ExecCreateTupleTable(nSlots + 10);		/* why add ten? - jolly */
726

727 728
		estate->es_tupleTable = tupleTable;
	}
729

B
Bruce Momjian 已提交
730
	/*
B
Bruce Momjian 已提交
731 732
	 * initialize the private state information for all the nodes in the
	 * query tree.	This opens files, allocates storage and leaves us
733
	 * ready to start processing tuples.
734 735 736
	 */
	ExecInitNode(plan, estate, NULL);

B
Bruce Momjian 已提交
737
	/*
B
Bruce Momjian 已提交
738 739 740
	 * get the tuple descriptor describing the type of tuples to return..
	 * (this is especially important if we are creating a relation with
	 * "retrieve into")
741 742 743 744
	 */
	tupType = ExecGetTupType(plan);		/* tuple descriptor */
	targetList = plan->targetlist;

B
Bruce Momjian 已提交
745
	/*
746 747 748 749 750
	 * Now that we have the target list, 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.
751 752
	 */
	{
753 754 755
		bool		junk_filter_needed = false;
		List	   *tlist;

756
		switch (operation)
757
		{
758 759 760
			case CMD_SELECT:
			case CMD_INSERT:
				foreach(tlist, targetList)
761
				{
762 763 764 765 766 767 768
					TargetEntry *tle = (TargetEntry *) lfirst(tlist);

					if (tle->resdom->resjunk)
					{
						junk_filter_needed = true;
						break;
					}
769
				}
770 771 772 773 774 775 776
				break;
			case CMD_UPDATE:
			case CMD_DELETE:
				junk_filter_needed = true;
				break;
			default:
				break;
777 778
		}

779
		if (junk_filter_needed)
780
		{
781
			JunkFilter *j = ExecInitJunkFilter(targetList, tupType);
782

783
			estate->es_junkFilter = j;
784

785 786 787 788 789 790
			if (operation == CMD_SELECT)
				tupType = j->jf_cleanTupType;
		}
		else
			estate->es_junkFilter = NULL;
	}
791

B
Bruce Momjian 已提交
792
	/*
B
Bruce Momjian 已提交
793
	 * initialize the "into" relation
794 795 796 797 798
	 */
	intoRelationDesc = (Relation) NULL;

	if (operation == CMD_SELECT)
	{
799 800 801
		char	   *intoName;
		Oid			intoRelationId;
		TupleDesc	tupdesc;
802 803 804 805 806 807 808 809 810

		if (!parseTree->isPortal)
		{

			/*
			 * a select into table
			 */
			if (parseTree->into != NULL)
			{
B
Bruce Momjian 已提交
811

B
Bruce Momjian 已提交
812
				/*
B
Bruce Momjian 已提交
813
				 * create the "into" relation
814 815 816 817 818 819 820 821
				 */
				intoName = parseTree->into;

				/*
				 * have to copy tupType to get rid of constraints
				 */
				tupdesc = CreateTupleDescCopy(tupType);

822 823 824 825 826 827
				intoRelationId =
					heap_create_with_catalog(intoName,
											 tupdesc,
											 RELKIND_RELATION,
											 parseTree->isTemp,
											 allowSystemTableMods);
828

829 830
				FreeTupleDesc(tupdesc);

B
Bruce Momjian 已提交
831
				/*
832 833
				 * Advance command counter so that the newly-created
				 * relation's catalog tuples will be visible to heap_open.
834
				 */
835
				CommandCounterIncrement();
836

837 838 839 840 841
				/*
				 * Eventually create a TOAST table for the into relation
				 */
				AlterTableCreateToastTable(intoName, true);

842 843
				intoRelationDesc = heap_open(intoRelationId,
											 AccessExclusiveLock);
844 845 846 847 848 849
			}
		}
	}

	estate->es_into_relation_descriptor = intoRelationDesc;

850 851 852 853 854
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_useEvalPlan = false;

855
	return tupType;
856 857 858
}

/* ----------------------------------------------------------------
859 860 861
 *		EndPlan
 *
 *		Cleans up the query plan -- closes files and free up storages
862 863 864
 * ----------------------------------------------------------------
 */
static void
865
EndPlan(Plan *plan, EState *estate)
866
{
867
	RelationInfo *resultRelationInfo;
868
	List	   *l;
869

870 871 872 873 874 875
	/*
	 * shut down any PlanQual processing we were doing
	 */
	if (estate->es_evalPlanQual != NULL)
		EndEvalPlanQual(estate);

B
Bruce Momjian 已提交
876
	/*
877
	 * shut down the node-type-specific query processing
878 879 880
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
881
	/*
B
Bruce Momjian 已提交
882
	 * destroy the executor "tuple" table.
883
	 */
884 885
	ExecDropTupleTable(estate->es_tupleTable, true);
	estate->es_tupleTable = NULL;
886

B
Bruce Momjian 已提交
887
	/*
888 889 890
	 * close the result relation if necessary, but hold lock on it
	 * until xact commit.  NB: must not do this till after ExecEndNode(),
	 * see nodeAppend.c ...
891
	 */
892
	resultRelationInfo = estate->es_result_relation_info;
893 894
	if (resultRelationInfo != NULL)
	{
895 896
		heap_close(resultRelationInfo->ri_RelationDesc, NoLock);
		/* close indices on the result relation, too */
897 898 899
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
900
	/*
901
	 * close the "into" relation if necessary, again keeping lock
902
	 */
903 904
	if (estate->es_into_relation_descriptor != NULL)
		heap_close(estate->es_into_relation_descriptor, NoLock);
905 906 907 908 909 910 911 912 913 914

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

		heap_close(erm->relation, NoLock);
	}
915 916 917
}

/* ----------------------------------------------------------------
918 919 920 921 922 923 924 925
 *		ExecutePlan
 *
 *		processes the query plan to retrieve 'tupleCount' tuples in the
 *		direction specified.
 *		Retrieves all tuples if tupleCount is 0
 *
 *		result is either a slot containing a tuple in the case
 *		of a RETRIEVE or NULL otherwise.
926 927 928 929 930 931 932 933
 *
 * ----------------------------------------------------------------
 */

/* the ctid attribute is a 'junk' attribute that is removed before the
   user can see it*/

static TupleTableSlot *
934 935
ExecutePlan(EState *estate,
			Plan *plan,
936
			CmdType operation,
937
			int offsetTuples,
938 939
			int numberTuples,
			ScanDirection direction,
940
			DestReceiver *destfunc)
941
{
942
	JunkFilter *junkfilter;
943
	TupleTableSlot *slot;
944
	ItemPointer tupleid = NULL;
945
	ItemPointerData tuple_ctid;
946
	int			current_tuple_count;
947 948
	TupleTableSlot *result;

B
Bruce Momjian 已提交
949
	/*
B
Bruce Momjian 已提交
950
	 * initialize local variables
951
	 */
952 953 954 955
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
956 957
	/*
	 * Set the direction.
958
	 */
959 960
	estate->es_direction = direction;

B
Bruce Momjian 已提交
961
	/*
B
Bruce Momjian 已提交
962 963
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
964 965 966 967
	 */

	for (;;)
	{
B
Bruce Momjian 已提交
968

B
Bruce Momjian 已提交
969
		/*
B
Bruce Momjian 已提交
970
		 * Execute the plan and obtain a tuple
971 972
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
973
lnext:	;
974 975 976 977 978 979 980 981
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
982

B
Bruce Momjian 已提交
983
		/*
B
Bruce Momjian 已提交
984 985
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
986 987 988 989 990
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
991 992
		}

B
Bruce Momjian 已提交
993
		/*
B
Bruce Momjian 已提交
994 995 996
		 * For now we completely execute the plan and skip result tuples
		 * if requested by LIMIT offset. Finally we should try to do it in
		 * deeper levels if possible (during index scan) - Jan
997 998 999 1000 1001 1002 1003
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

B
Bruce Momjian 已提交
1004
		/*
B
Bruce Momjian 已提交
1005 1006
		 * if we have a junk filter, then project a new tuple with the
		 * junk removed.
1007
		 *
B
Bruce Momjian 已提交
1008
		 * Store this new "clean" tuple in the place of the original tuple.
1009
		 *
B
Bruce Momjian 已提交
1010
		 * Also, extract all the junk information we need.
1011 1012 1013
		 */
		if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
		{
1014 1015 1016
			Datum		datum;
			HeapTuple	newTuple;
			bool		isNull;
1017

B
Bruce Momjian 已提交
1018
			/*
1019 1020 1021 1022 1023 1024 1025 1026 1027
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
1028
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1029 1030

				if (isNull)
1031
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1032 1033 1034 1035 1036 1037

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

B
Bruce Momjian 已提交
1042 1043
		lmark:	;
				foreach(l, estate->es_rowMark)
1044
				{
1045 1046 1047 1048 1049 1050
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

1051 1052 1053 1054 1055
					if (!ExecGetJunkAttribute(junkfilter,
											  slot,
											  erm->resname,
											  &datum,
											  &isNull))
1056 1057
						elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
							 erm->resname);
1058 1059

					if (isNull)
1060 1061
						elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
							 erm->resname);
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

					tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
					test = heap_mark4update(erm->relation, &tuple, &buffer);
					ReleaseBuffer(buffer);
					switch (test)
					{
						case HeapTupleSelfUpdated:
						case HeapTupleMayBeUpdated:
							break;

						case HeapTupleUpdated:
							if (XactIsoLevel == XACT_SERIALIZABLE)
1074
							{
1075
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
1076
								return (NULL);
1077
							}
B
Bruce Momjian 已提交
1078 1079
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
1080
							{
B
Bruce Momjian 已提交
1081
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1082 1083 1084 1085 1086 1087 1088
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1089 1090 1091 1092 1093

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
1094 1095
							 */
							goto lnext;
1096 1097 1098

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
1099
							return (NULL);
1100 1101 1102
					}
				}
			}
1103

B
Bruce Momjian 已提交
1104
			/*
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
			 * Finally create a new "clean" tuple with all junk attributes
			 * removed
			 */
			newTuple = ExecRemoveJunk(junkfilter, slot);

			slot = ExecStoreTuple(newTuple,		/* tuple to store */
								  slot, /* destination slot */
								  InvalidBuffer,		/* this tuple has no
														 * buffer */
								  true);		/* tuple should be pfreed */
		}						/* if (junkfilter... */

B
Bruce Momjian 已提交
1117
		/*
B
Bruce Momjian 已提交
1118 1119
		 * 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 已提交
1120
		 * delete it from a relation, or modify some of its attributes.
1121 1122 1123 1124
		 */

		switch (operation)
		{
1125 1126
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1127 1128
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1129 1130 1131
							 estate);	/* */
				result = slot;
				break;
1132

1133 1134 1135 1136
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1137

1138 1139 1140 1141
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1142

1143
			case CMD_UPDATE:
1144
				ExecReplace(slot, tupleid, estate);
1145 1146
				result = NULL;
				break;
1147

1148 1149
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1150
				result = NULL;
1151
				break;
1152
		}
B
Bruce Momjian 已提交
1153

B
Bruce Momjian 已提交
1154
		/*
B
Bruce Momjian 已提交
1155 1156
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1157 1158 1159 1160
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1161
	}
1162

B
Bruce Momjian 已提交
1163
	/*
B
Bruce Momjian 已提交
1164 1165
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1166
	 */
1167
	return result;
1168 1169 1170
}

/* ----------------------------------------------------------------
1171
 *		ExecRetrieve
1172
 *
1173 1174 1175 1176 1177
 *		RETRIEVEs are easy.. we just pass the tuple to the appropriate
 *		print function.  The only complexity is when we do a
 *		"retrieve into", in which case we insert the tuple into
 *		the appropriate relation (note: this is a newly created relation
 *		so we don't need to worry about indices or locks.)
1178 1179 1180
 * ----------------------------------------------------------------
 */
static void
1181
ExecRetrieve(TupleTableSlot *slot,
1182
			 DestReceiver *destfunc,
1183
			 EState *estate)
1184
{
1185 1186
	HeapTuple	tuple;
	TupleDesc	attrtype;
1187

B
Bruce Momjian 已提交
1188
	/*
B
Bruce Momjian 已提交
1189
	 * get the heap tuple out of the tuple table slot
1190 1191 1192 1193
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1194
	/*
B
Bruce Momjian 已提交
1195
	 * insert the tuple into the "into relation"
1196 1197 1198 1199 1200 1201 1202
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1203
	/*
B
Bruce Momjian 已提交
1204
	 * send the tuple to the front end (or the screen)
1205
	 */
1206
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1207 1208
	IncrRetrieved();
	(estate->es_processed)++;
1209 1210 1211
}

/* ----------------------------------------------------------------
1212
 *		ExecAppend
1213
 *
1214 1215 1216
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1217 1218 1219 1220
 * ----------------------------------------------------------------
 */

static void
1221
ExecAppend(TupleTableSlot *slot,
1222
		   ItemPointer tupleid,
1223
		   EState *estate)
1224
{
1225 1226 1227 1228 1229
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1230

B
Bruce Momjian 已提交
1231
	/*
B
Bruce Momjian 已提交
1232
	 * get the heap tuple out of the tuple table slot
1233 1234 1235
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1236
	/*
B
Bruce Momjian 已提交
1237
	 * get information on the result relation
1238 1239 1240 1241 1242 1243 1244 1245
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1246
		HeapTuple	newtuple;
1247 1248 1249 1250 1251 1252 1253 1254 1255

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1256
			heap_freetuple(tuple);
1257 1258 1259 1260
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1261
	/*
1262
	 * Check the constraints of the tuple
1263 1264 1265
	 */

	if (resultRelationDesc->rd_att->constr)
1266
		ExecConstraints("ExecAppend", resultRelationDesc, slot, estate);
1267

B
Bruce Momjian 已提交
1268
	/*
B
Bruce Momjian 已提交
1269
	 * insert the tuple
1270
	 */
1271 1272
	newId = heap_insert(resultRelationDesc, tuple);

1273
	IncrAppended();
1274 1275
	(estate->es_processed)++;
	estate->es_lastoid = newId;
1276

B
Bruce Momjian 已提交
1277
	/*
B
Bruce Momjian 已提交
1278
	 * process indices
1279
	 *
B
Bruce Momjian 已提交
1280 1281 1282
	 * 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.
1283 1284 1285
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1286
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1287 1288

	/* AFTER ROW INSERT Triggers */
1289
	if (resultRelationDesc->trigdesc)
1290
		ExecARInsertTriggers(resultRelationDesc, tuple);
1291 1292 1293
}

/* ----------------------------------------------------------------
1294
 *		ExecDelete
1295
 *
1296 1297
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1298 1299 1300
 * ----------------------------------------------------------------
 */
static void
1301
ExecDelete(TupleTableSlot *slot,
1302
		   ItemPointer tupleid,
1303
		   EState *estate)
1304
{
B
Bruce Momjian 已提交
1305 1306 1307 1308
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1309

B
Bruce Momjian 已提交
1310
	/*
B
Bruce Momjian 已提交
1311
	 * get the result relation information
1312 1313 1314 1315 1316 1317 1318 1319
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

	/* BEFORE ROW DELETE Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
	{
1320
		bool		dodelete;
1321

V
Vadim B. Mikheev 已提交
1322
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1323 1324 1325 1326 1327

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

V
Vadim B. Mikheev 已提交
1328
	/*
B
Bruce Momjian 已提交
1329
	 * delete the tuple
1330
	 */
1331
ldelete:;
V
Vadim B. Mikheev 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1342 1343
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1344 1345
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1346 1347
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1348

V
Vadim B. Mikheev 已提交
1349
				if (!TupIsNull(epqslot))
1350 1351 1352 1353 1354
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1355 1356 1357 1358 1359 1360
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1361 1362 1363 1364

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

B
Bruce Momjian 已提交
1365
	/*
B
Bruce Momjian 已提交
1366 1367
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1368
	 *
B
Bruce Momjian 已提交
1369 1370 1371
	 * ... 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
1372 1373 1374
	 */

	/* AFTER ROW DELETE Triggers */
1375
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1376
		ExecARDeleteTriggers(estate, tupleid);
1377 1378 1379 1380

}

/* ----------------------------------------------------------------
1381
 *		ExecReplace
1382
 *
1383 1384 1385 1386 1387 1388
 *		note: we can't run replace queries with transactions
 *		off because replaces are actually appends and our
 *		scan will mistakenly loop forever, replacing the tuple
 *		it just appended..	This should be fixed but until it
 *		is, we don't want to get stuck in an infinite loop
 *		which corrupts your database..
1389 1390 1391
 * ----------------------------------------------------------------
 */
static void
1392
ExecReplace(TupleTableSlot *slot,
1393
			ItemPointer tupleid,
1394
			EState *estate)
1395
{
B
Bruce Momjian 已提交
1396 1397 1398 1399 1400 1401
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
	int			numIndices;
1402

B
Bruce Momjian 已提交
1403
	/*
B
Bruce Momjian 已提交
1404
	 * abort the operation if not running transactions
1405 1406 1407
	 */
	if (IsBootstrapProcessingMode())
	{
1408
		elog(NOTICE, "ExecReplace: replace can't run without transactions");
1409 1410 1411
		return;
	}

B
Bruce Momjian 已提交
1412
	/*
B
Bruce Momjian 已提交
1413
	 * get the heap tuple out of the tuple table slot
1414 1415 1416
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1417
	/*
B
Bruce Momjian 已提交
1418
	 * get the result relation information
1419 1420 1421 1422 1423 1424 1425 1426
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

	/* BEFORE ROW UPDATE Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
	{
1427
		HeapTuple	newtuple;
1428

V
Vadim B. Mikheev 已提交
1429
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1430 1431 1432 1433 1434 1435 1436

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1437
			heap_freetuple(tuple);
1438 1439 1440 1441
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1442
	/*
1443
	 * Check the constraints of the tuple
1444 1445 1446
	 */

	if (resultRelationDesc->rd_att->constr)
1447
		ExecConstraints("ExecReplace", resultRelationDesc, slot, estate);
1448

V
Vadim B. Mikheev 已提交
1449
	/*
B
Bruce Momjian 已提交
1450
	 * replace the heap tuple
1451
	 */
1452
lreplace:;
1453
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1463 1464
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1465 1466
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1467 1468
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1469

V
Vadim B. Mikheev 已提交
1470
				if (!TupIsNull(epqslot))
1471 1472
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1473 1474
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1475 1476 1477
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1478 1479 1480
			return;

		default:
1481
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1482
			return;
1483 1484 1485 1486 1487
	}

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

B
Bruce Momjian 已提交
1488
	/*
B
Bruce Momjian 已提交
1489 1490
	 * Note: instead of having to update the old index tuples associated
	 * with the heap tuple, all we do is form and insert new index
1491 1492 1493
	 * tuples.  This is because replaces are actually deletes and inserts
	 * and index tuple deletion is done automagically by the vacuum
	 * daemon. All we do is insert new index tuples.  -cim 9/27/89
1494 1495
	 */

B
Bruce Momjian 已提交
1496
	/*
B
Bruce Momjian 已提交
1497
	 * process indices
1498
	 *
1499
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1500 1501 1502 1503
	 * and then appending a new tuple to the relation.	As a side effect,
	 * 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.
1504 1505 1506 1507
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1508
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1509 1510

	/* AFTER ROW UPDATE Triggers */
1511
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1512
		ExecARUpdateTriggers(estate, tupleid, tuple);
1513
}
V
Vadim B. Mikheev 已提交
1514

1515
static char *
1516
ExecRelCheck(Relation rel, TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
1517
{
1518 1519
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
1520
	ExprContext *econtext;
1521
	MemoryContext oldContext;
1522 1523
	List	   *qual;
	int			i;
1524

1525
	/*
1526 1527 1528
	 * We will use the EState's per-tuple context for evaluating constraint
	 * expressions.  Create it if it's not already there; if it is, reset it
	 * to free previously-used storage.
1529
	 */
1530
	econtext = estate->es_per_tuple_exprcontext;
1531
	if (econtext == NULL)
1532 1533 1534 1535 1536 1537
	{
		oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
		estate->es_per_tuple_exprcontext = econtext =
			MakeExprContext(NULL, estate->es_query_cxt);
		MemoryContextSwitchTo(oldContext);
	}
1538 1539
	else
		ResetExprContext(econtext);
1540

1541
	/*
1542 1543
	 * If first time through for current result relation, set up econtext's
	 * range table to refer to result rel, and build expression nodetrees
1544 1545
	 * for rel's constraint expressions.  All this stuff is kept in the
	 * per-query memory context so it will still be here next time through.
1546 1547 1548 1549 1550
	 *
	 * NOTE: if there are multiple result relations (eg, due to inheritance)
	 * then we leak storage for prior rel's expressions and rangetable.
	 * This should not be a big problem as long as result rels are processed
	 * sequentially within a command.
1551
	 */
1552 1553
	if (econtext->ecxt_range_table == NIL ||
		getrelid(1, econtext->ecxt_range_table) != RelationGetRelid(rel))
1554
	{
1555 1556 1557 1558 1559 1560 1561 1562
		RangeTblEntry *rte;

		/*
		 * Make sure expressions, etc are placed in appropriate context.
		 */
		oldContext = MemoryContextSwitchTo(estate->es_query_cxt);

		rte = makeNode(RangeTblEntry);
1563 1564 1565

		rte->relname = RelationGetRelationName(rel);
		rte->relid = RelationGetRelid(rel);
1566 1567
		rte->eref = makeNode(Attr);
		rte->eref->relname = rte->relname;
1568
		/* other fields won't be used, leave them zero */
1569

1570
		/* Set up single-entry range table */
1571
		econtext->ecxt_range_table = makeList1(rte);
1572

1573
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1574
			(List **) palloc(ncheck * sizeof(List *));
1575 1576 1577 1578 1579 1580 1581

		for (i = 0; i < ncheck; i++)
		{
			qual = (List *) stringToNode(check[i].ccbin);
			estate->es_result_relation_constraints[i] = qual;
		}

1582 1583 1584
		/* Done with building long-lived items */
		MemoryContextSwitchTo(oldContext);
	}
1585 1586 1587 1588 1589

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

	/* And evaluate the constraints */
1590 1591
	for (i = 0; i < ncheck; i++)
	{
1592
		qual = estate->es_result_relation_constraints[i];
1593

1594 1595
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
1596 1597
		 * expression is not to be treated as a failure.  Therefore, tell
		 * ExecQual to return TRUE for NULL.
1598
		 */
1599
		if (!ExecQual(qual, econtext, true))
1600
			return check[i].ccname;
1601 1602
	}

1603
	/* NULL result means no error */
1604
	return (char *) NULL;
V
Vadim B. Mikheev 已提交
1605 1606
}

1607
void
1608 1609
ExecConstraints(char *caller, Relation rel,
				TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
1610
{
1611 1612 1613 1614
	HeapTuple	tuple = slot->val;
	TupleConstr *constr = rel->rd_att->constr;

	Assert(constr);
1615

1616
	if (constr->has_not_null)
V
Vadim B. Mikheev 已提交
1617
	{
1618
		int			natts = rel->rd_att->natts;
1619
		int			attrChk;
1620

1621
		for (attrChk = 1; attrChk <= natts; attrChk++)
1622
		{
1623 1624
			if (rel->rd_att->attrs[attrChk-1]->attnotnull &&
				heap_attisnull(tuple, attrChk))
1625
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1626
					 caller, NameStr(rel->rd_att->attrs[attrChk-1]->attname));
1627 1628 1629
		}
	}

1630
	if (constr->num_check > 0)
1631
	{
1632
		char	   *failed;
1633

1634
		if ((failed = ExecRelCheck(rel, slot, estate)) != NULL)
1635 1636
			elog(ERROR, "%s: rejected due to CHECK constraint %s",
				 caller, failed);
1637
	}
V
Vadim B. Mikheev 已提交
1638
}
1639

B
Bruce Momjian 已提交
1640
TupleTableSlot *
1641 1642
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1643 1644 1645 1646 1647 1648 1649
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1650 1651 1652 1653 1654

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1655 1656
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1657 1658 1659 1660 1661 1662
		epq->rti = rti;
		endNode = false;
	}

	/*
	 * If this is request for another RTE - Ra, - then we have to check
B
Bruce Momjian 已提交
1663 1664 1665
	 * 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? -:))
1666
	 */
B
Bruce Momjian 已提交
1667
	if (epq != NULL && epq->rti != rti &&
1668 1669 1670 1671 1672 1673
		epq->estate.es_evTuple[rti - 1] != NULL)
	{
		do
		{
			/* pop previous PlanQual from the stack */
			epqstate = &(epq->estate);
B
Bruce Momjian 已提交
1674
			oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1675 1676 1677
			Assert(oldepq->rti != 0);
			/* stop execution */
			ExecEndNode(epq->plan, epq->plan);
1678
			epqstate->es_tupleTable->next = 0;
1679
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1680 1681 1682 1683 1684 1685 1686 1687
			epqstate->es_evTuple[epq->rti - 1] = NULL;
			/* push current PQ to freePQ stack */
			oldepq->free = epq;
			epq = oldepq;
		} while (epq->rti != rti);
		estate->es_evalPlanQual = (Pointer) epq;
	}

B
Bruce Momjian 已提交
1688
	/*
1689 1690 1691 1692 1693 1694
	 * 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 已提交
1695
		evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1696

1697
		if (newepq == NULL)		/* first call or freePQ stack is empty */
1698
		{
B
Bruce Momjian 已提交
1699
			newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1700 1701 1702
			/* Init EState */
			epqstate = &(newepq->estate);
			memset(epqstate, 0, sizeof(EState));
B
Bruce Momjian 已提交
1703
			epqstate->type = T_EState;
1704 1705 1706 1707 1708 1709
			epqstate->es_direction = ForwardScanDirection;
			epqstate->es_snapshot = estate->es_snapshot;
			epqstate->es_range_table = estate->es_range_table;
			epqstate->es_param_list_info = estate->es_param_list_info;
			if (estate->es_origPlan->nParamExec > 0)
				epqstate->es_param_exec_vals = (ParamExecData *)
B
Bruce Momjian 已提交
1710 1711 1712
					palloc(estate->es_origPlan->nParamExec *
						   sizeof(ParamExecData));
			epqstate->es_tupleTable =
1713 1714 1715 1716
				ExecCreateTupleTable(estate->es_tupleTable->size);
			/* ... rest */
			newepq->plan = copyObject(estate->es_origPlan);
			newepq->free = NULL;
B
Bruce Momjian 已提交
1717
			epqstate->es_evTupleNull = (bool *)
1718 1719
				palloc(length(estate->es_range_table) * sizeof(bool));
			if (epq == NULL)	/* first call */
1720
			{
B
Bruce Momjian 已提交
1721
				epqstate->es_evTuple = (HeapTuple *)
1722
					palloc(length(estate->es_range_table) * sizeof(HeapTuple));
B
Bruce Momjian 已提交
1723 1724
				memset(epqstate->es_evTuple, 0,
					 length(estate->es_range_table) * sizeof(HeapTuple));
1725 1726 1727 1728 1729 1730 1731 1732
			}
			else
				epqstate->es_evTuple = epq->estate.es_evTuple;
		}
		else
			epqstate = &(newepq->estate);
		/* push current PQ to the stack */
		epqstate->es_evalPlanQual = (Pointer) epq;
1733 1734
		epq = newepq;
		estate->es_evalPlanQual = (Pointer) epq;
1735 1736 1737 1738 1739 1740 1741
		epq->rti = rti;
		endNode = false;
	}

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1742 1743
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1744 1745
	 */
	if (endNode)
1746
	{
1747
		ExecEndNode(epq->plan, epq->plan);
1748
		epqstate->es_tupleTable->next = 0;
1749
	}
1750 1751 1752 1753

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1754
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1755 1756 1757 1758
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1759
	if (estate->es_result_relation_info != NULL &&
1760 1761 1762 1763
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1764
		List	   *l;
1765

B
Bruce Momjian 已提交
1766
		foreach(l, estate->es_rowMark)
1767
		{
B
Bruce Momjian 已提交
1768
			if (((execRowMark *) lfirst(l))->rti == rti)
1769 1770
				break;
		}
B
Bruce Momjian 已提交
1771
		relation = ((execRowMark *) lfirst(l))->relation;
1772 1773
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1774
	for (;;)
1775 1776 1777 1778 1779 1780 1781
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1782 1783 1784 1785 1786
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1787

1788
			/*
B
Bruce Momjian 已提交
1789 1790
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1791 1792 1793 1794 1795 1796 1797
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1798

1799 1800 1801
			/*
			 * Nice! We got tuple - now copy it.
			 */
1802
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1803
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1804 1805 1806 1807
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1808

1809 1810
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1811 1812
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1813
		 */
B
Bruce Momjian 已提交
1814
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1815 1816 1817 1818 1819
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1820

1821
		/*
B
Bruce Momjian 已提交
1822 1823
		 * Deleted or updated by this transaction. Do not (re-)start
		 * execution of this PQ. Continue previous PQ.
1824
		 */
B
Bruce Momjian 已提交
1825
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
		if (oldepq != NULL)
		{
			Assert(oldepq->rti != 0);
			/* push current PQ to freePQ stack */
			oldepq->free = epq;
			epq = oldepq;
			epqstate = &(epq->estate);
			estate->es_evalPlanQual = (Pointer) epq;
		}
		else
1836 1837 1838 1839
		{
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free and	  */
			return (NULL);		/* continue Query execution   */
1840 1841 1842 1843
		}
	}

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1844 1845 1846 1847
		memset(epqstate->es_param_exec_vals, 0,
			   estate->es_origPlan->nParamExec * sizeof(ParamExecData));
	memset(epqstate->es_evTupleNull, false,
		   length(estate->es_range_table) * sizeof(bool));
1848
	Assert(epqstate->es_tupleTable->next == 0);
1849 1850 1851
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1852 1853
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1854 1855 1856
	 */
	*tid = tuple.t_self;

1857
	return EvalPlanQualNext(estate);
1858 1859
}

B
Bruce Momjian 已提交
1860
static TupleTableSlot *
1861 1862
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1863 1864 1865 1866
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

	Assert(epq->rti != 0);

lpqnext:;
	slot = ExecProcNode(epq->plan, epq->plan);

	/*
	 * No more tuples for this PQ. Continue previous one.
	 */
	if (TupIsNull(slot))
	{
		ExecEndNode(epq->plan, epq->plan);
1879
		epqstate->es_tupleTable->next = 0;
1880
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1881 1882
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1883 1884
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
1885
		{
1886 1887 1888
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free and	  */
			return (NULL);		/* continue Query execution   */
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
		}
		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);
}
1901 1902 1903 1904 1905 1906 1907 1908

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

1909 1910 1911
	if (epq->rti == 0)			/* plans already shutdowned */
	{
		Assert(epq->estate.es_evalPlanQual == NULL);
1912
		return;
1913
	}
1914 1915 1916 1917

	for (;;)
	{
		ExecEndNode(epq->plan, epq->plan);
1918
		epqstate->es_tupleTable->next = 0;
1919 1920 1921 1922 1923
		if (epqstate->es_evTuple[epq->rti - 1] != NULL)
		{
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
			epqstate->es_evTuple[epq->rti - 1] = NULL;
		}
1924 1925 1926 1927
		/* pop old PQ from the stack */
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
		{
1928 1929
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free */
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
			break;
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
		epqstate = &(epq->estate);
		estate->es_evalPlanQual = (Pointer) epq;
	}
}