execMain.c 49.5 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
30
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.110 2000/03/09 05:15:33 tgl Exp $
31 32 33
 *
 *-------------------------------------------------------------------------
 */
34 35
#include "postgres.h"

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

49 50 51
/* XXX no points for style */
extern TupleTableSlot *EvalPlanQual(EState *estate, Index rti,
									ItemPointer tid);
52 53

/* decls for local routines only used within this module */
54
static TupleDesc InitPlan(CmdType operation,
B
Bruce Momjian 已提交
55 56 57
		 Query *parseTree,
		 Plan *plan,
		 EState *estate);
58
static void EndPlan(Plan *plan,
B
Bruce Momjian 已提交
59
		EState *estate);
60
static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
B
Bruce Momjian 已提交
61 62 63 64
			CmdType operation,
			int offsetTuples,
			int numberTuples,
			ScanDirection direction,
65
			DestReceiver *destfunc);
66
static void ExecRetrieve(TupleTableSlot *slot,
67
			 DestReceiver *destfunc,
B
Bruce Momjian 已提交
68
			 EState *estate);
69
static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
70
		   EState *estate);
71
static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
72
		   EState *estate);
73
static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
74
			EState *estate);
75
static TupleTableSlot *EvalPlanQualNext(EState *estate);
76 77 78 79 80 81 82 83
static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
								Plan *plan);
static void ExecCheckPlanPerms(Plan *plan, CmdType operation,
							   int resultRelation, bool resultIsScanned);
static void ExecCheckRTPerms(List *rangeTable, CmdType operation,
							 int resultRelation, bool resultIsScanned);
static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation,
							  bool isResultRelation, bool resultIsScanned);
84 85
/* end of local decls */

86

87
/* ----------------------------------------------------------------
88 89 90 91 92 93 94
 *		ExecutorStart
 *
 *		This routine must be called at the beginning of any execution of any
 *		query plan
 *
 *		returns (AttrInfo*) which describes the attributes of the tuples to
 *		be returned by the query.
95 96 97 98
 *
 * ----------------------------------------------------------------
 */
TupleDesc
99
ExecutorStart(QueryDesc *queryDesc, EState *estate)
100
{
101
	TupleDesc	result;
102 103 104

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

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

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

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

	return result;
140 141 142
}

/* ----------------------------------------------------------------
143 144 145 146 147 148 149
 *		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.
150
 *
151 152 153 154 155 156
 *		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
157 158 159 160
 *
 *
 * ----------------------------------------------------------------
 */
161
TupleTableSlot *
B
Bruce Momjian 已提交
162 163
ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature,
			Node *limoffset, Node *limcount)
164
{
B
Bruce Momjian 已提交
165 166
	CmdType		operation;
	Plan	   *plan;
167
	TupleTableSlot *result;
B
Bruce Momjian 已提交
168 169 170 171
	CommandDest dest;
	DestReceiver *destfunc;
	int			offset = 0;
	int			count = 0;
172

B
Bruce Momjian 已提交
173
	/*
B
Bruce Momjian 已提交
174
	 * sanity checks
175
	 */
176 177
	Assert(queryDesc != NULL);

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;
	plan = queryDesc->plantree;
	dest = queryDesc->dest;
185
	destfunc = DestToFunction(dest);
186 187 188
	estate->es_processed = 0;
	estate->es_lastoid = InvalidOid;

B
Bruce Momjian 已提交
189
	/*
B
Bruce Momjian 已提交
190 191 192 193
	 * 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.
194 195 196
	 */
	(*destfunc->setup) (destfunc, (TupleDesc) NULL);

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

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

214
			case T_Param:
B
Bruce Momjian 已提交
215
				poffset = (Param *) limoffset;
216
				paramLI = estate->es_param_list_info;
B
Bruce Momjian 已提交
217

218 219 220 221 222 223 224 225 226 227 228
				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 已提交
229 230
				offset = (int) (paramLI[i].value);

231
				break;
B
Bruce Momjian 已提交
232

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

237 238 239
		if (offset < 0)
			elog(ERROR, "limit offset cannot be negative");
	}
B
Bruce Momjian 已提交
240

B
Bruce Momjian 已提交
241
	/*
B
Bruce Momjian 已提交
242
	 * if given get the count of the LIMIT clause
243 244 245
	 */
	if (limcount != NULL)
	{
B
Bruce Momjian 已提交
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 280 281 282
		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");
283 284
	}

285 286 287
	switch (feature)
	{

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

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

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

339 340
	(*destfunc->cleanup) (destfunc);

341
	return result;
342 343 344
}

/* ----------------------------------------------------------------
345 346 347 348 349 350 351
 *		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.
352 353 354 355
 *
 * ----------------------------------------------------------------
 */
void
356
ExecutorEnd(QueryDesc *queryDesc, EState *estate)
357
{
358 359
	/* sanity checks */
	Assert(queryDesc != NULL);
360

361
	EndPlan(queryDesc->plantree, estate);
362

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

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

386 387 388 389 390 391 392

/*
 * ExecCheckQueryPerms
 *		Check access permissions for all relations referenced in a query.
 */
static void
ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
393
{
394 395 396
	List	   *rangeTable = parseTree->rtable;
	int			resultRelation = parseTree->resultRelation;
	bool		resultIsScanned = false;
397
	List	   *lp;
398

399 400 401 402 403 404 405 406 407
	/*
	 * If we have a result relation, determine whether the result rel is
	 * scanned or merely written.  If scanned, we will insist on read
	 * permission as well as modify permission.
	 */
	if (resultRelation > 0)
	{
		List	   *qvars = pull_varnos(parseTree->qual);
		List	   *tvars = pull_varnos((Node *) parseTree->targetList);
408

409 410 411 412 413
		resultIsScanned = (intMember(resultRelation, qvars) ||
						   intMember(resultRelation, tvars));
		freeList(qvars);
		freeList(tvars);
	}
414

415 416 417 418 419 420 421 422 423
	/*
	 * Check RTEs in the query's primary rangetable.
	 */
	ExecCheckRTPerms(rangeTable, operation, resultRelation, resultIsScanned);

	/*
	 * Check SELECT FOR UPDATE access rights.
	 */
	foreach(lp, parseTree->rowMark)
424
	{
425
		RowMark    *rm = lfirst(lp);
426

427 428
		if (!(rm->info & ROW_ACL_FOR_UPDATE))
			continue;
429

430 431 432
		ExecCheckRTEPerms(rt_fetch(rm->rti, rangeTable),
						  CMD_UPDATE, true, false);
	}
433

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
	/*
	 * Search for subplans and APPEND nodes to check their rangetables.
	 */
	ExecCheckPlanPerms(plan, operation, resultRelation, resultIsScanned);
}

/*
 * 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
ExecCheckPlanPerms(Plan *plan, CmdType operation,
				   int resultRelation, bool resultIsScanned)
{
	List	   *subp;

	if (plan == NULL)
		return;

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

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

		ExecCheckRTPerms(subplan->rtable, CMD_SELECT, 0, false);
		ExecCheckPlanPerms(subplan->plan, CMD_SELECT, 0, false);
	}
	foreach(subp, plan->subPlan)
	{
		SubPlan	   *subplan = (SubPlan *) lfirst(subp);
M
Marc G. Fournier 已提交
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		ExecCheckRTPerms(subplan->rtable, CMD_SELECT, 0, false);
		ExecCheckPlanPerms(subplan->plan, CMD_SELECT, 0, false);
	}

	/* Check lower plan nodes */

	ExecCheckPlanPerms(plan->lefttree, operation,
					   resultRelation, resultIsScanned);
	ExecCheckPlanPerms(plan->righttree, operation,
					   resultRelation, resultIsScanned);

	/* Do node-type-specific checks */

	switch (nodeTag(plan))
	{
		case T_Append:
		{
			Append	   *app = (Append *) plan;
			List	   *appendplans;

			if (app->inheritrelid > 0)
492
			{
493 494 495 496 497 498 499 500 501 502 503 504 505 506
				/*
				 * Append implements expansion of inheritance; all members
				 * of inheritrtable list will be plugged into same RTE slot.
				 * Therefore, they are either all result relations or none.
				 */
				List	   *rtable;

				foreach(rtable, app->inheritrtable)
				{
					ExecCheckRTEPerms((RangeTblEntry *) lfirst(rtable),
									  operation,
									  (app->inheritrelid == resultRelation),
									  resultIsScanned);
				}
507
			}
508
			else
509
			{
510 511 512 513 514 515 516 517
				/* Append implements UNION, which must be a SELECT */
				List	   *rtables;

				foreach(rtables, app->unionrtables)
				{
					ExecCheckRTPerms((List *) lfirst(rtables),
									 CMD_SELECT, 0, false);
				}
518
			}
519 520 521 522 523 524 525 526 527 528

			/* Check appended plans */
			foreach(appendplans, app->appendplans)
			{
				ExecCheckPlanPerms((Plan *) lfirst(appendplans),
								   operation,
								   resultRelation,
								   resultIsScanned);
			}
			break;
529
		}
530 531

		default:
532
			break;
533
	}
534
}
535

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
/*
 * ExecCheckRTPerms
 *		Check access permissions for all relations listed in a range table.
 *
 * If resultRelation is not 0, it is the RT index of the relation to be
 * treated as the result relation.  All other relations are assumed to be
 * read-only for the query.
 */
static void
ExecCheckRTPerms(List *rangeTable, CmdType operation,
				 int resultRelation, bool resultIsScanned)
{
	int			rtindex = 0;
	List	   *lp;

	foreach(lp, rangeTable)
552
	{
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
		RangeTblEntry *rte = lfirst(lp);

		++rtindex;

		ExecCheckRTEPerms(rte,
						  operation,
						  (rtindex == resultRelation),
						  resultIsScanned);
	}
}

/*
 * ExecCheckRTEPerms
 *		Check access permissions for a single RTE.
 */
static void
ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation,
				  bool isResultRelation, bool resultIsScanned)
{
	char	   *relName;
	char	   *userName;
	int32		aclcheck_result;

	if (rte->skipAcl)
	{
		/*
		 * This happens if the access to this table is due to a view
		 * query rewriting - the rewrite handler already checked the
		 * permissions against the view owner, so we just skip this entry.
		 */
		return;
	}

	relName = rte->relname;

	/*
	 * Note: GetPgUserName is presently fast enough that there's no harm
	 * in calling it separately for each RTE.  If that stops being true,
	 * we could call it once in ExecCheckQueryPerms and pass the userName
	 * down from there.  But for now, no need for the extra clutter.
	 */
	userName = GetPgUserName();
595

596
#define CHECK(MODE)		pg_aclcheck(relName, userName, MODE)
597

598 599 600 601 602 603 604 605
	if (isResultRelation)
	{
		if (resultIsScanned)
		{
			aclcheck_result = CHECK(ACL_RD);
			if (aclcheck_result != ACLCHECK_OK)
				elog(ERROR, "%s: %s",
					 relName, aclcheck_error_strings[aclcheck_result]);
606
		}
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
		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;
			case CMD_DELETE:
			case CMD_UPDATE:
				aclcheck_result = CHECK(ACL_WR);
				break;
			default:
				elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
					 operation);
				aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
				break;
		}
	}
	else
	{
		aclcheck_result = CHECK(ACL_RD);
629
	}
630 631 632 633

	if (aclcheck_result != ACLCHECK_OK)
		elog(ERROR, "%s: %s",
			 relName, aclcheck_error_strings[aclcheck_result]);
634 635
}

636

637 638 639 640 641 642 643
/* ===============================================================
 * ===============================================================
						 static routines follow
 * ===============================================================
 * ===============================================================
 */

644 645 646
typedef struct execRowMark
{
	Relation	relation;
647
	Index		rti;
648
	char		resname[32];
649
} execRowMark;
650

651 652
typedef struct evalPlanQual
{
B
Bruce Momjian 已提交
653 654 655 656
	Plan	   *plan;
	Index		rti;
	EState		estate;
	struct evalPlanQual *free;
657
} evalPlanQual;
658

659
/* ----------------------------------------------------------------
660 661 662 663
 *		InitPlan
 *
 *		Initializes the query plan: open files, allocate storage
 *		and start up the rule manager
664 665
 * ----------------------------------------------------------------
 */
666
static TupleDesc
667
InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
668
{
B
Bruce Momjian 已提交
669 670 671 672 673
	List	   *rangeTable;
	int			resultRelation;
	Relation	intoRelationDesc;
	TupleDesc	tupType;
	List	   *targetList;
674

675 676 677 678 679 680 681
	/*
	 * Do permissions checks.
	 */
#ifndef NO_SECURITY
	ExecCheckQueryPerms(operation, parseTree, plan);
#endif

B
Bruce Momjian 已提交
682
	/*
B
Bruce Momjian 已提交
683
	 * get information from query descriptor
684
	 */
685 686
	rangeTable = parseTree->rtable;
	resultRelation = parseTree->resultRelation;
687

B
Bruce Momjian 已提交
688
	/*
B
Bruce Momjian 已提交
689
	 * initialize the node's execution state
690
	 */
691 692
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
693
	/*
B
Bruce Momjian 已提交
694 695 696
	 * initialize the BaseId counter so node base_id's are assigned
	 * correctly.  Someday baseid's will have to be stored someplace other
	 * than estate because they should be unique per query planned.
697
	 */
698
	estate->es_BaseId = 1;
699

B
Bruce Momjian 已提交
700
	/*
B
Bruce Momjian 已提交
701
	 * initialize result relation stuff
702
	 */
B
Bruce Momjian 已提交
703

704 705
	if (resultRelation != 0 && operation != CMD_SELECT)
	{
B
Bruce Momjian 已提交
706

B
Bruce Momjian 已提交
707
		/*
B
Bruce Momjian 已提交
708 709
		 * if we have a result relation, open it and initialize the result
		 * relation info stuff.
710
		 */
711 712 713 714 715
		RelationInfo *resultRelationInfo;
		Index		resultRelationIndex;
		RangeTblEntry *rtentry;
		Oid			resultRelationOid;
		Relation	resultRelationDesc;
716 717 718 719

		resultRelationIndex = resultRelation;
		rtentry = rt_fetch(resultRelationIndex, rangeTable);
		resultRelationOid = rtentry->relid;
720
		resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
721 722

		if (resultRelationDesc->rd_rel->relkind == RELKIND_SEQUENCE)
723
			elog(ERROR, "You can't change sequence relation %s",
724
				 RelationGetRelationName(resultRelationDesc));
725 726 727 728 729 730 731

		resultRelationInfo = makeNode(RelationInfo);
		resultRelationInfo->ri_RangeTableIndex = resultRelationIndex;
		resultRelationInfo->ri_RelationDesc = resultRelationDesc;
		resultRelationInfo->ri_NumIndices = 0;
		resultRelationInfo->ri_IndexRelationDescs = NULL;
		resultRelationInfo->ri_IndexRelationInfo = NULL;
732

B
Bruce Momjian 已提交
733
		/*
734 735 736 737
		 * If there are indices on the result relation, open them and save
		 * descriptors in the result relation info, so that we can add new
		 * index entries for the tuples we add/update.  We need not do this
		 * for a DELETE, however, since deletion doesn't affect indexes.
738
		 */
739 740
		if (resultRelationDesc->rd_rel->relhasindex &&
			operation != CMD_DELETE)
V
Vadim B. Mikheev 已提交
741
			ExecOpenIndices(resultRelationOid, resultRelationInfo);
742 743

		estate->es_result_relation_info = resultRelationInfo;
744
	}
745 746
	else
	{
B
Bruce Momjian 已提交
747

B
Bruce Momjian 已提交
748
		/*
B
Bruce Momjian 已提交
749
		 * if no result relation, then set state appropriately
750 751 752 753
		 */
		estate->es_result_relation_info = NULL;
	}

754 755 756 757 758 759
	/*
	 * Have to lock relations selected for update
	 */
	estate->es_rowMark = NULL;
	if (parseTree->rowMark != NULL)
	{
B
Bruce Momjian 已提交
760
		List	   *l;
761 762 763

		foreach(l, parseTree->rowMark)
		{
764 765 766 767 768
			RowMark    *rm = lfirst(l);
			Oid			relid;
			Relation	relation;
			execRowMark *erm;

769 770
			if (!(rm->info & ROW_MARK_FOR_UPDATE))
				continue;
771 772
			relid = rt_fetch(rm->rti, rangeTable)->relid;
			relation = heap_open(relid, RowShareLock);
B
Bruce Momjian 已提交
773
			erm = (execRowMark *) palloc(sizeof(execRowMark));
774
			erm->relation = relation;
775
			erm->rti = rm->rti;
776 777 778 779
			sprintf(erm->resname, "ctid%u", rm->rti);
			estate->es_rowMark = lappend(estate->es_rowMark, erm);
		}
	}
780

B
Bruce Momjian 已提交
781
	/*
B
Bruce Momjian 已提交
782
	 * initialize the executor "tuple" table.
783 784
	 */
	{
785 786
		int			nSlots = ExecCountSlotsNode(plan);
		TupleTable	tupleTable = ExecCreateTupleTable(nSlots + 10);		/* why add ten? - jolly */
787

788 789
		estate->es_tupleTable = tupleTable;
	}
790

B
Bruce Momjian 已提交
791
	/*
B
Bruce Momjian 已提交
792 793 794
	 * initialize the private state information for all the nodes in the
	 * query tree.	This opens files, allocates storage and leaves us
	 * ready to start processing tuples..
795 796 797
	 */
	ExecInitNode(plan, estate, NULL);

B
Bruce Momjian 已提交
798
	/*
B
Bruce Momjian 已提交
799 800 801
	 * get the tuple descriptor describing the type of tuples to return..
	 * (this is especially important if we are creating a relation with
	 * "retrieve into")
802 803 804 805
	 */
	tupType = ExecGetTupType(plan);		/* tuple descriptor */
	targetList = plan->targetlist;

B
Bruce Momjian 已提交
806
	/*
807 808 809 810
	 * 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.
811 812
	 */
	{
813 814 815
		bool		junk_filter_needed = false;
		List	   *tlist;

816
		switch (operation)
817
		{
818 819 820
			case CMD_SELECT:
			case CMD_INSERT:
				foreach(tlist, targetList)
821
				{
822 823 824 825 826 827 828
					TargetEntry *tle = (TargetEntry *) lfirst(tlist);

					if (tle->resdom->resjunk)
					{
						junk_filter_needed = true;
						break;
					}
829
				}
830 831 832 833 834 835 836
				break;
			case CMD_UPDATE:
			case CMD_DELETE:
				junk_filter_needed = true;
				break;
			default:
				break;
837 838
		}

839
		if (junk_filter_needed)
840
		{
841
			JunkFilter *j = ExecInitJunkFilter(targetList, tupType);
842

843
			estate->es_junkFilter = j;
844

845 846 847 848 849 850
			if (operation == CMD_SELECT)
				tupType = j->jf_cleanTupType;
		}
		else
			estate->es_junkFilter = NULL;
	}
851

B
Bruce Momjian 已提交
852
	/*
B
Bruce Momjian 已提交
853
	 * initialize the "into" relation
854 855 856 857 858
	 */
	intoRelationDesc = (Relation) NULL;

	if (operation == CMD_SELECT)
	{
859 860 861
		char	   *intoName;
		Oid			intoRelationId;
		TupleDesc	tupdesc;
862 863 864 865 866 867 868 869 870

		if (!parseTree->isPortal)
		{

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

B
Bruce Momjian 已提交
872
				/*
B
Bruce Momjian 已提交
873
				 * create the "into" relation
874 875 876 877 878 879 880 881
				 */
				intoName = parseTree->into;

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

882
				intoRelationId = heap_create_with_catalog(intoName,
B
Bruce Momjian 已提交
883
						   tupdesc, RELKIND_RELATION, parseTree->isTemp);
884

885 886
				FreeTupleDesc(tupdesc);

B
Bruce Momjian 已提交
887
				/*
888 889
				 * Advance command counter so that the newly-created
				 * relation's catalog tuples will be visible to heap_open.
890
				 */
891
				CommandCounterIncrement();
892

893 894
				intoRelationDesc = heap_open(intoRelationId,
											 AccessExclusiveLock);
895 896 897 898 899 900
			}
		}
	}

	estate->es_into_relation_descriptor = intoRelationDesc;

901 902 903 904 905
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_useEvalPlan = false;

906
	return tupType;
907 908 909
}

/* ----------------------------------------------------------------
910 911 912
 *		EndPlan
 *
 *		Cleans up the query plan -- closes files and free up storages
913 914 915
 * ----------------------------------------------------------------
 */
static void
916
EndPlan(Plan *plan, EState *estate)
917
{
918 919
	RelationInfo *resultRelationInfo;
	Relation	intoRelationDesc;
920
	List	   *l;
921

B
Bruce Momjian 已提交
922
	/*
B
Bruce Momjian 已提交
923
	 * get information from state
924
	 */
925 926 927
	resultRelationInfo = estate->es_result_relation_info;
	intoRelationDesc = estate->es_into_relation_descriptor;

B
Bruce Momjian 已提交
928
	/*
B
Bruce Momjian 已提交
929
	 * shut down the query
930 931 932
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
933
	/*
B
Bruce Momjian 已提交
934
	 * destroy the executor "tuple" table.
935 936
	 */
	{
937
		TupleTable	tupleTable = (TupleTable) estate->es_tupleTable;
938

939
		ExecDropTupleTable(tupleTable, true);
940 941 942
		estate->es_tupleTable = NULL;
	}

B
Bruce Momjian 已提交
943
	/*
944 945
	 * close the result relations if necessary,
	 * but hold locks on them until xact commit
946 947 948
	 */
	if (resultRelationInfo != NULL)
	{
949
		Relation	resultRelationDesc;
950 951

		resultRelationDesc = resultRelationInfo->ri_RelationDesc;
952
		heap_close(resultRelationDesc, NoLock);
953

B
Bruce Momjian 已提交
954
		/*
B
Bruce Momjian 已提交
955
		 * close indices on the result relation
956 957 958 959
		 */
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
960
	/*
961
	 * close the "into" relation if necessary, again keeping lock
962 963
	 */
	if (intoRelationDesc != NULL)
964
		heap_close(intoRelationDesc, NoLock);
965 966 967 968 969 970 971 972 973 974

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

		heap_close(erm->relation, NoLock);
	}
975 976 977
}

/* ----------------------------------------------------------------
978 979 980 981 982 983 984 985
 *		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.
986 987 988 989 990 991 992 993
 *
 * ----------------------------------------------------------------
 */

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

static TupleTableSlot *
994 995
ExecutePlan(EState *estate,
			Plan *plan,
996
			CmdType operation,
997
			int offsetTuples,
998 999
			int numberTuples,
			ScanDirection direction,
1000
			DestReceiver *destfunc)
1001
{
1002
	JunkFilter *junkfilter;
1003
	TupleTableSlot *slot;
1004
	ItemPointer tupleid = NULL;
1005
	ItemPointerData tuple_ctid;
1006
	int			current_tuple_count;
1007 1008
	TupleTableSlot *result;

B
Bruce Momjian 已提交
1009
	/*
B
Bruce Momjian 已提交
1010
	 * initialize local variables
1011
	 */
1012 1013 1014 1015
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
1016 1017
	/*
	 * Set the direction.
1018
	 */
1019 1020
	estate->es_direction = direction;

B
Bruce Momjian 已提交
1021
	/*
B
Bruce Momjian 已提交
1022 1023
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
1024 1025 1026 1027
	 */

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

B
Bruce Momjian 已提交
1029
		/*
B
Bruce Momjian 已提交
1030
		 * Execute the plan and obtain a tuple
1031 1032
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
1033
lnext:	;
1034 1035 1036 1037 1038 1039 1040 1041
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
1042

B
Bruce Momjian 已提交
1043
		/*
B
Bruce Momjian 已提交
1044 1045
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
1046 1047 1048 1049 1050
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
1051 1052
		}

B
Bruce Momjian 已提交
1053
		/*
B
Bruce Momjian 已提交
1054 1055 1056
		 * 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
1057 1058 1059 1060 1061 1062 1063
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

B
Bruce Momjian 已提交
1064
		/*
B
Bruce Momjian 已提交
1065 1066
		 * if we have a junk filter, then project a new tuple with the
		 * junk removed.
1067
		 *
B
Bruce Momjian 已提交
1068
		 * Store this new "clean" tuple in the place of the original tuple.
1069
		 *
B
Bruce Momjian 已提交
1070
		 * Also, extract all the junk information we need.
1071 1072 1073
		 */
		if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
		{
1074 1075 1076
			Datum		datum;
			HeapTuple	newTuple;
			bool		isNull;
1077

B
Bruce Momjian 已提交
1078
			/*
1079 1080 1081 1082 1083 1084 1085 1086 1087
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
1088
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1089 1090

				if (isNull)
1091
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1092 1093 1094 1095 1096 1097

				tupleid = (ItemPointer) DatumGetPointer(datum);
				tuple_ctid = *tupleid;	/* make sure we don't free the
										 * ctid!! */
				tupleid = &tuple_ctid;
			}
1098 1099
			else if (estate->es_rowMark != NULL)
			{
B
Bruce Momjian 已提交
1100
				List	   *l;
1101

B
Bruce Momjian 已提交
1102 1103
		lmark:	;
				foreach(l, estate->es_rowMark)
1104
				{
1105 1106 1107 1108 1109 1110
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
					if (!ExecGetJunkAttribute(junkfilter,
											  slot,
											  erm->resname,
											  &datum,
											  &isNull))
						elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!", erm->resname);

					if (isNull)
						elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!", erm->resname);

					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)
1132
							{
1133
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
1134
								return (NULL);
1135
							}
B
Bruce Momjian 已提交
1136 1137
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
1138
							{
B
Bruce Momjian 已提交
1139
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1140 1141 1142 1143 1144 1145 1146
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1147 1148 1149 1150 1151

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
1152 1153
							 */
							goto lnext;
1154 1155 1156

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
1157
							return (NULL);
1158 1159 1160
					}
				}
			}
1161

B
Bruce Momjian 已提交
1162
			/*
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
			 * 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 已提交
1175
		/*
B
Bruce Momjian 已提交
1176 1177
		 * 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 已提交
1178
		 * delete it from a relation, or modify some of its attributes.
1179 1180 1181 1182
		 */

		switch (operation)
		{
1183 1184
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1185 1186
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1187 1188 1189
							 estate);	/* */
				result = slot;
				break;
1190

1191 1192 1193 1194
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1195

1196 1197 1198 1199
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1200

1201
			case CMD_UPDATE:
1202
				ExecReplace(slot, tupleid, estate);
1203 1204
				result = NULL;
				break;
1205

1206 1207
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1208
				result = NULL;
1209
				break;
1210
		}
B
Bruce Momjian 已提交
1211

B
Bruce Momjian 已提交
1212
		/*
B
Bruce Momjian 已提交
1213 1214
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1215 1216 1217 1218
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1219
	}
1220

B
Bruce Momjian 已提交
1221
	/*
B
Bruce Momjian 已提交
1222 1223
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1224
	 */
1225
	return result;
1226 1227 1228
}

/* ----------------------------------------------------------------
1229
 *		ExecRetrieve
1230
 *
1231 1232 1233 1234 1235
 *		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.)
1236 1237 1238
 * ----------------------------------------------------------------
 */
static void
1239
ExecRetrieve(TupleTableSlot *slot,
1240
			 DestReceiver *destfunc,
1241
			 EState *estate)
1242
{
1243 1244
	HeapTuple	tuple;
	TupleDesc	attrtype;
1245

B
Bruce Momjian 已提交
1246
	/*
B
Bruce Momjian 已提交
1247
	 * get the heap tuple out of the tuple table slot
1248 1249 1250 1251
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1252
	/*
B
Bruce Momjian 已提交
1253
	 * insert the tuple into the "into relation"
1254 1255 1256 1257 1258 1259 1260
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1261
	/*
B
Bruce Momjian 已提交
1262
	 * send the tuple to the front end (or the screen)
1263
	 */
1264
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1265 1266
	IncrRetrieved();
	(estate->es_processed)++;
1267 1268 1269
}

/* ----------------------------------------------------------------
1270
 *		ExecAppend
1271
 *
1272 1273 1274
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1275 1276 1277 1278
 * ----------------------------------------------------------------
 */

static void
1279
ExecAppend(TupleTableSlot *slot,
1280
		   ItemPointer tupleid,
1281
		   EState *estate)
1282
{
1283 1284 1285 1286 1287
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1288

B
Bruce Momjian 已提交
1289
	/*
B
Bruce Momjian 已提交
1290
	 * get the heap tuple out of the tuple table slot
1291 1292 1293
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1294
	/*
B
Bruce Momjian 已提交
1295
	 * get information on the result relation
1296 1297 1298 1299
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1300
	/*
B
Bruce Momjian 已提交
1301
	 * have to add code to preform unique checking here. cim -12/1/89
1302 1303 1304 1305 1306 1307
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1308
		HeapTuple	newtuple;
1309 1310 1311 1312 1313 1314 1315 1316 1317

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1318
			heap_freetuple(tuple);
1319 1320 1321 1322
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1323
	/*
1324 1325 1326 1327
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1328
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1329

B
Bruce Momjian 已提交
1330
	/*
B
Bruce Momjian 已提交
1331
	 * insert the tuple
1332 1333 1334 1335 1336
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

B
Bruce Momjian 已提交
1337
	/*
B
Bruce Momjian 已提交
1338
	 * process indices
1339
	 *
B
Bruce Momjian 已提交
1340 1341 1342
	 * 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.
1343 1344 1345
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1346
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1347 1348 1349 1350
	(estate->es_processed)++;
	estate->es_lastoid = newId;

	/* AFTER ROW INSERT Triggers */
1351
	if (resultRelationDesc->trigdesc)
1352
		ExecARInsertTriggers(resultRelationDesc, tuple);
1353 1354 1355
}

/* ----------------------------------------------------------------
1356
 *		ExecDelete
1357
 *
1358 1359
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1360 1361 1362
 * ----------------------------------------------------------------
 */
static void
1363
ExecDelete(TupleTableSlot *slot,
1364
		   ItemPointer tupleid,
1365
		   EState *estate)
1366
{
B
Bruce Momjian 已提交
1367 1368 1369 1370
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1371

B
Bruce Momjian 已提交
1372
	/*
B
Bruce Momjian 已提交
1373
	 * get the result relation information
1374 1375 1376 1377 1378 1379 1380 1381
	 */
	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)
	{
1382
		bool		dodelete;
1383

V
Vadim B. Mikheev 已提交
1384
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1385 1386 1387 1388 1389

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

V
Vadim B. Mikheev 已提交
1390
	/*
B
Bruce Momjian 已提交
1391
	 * delete the tuple
1392
	 */
1393
ldelete:;
V
Vadim B. Mikheev 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1404 1405
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1406 1407
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1408 1409
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1410

V
Vadim B. Mikheev 已提交
1411
				if (!TupIsNull(epqslot))
1412 1413 1414 1415 1416
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1417 1418 1419 1420 1421 1422
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1423 1424 1425 1426

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

B
Bruce Momjian 已提交
1427
	/*
B
Bruce Momjian 已提交
1428 1429
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1430
	 *
B
Bruce Momjian 已提交
1431 1432 1433
	 * ... 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
1434 1435 1436
	 */

	/* AFTER ROW DELETE Triggers */
1437
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1438
		ExecARDeleteTriggers(estate, tupleid);
1439 1440 1441 1442

}

/* ----------------------------------------------------------------
1443
 *		ExecReplace
1444
 *
1445 1446 1447 1448 1449 1450
 *		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..
1451 1452 1453
 * ----------------------------------------------------------------
 */
static void
1454
ExecReplace(TupleTableSlot *slot,
1455
			ItemPointer tupleid,
1456
			EState *estate)
1457
{
B
Bruce Momjian 已提交
1458 1459 1460 1461 1462 1463
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
	int			numIndices;
1464

B
Bruce Momjian 已提交
1465
	/*
B
Bruce Momjian 已提交
1466
	 * abort the operation if not running transactions
1467 1468 1469 1470 1471 1472 1473
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1474
	/*
B
Bruce Momjian 已提交
1475
	 * get the heap tuple out of the tuple table slot
1476 1477 1478
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1479
	/*
B
Bruce Momjian 已提交
1480
	 * get the result relation information
1481 1482 1483 1484
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1485
	/*
B
Bruce Momjian 已提交
1486 1487 1488
	 * have to add code to preform unique checking here. in the event of
	 * unique tuples, this becomes a deletion of the original tuple
	 * affected by the replace. cim -12/1/89
1489 1490 1491 1492 1493 1494
	 */

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

V
Vadim B. Mikheev 已提交
1497
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1498 1499 1500 1501 1502 1503 1504

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1505
			heap_freetuple(tuple);
1506 1507 1508 1509
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1510
	/*
1511 1512 1513 1514
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1515
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1516

V
Vadim B. Mikheev 已提交
1517
	/*
B
Bruce Momjian 已提交
1518
	 * replace the heap tuple
1519
	 */
1520
lreplace:;
1521
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1531 1532
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1533 1534
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1535 1536
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1537

V
Vadim B. Mikheev 已提交
1538
				if (!TupIsNull(epqslot))
1539 1540
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1541 1542
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1543 1544 1545
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1546 1547 1548
			return;

		default:
1549
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1550
			return;
1551 1552 1553 1554 1555
	}

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

B
Bruce Momjian 已提交
1556
	/*
B
Bruce Momjian 已提交
1557 1558 1559 1560 1561
	 * Note: instead of having to update the old index tuples associated
	 * with the heap tuple, all we do is form and insert new index
	 * tuples..  This is because replaces are actually deletes and inserts
	 * and index tuple deletion is done automagically by the vaccuum
	 * deamon.. All we do is insert new index tuples.  -cim 9/27/89
1562 1563
	 */

B
Bruce Momjian 已提交
1564
	/*
B
Bruce Momjian 已提交
1565
	 * process indices
1566
	 *
1567
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1568 1569 1570 1571
	 * 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.
1572 1573 1574 1575
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1576
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1577 1578

	/* AFTER ROW UPDATE Triggers */
1579
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1580
		ExecARUpdateTriggers(estate, tupleid, tuple);
1581
}
V
Vadim B. Mikheev 已提交
1582

M
 
Marc G. Fournier 已提交
1583
#ifdef NOT_USED
1584
static HeapTuple
1585
ExecAttrDefault(Relation rel, HeapTuple tuple)
V
Vadim B. Mikheev 已提交
1586
{
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
	int			ndef = rel->rd_att->constr->num_defval;
	AttrDefault *attrdef = rel->rd_att->constr->defval;
	ExprContext *econtext = makeNode(ExprContext);
	HeapTuple	newtuple;
	Node	   *expr;
	bool		isnull;
	bool		isdone;
	Datum		val;
	Datum	   *replValue = NULL;
	char	   *replNull = NULL;
	char	   *repl = NULL;
	int			i;
1599 1600 1601 1602 1603 1604

	econtext->ecxt_scantuple = NULL;	/* scan tuple slot */
	econtext->ecxt_innertuple = NULL;	/* inner tuple slot */
	econtext->ecxt_outertuple = NULL;	/* outer tuple slot */
	econtext->ecxt_relation = NULL;		/* relation */
	econtext->ecxt_relid = 0;	/* relid */
1605 1606
	econtext->ecxt_param_list_info = NULL;		/* param list info */
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
	econtext->ecxt_range_table = NULL;	/* range table */
	for (i = 0; i < ndef; i++)
	{
		if (!heap_attisnull(tuple, attrdef[i].adnum))
			continue;
		expr = (Node *) stringToNode(attrdef[i].adbin);

		val = ExecEvalExpr(expr, econtext, &isnull, &isdone);

		pfree(expr);

		if (isnull)
			continue;

		if (repl == NULL)
		{
			repl = (char *) palloc(rel->rd_att->natts * sizeof(char));
			replNull = (char *) palloc(rel->rd_att->natts * sizeof(char));
			replValue = (Datum *) palloc(rel->rd_att->natts * sizeof(Datum));
B
Bruce Momjian 已提交
1626
			MemSet(repl, ' ', rel->rd_att->natts * sizeof(char));
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
		}

		repl[attrdef[i].adnum - 1] = 'r';
		replNull[attrdef[i].adnum - 1] = ' ';
		replValue[attrdef[i].adnum - 1] = val;

	}

	pfree(econtext);

	if (repl == NULL)
1638
		return tuple;
1639

1640
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1641 1642

	pfree(repl);
1643
	heap_freetuple(tuple);
1644 1645 1646
	pfree(replNull);
	pfree(replValue);

1647
	return newtuple;
1648

V
Vadim B. Mikheev 已提交
1649
}
1650

1651
#endif
V
Vadim B. Mikheev 已提交
1652

1653
static char *
1654
ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1655
{
1656 1657 1658
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
	ExprContext *econtext = makeNode(ExprContext);
1659
	TupleTableSlot *slot = makeNode(TupleTableSlot);
1660 1661 1662 1663
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *rtlist;
	List	   *qual;
	int			i;
1664 1665 1666 1667 1668 1669 1670

	slot->val = tuple;
	slot->ttc_shouldFree = false;
	slot->ttc_descIsNew = true;
	slot->ttc_tupleDescriptor = rel->rd_att;
	slot->ttc_buffer = InvalidBuffer;
	slot->ttc_whichplan = -1;
1671
	rte->relname = RelationGetRelationName(rel);
1672 1673
	rte->ref = makeNode(Attr);
	rte->ref->relname = rte->relname;
1674
	rte->relid = RelationGetRelid(rel);
1675
	/* inh, inFromCl, inJoinSet, skipAcl won't be used, leave them zero */
1676 1677 1678 1679 1680 1681 1682
	rtlist = lcons(rte, NIL);
	econtext->ecxt_scantuple = slot;	/* scan tuple slot */
	econtext->ecxt_innertuple = NULL;	/* inner tuple slot */
	econtext->ecxt_outertuple = NULL;	/* outer tuple slot */
	econtext->ecxt_relation = rel;		/* relation */
	econtext->ecxt_relid = 0;	/* relid */
	econtext->ecxt_param_list_info = NULL;		/* param list info */
V
Vadim B. Mikheev 已提交
1683
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1684 1685
	econtext->ecxt_range_table = rtlist;		/* range table */

1686 1687 1688
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1689
			(List **) palloc(ncheck * sizeof(List *));
1690 1691 1692 1693 1694 1695 1696 1697

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

1698 1699
	for (i = 0; i < ncheck; i++)
	{
1700
		qual = estate->es_result_relation_constraints[i];
1701

1702 1703 1704 1705 1706 1707
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
		 * expression is not to be treated as a failure.  Therefore,
		 * tell ExecQual to return TRUE for NULL.
		 */
		if (! ExecQual(qual, econtext, true))
1708
			return check[i].ccname;
1709 1710 1711 1712 1713 1714 1715
	}

	pfree(slot);
	pfree(rte);
	pfree(rtlist);
	pfree(econtext);

1716
	return (char *) NULL;
1717

V
Vadim B. Mikheev 已提交
1718 1719
}

1720
void
1721
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1722
{
1723 1724 1725 1726

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1727
	{
1728
		int			attrChk;
1729 1730 1731 1732

		for (attrChk = 1; attrChk <= rel->rd_att->natts; attrChk++)
		{
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
1733
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1734
				  caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1735 1736 1737 1738 1739
		}
	}

	if (rel->rd_att->constr->num_check > 0)
	{
1740
		char	   *failed;
1741

1742
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1743
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1744 1745
	}

1746
	return;
V
Vadim B. Mikheev 已提交
1747
}
1748

B
Bruce Momjian 已提交
1749
TupleTableSlot *
1750 1751
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1752 1753 1754 1755 1756 1757 1758
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1759 1760 1761 1762 1763

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1764 1765
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1766 1767 1768 1769 1770 1771
		epq->rti = rti;
		endNode = false;
	}

	/*
	 * If this is request for another RTE - Ra, - then we have to check
B
Bruce Momjian 已提交
1772 1773 1774
	 * 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? -:))
1775
	 */
B
Bruce Momjian 已提交
1776
	if (epq != NULL && epq->rti != rti &&
1777 1778 1779 1780 1781 1782
		epq->estate.es_evTuple[rti - 1] != NULL)
	{
		do
		{
			/* pop previous PlanQual from the stack */
			epqstate = &(epq->estate);
B
Bruce Momjian 已提交
1783
			oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1784 1785 1786
			Assert(oldepq->rti != 0);
			/* stop execution */
			ExecEndNode(epq->plan, epq->plan);
1787
		    epqstate->es_tupleTable->next = 0;
1788
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1789 1790 1791 1792 1793 1794 1795 1796
			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 已提交
1797
	/*
1798 1799 1800 1801 1802 1803
	 * 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 已提交
1804
		evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1805

1806
		if (newepq == NULL)		/* first call or freePQ stack is empty */
1807
		{
B
Bruce Momjian 已提交
1808
			newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1809 1810 1811
			/* Init EState */
			epqstate = &(newepq->estate);
			memset(epqstate, 0, sizeof(EState));
B
Bruce Momjian 已提交
1812
			epqstate->type = T_EState;
1813 1814 1815 1816 1817 1818
			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 已提交
1819 1820 1821
					palloc(estate->es_origPlan->nParamExec *
						   sizeof(ParamExecData));
			epqstate->es_tupleTable =
1822 1823 1824 1825
				ExecCreateTupleTable(estate->es_tupleTable->size);
			/* ... rest */
			newepq->plan = copyObject(estate->es_origPlan);
			newepq->free = NULL;
B
Bruce Momjian 已提交
1826
			epqstate->es_evTupleNull = (bool *)
1827 1828
				palloc(length(estate->es_range_table) * sizeof(bool));
			if (epq == NULL)	/* first call */
1829
			{
B
Bruce Momjian 已提交
1830
				epqstate->es_evTuple = (HeapTuple *)
1831
					palloc(length(estate->es_range_table) * sizeof(HeapTuple));
B
Bruce Momjian 已提交
1832 1833
				memset(epqstate->es_evTuple, 0,
					 length(estate->es_range_table) * sizeof(HeapTuple));
1834 1835 1836 1837 1838 1839 1840 1841
			}
			else
				epqstate->es_evTuple = epq->estate.es_evTuple;
		}
		else
			epqstate = &(newepq->estate);
		/* push current PQ to the stack */
		epqstate->es_evalPlanQual = (Pointer) epq;
1842 1843
		epq = newepq;
		estate->es_evalPlanQual = (Pointer) epq;
1844 1845 1846 1847 1848 1849 1850
		epq->rti = rti;
		endNode = false;
	}

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1851 1852
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1853 1854
	 */
	if (endNode)
1855
	{
1856
		ExecEndNode(epq->plan, epq->plan);
1857 1858
	    epqstate->es_tupleTable->next = 0;
	}
1859 1860 1861 1862

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1863
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1864 1865 1866 1867
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1868
	if (estate->es_result_relation_info != NULL &&
1869 1870 1871 1872
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1873
		List	   *l;
1874

B
Bruce Momjian 已提交
1875
		foreach(l, estate->es_rowMark)
1876
		{
B
Bruce Momjian 已提交
1877
			if (((execRowMark *) lfirst(l))->rti == rti)
1878 1879
				break;
		}
B
Bruce Momjian 已提交
1880
		relation = ((execRowMark *) lfirst(l))->relation;
1881 1882
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1883
	for (;;)
1884 1885 1886 1887 1888 1889 1890
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1891 1892 1893 1894 1895
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1896

1897
			/*
B
Bruce Momjian 已提交
1898 1899
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1900 1901 1902 1903 1904 1905 1906
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1907

1908 1909 1910
			/*
			 * Nice! We got tuple - now copy it.
			 */
1911
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1912
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1913 1914 1915 1916
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1917

1918 1919
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1920 1921
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1922
		 */
B
Bruce Momjian 已提交
1923
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1924 1925 1926 1927 1928
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1929

1930
		/*
B
Bruce Momjian 已提交
1931 1932
		 * Deleted or updated by this transaction. Do not (re-)start
		 * execution of this PQ. Continue previous PQ.
1933
		 */
B
Bruce Momjian 已提交
1934
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
		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
1945 1946 1947 1948
		{									
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and      */
			return (NULL);					/* continue Query execution   */
1949 1950 1951 1952
		}
	}

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1953 1954 1955 1956
		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));
1957
    Assert(epqstate->es_tupleTable->next == 0);
1958 1959 1960
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1961 1962
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1963 1964 1965 1966 1967 1968
	 */
	*tid = tuple.t_self;

	return (EvalPlanQualNext(estate));
}

B
Bruce Momjian 已提交
1969
static TupleTableSlot *
1970 1971
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1972 1973 1974 1975
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

	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);
1988
	    epqstate->es_tupleTable->next = 0;
1989
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1990 1991
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1992 1993
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
1994 1995 1996 1997
		{
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and	  */
			return (NULL);					/* continue Query execution   */
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
		}
		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);
}