execMain.c 50.4 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.119 2000/07/04 06:11: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
#include "executor/execdebug.h"
#include "executor/execdefs.h"
#include "miscadmin.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "utils/acl.h"
45

46 47

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

79 80
/* end of local decls */

81

82
/* ----------------------------------------------------------------
83 84 85 86 87 88 89
 *		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.
90 91 92 93
 *
 * ----------------------------------------------------------------
 */
TupleDesc
94
ExecutorStart(QueryDesc *queryDesc, EState *estate)
95
{
96
	TupleDesc	result;
97 98 99

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

V
Vadim B. Mikheev 已提交
101 102
	if (queryDesc->plantree->nParamExec > 0)
	{
103 104 105
		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 已提交
106
	}
107

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

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

	return result;
135 136 137
}

/* ----------------------------------------------------------------
138 139 140 141 142 143 144
 *		ExecutorRun
 *
 *		This is the main routine of the executor module. It accepts
 *		the query descriptor from the traffic cop and executes the
 *		query plan.
 *
 *		ExecutorStart must have been called already.
145
 *
146 147 148 149 150 151
 *		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
152 153 154 155
 *
 *
 * ----------------------------------------------------------------
 */
156
TupleTableSlot *
B
Bruce Momjian 已提交
157 158
ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature,
			Node *limoffset, Node *limcount)
159
{
B
Bruce Momjian 已提交
160 161
	CmdType		operation;
	Plan	   *plan;
162
	TupleTableSlot *result;
B
Bruce Momjian 已提交
163 164 165 166
	CommandDest dest;
	DestReceiver *destfunc;
	int			offset = 0;
	int			count = 0;
167

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

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

B
Bruce Momjian 已提交
184
	/*
B
Bruce Momjian 已提交
185 186 187 188
	 * 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.
189 190 191
	 */
	(*destfunc->setup) (destfunc, (TupleDesc) NULL);

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

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

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

213 214 215 216 217 218 219 220 221 222 223
				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 已提交
224 225
				offset = (int) (paramLI[i].value);

226
				break;
B
Bruce Momjian 已提交
227

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

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

B
Bruce Momjian 已提交
236
	/*
B
Bruce Momjian 已提交
237
	 * if given get the count of the LIMIT clause
238 239 240
	 */
	if (limcount != NULL)
	{
B
Bruce Momjian 已提交
241 242 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
		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");
278 279
	}

280 281 282
	switch (feature)
	{

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

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

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

334 335
	(*destfunc->cleanup) (destfunc);

336
	return result;
337 338 339
}

/* ----------------------------------------------------------------
340 341 342 343 344 345 346
 *		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.
347 348 349 350
 *
 * ----------------------------------------------------------------
 */
void
351
ExecutorEnd(QueryDesc *queryDesc, EState *estate)
352
{
353 354
	/* sanity checks */
	Assert(queryDesc != NULL);
355

356
	EndPlan(queryDesc->plantree, estate);
357

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

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

381 382 383 384 385 386 387

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

394 395 396 397 398 399 400 401 402
	/*
	 * 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);
403

404 405 406 407 408
		resultIsScanned = (intMember(resultRelation, qvars) ||
						   intMember(resultRelation, tvars));
		freeList(qvars);
		freeList(tvars);
	}
409

410 411 412 413 414 415 416 417 418
	/*
	 * Check RTEs in the query's primary rangetable.
	 */
	ExecCheckRTPerms(rangeTable, operation, resultRelation, resultIsScanned);

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

422 423
		if (!(rm->info & ROW_ACL_FOR_UPDATE))
			continue;
424

425 426 427
		ExecCheckRTEPerms(rt_fetch(rm->rti, rangeTable),
						  CMD_UPDATE, true, false);
	}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	/*
	 * 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)
	{
457
		SubPlan    *subplan = (SubPlan *) lfirst(subp);
458 459 460 461 462 463

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

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
		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:
482
			{
483 484
				Append	   *app = (Append *) plan;
				List	   *appendplans;
485

486
				if (app->inheritrelid > 0)
487 488
				{

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
					/*
					 * 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);
					}
				}
				else
506
				{
507 508 509 510 511 512 513 514
					/* Append implements UNION, which must be a SELECT */
					List	   *rtables;

					foreach(rtables, app->unionrtables)
					{
						ExecCheckRTPerms((List *) lfirst(rtables),
										 CMD_SELECT, 0, false);
					}
515 516
				}

517 518 519 520 521 522 523 524 525
				/* Check appended plans */
				foreach(appendplans, app->appendplans)
				{
					ExecCheckPlanPerms((Plan *) lfirst(appendplans),
									   operation,
									   resultRelation,
									   resultIsScanned);
				}
				break;
526 527 528
			}

		default:
529
			break;
530
	}
531
}
532

533 534 535 536 537
/*
 * 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
538
 * treated as the result relation.	All other relations are assumed to be
539 540 541 542 543 544 545 546 547 548
 * read-only for the query.
 */
static void
ExecCheckRTPerms(List *rangeTable, CmdType operation,
				 int resultRelation, bool resultIsScanned)
{
	int			rtindex = 0;
	List	   *lp;

	foreach(lp, rangeTable)
549
	{
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
		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)
	{
575

576
		/*
577 578 579
		 * 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.
580 581 582 583 584 585 586 587 588 589 590 591 592
		 */
		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();
593

594
#define CHECK(MODE)		pg_aclcheck(relName, userName, MODE)
595

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

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

632

633 634 635 636 637 638 639
/* ===============================================================
 * ===============================================================
						 static routines follow
 * ===============================================================
 * ===============================================================
 */

640 641 642
typedef struct execRowMark
{
	Relation	relation;
643
	Index		rti;
644
	char		resname[32];
645
} execRowMark;
646

647 648
typedef struct evalPlanQual
{
B
Bruce Momjian 已提交
649 650 651 652
	Plan	   *plan;
	Index		rti;
	EState		estate;
	struct evalPlanQual *free;
653
} evalPlanQual;
654

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

671 672 673 674 675 676 677
	/*
	 * Do permissions checks.
	 */
#ifndef NO_SECURITY
	ExecCheckQueryPerms(operation, parseTree, plan);
#endif

B
Bruce Momjian 已提交
678
	/*
B
Bruce Momjian 已提交
679
	 * get information from query descriptor
680
	 */
681 682
	rangeTable = parseTree->rtable;
	resultRelation = parseTree->resultRelation;
683

B
Bruce Momjian 已提交
684
	/*
B
Bruce Momjian 已提交
685
	 * initialize the node's execution state
686
	 */
687 688
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
689
	/*
B
Bruce Momjian 已提交
690 691 692
	 * 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.
693
	 */
694
	estate->es_BaseId = 1;
695

B
Bruce Momjian 已提交
696
	/*
B
Bruce Momjian 已提交
697
	 * initialize result relation stuff
698
	 */
B
Bruce Momjian 已提交
699

700 701
	if (resultRelation != 0 && operation != CMD_SELECT)
	{
B
Bruce Momjian 已提交
702

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

		resultRelationIndex = resultRelation;
		rtentry = rt_fetch(resultRelationIndex, rangeTable);
		resultRelationOid = rtentry->relid;
716
		resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
717 718

		if (resultRelationDesc->rd_rel->relkind == RELKIND_SEQUENCE)
719
			elog(ERROR, "You can't change sequence relation %s",
720
				 RelationGetRelationName(resultRelationDesc));
721 722 723 724 725 726 727

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

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

		estate->es_result_relation_info = resultRelationInfo;
741
	}
742 743
	else
	{
B
Bruce Momjian 已提交
744

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

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

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

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

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

785 786
		estate->es_tupleTable = tupleTable;
	}
787

B
Bruce Momjian 已提交
788
	/*
B
Bruce Momjian 已提交
789 790 791
	 * 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..
792 793 794
	 */
	ExecInitNode(plan, estate, NULL);

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

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

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

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

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

841
			estate->es_junkFilter = j;
842

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

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

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

		if (!parseTree->isPortal)
		{

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

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

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

880 881 882 883 884 885
				intoRelationId =
					heap_create_with_catalog(intoName,
											 tupdesc,
											 RELKIND_RELATION,
											 parseTree->isTemp,
											 allowSystemTableMods);
886

887 888
				FreeTupleDesc(tupdesc);

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

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

	estate->es_into_relation_descriptor = intoRelationDesc;

903 904 905 906 907
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_useEvalPlan = false;

908
	return tupType;
909 910 911
}

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

923 924 925 926 927 928
	/*
	 * shut down any PlanQual processing we were doing
	 */
	if (estate->es_evalPlanQual != NULL)
		EndEvalPlanQual(estate);

B
Bruce Momjian 已提交
929
	/*
930
	 * shut down the node-type-specific query processing
931 932 933
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
934
	/*
B
Bruce Momjian 已提交
935
	 * destroy the executor "tuple" table.
936
	 */
937 938
	ExecDropTupleTable(estate->es_tupleTable, true);
	estate->es_tupleTable = NULL;
939

B
Bruce Momjian 已提交
940
	/*
941 942 943
	 * 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 ...
944
	 */
945
	resultRelationInfo = estate->es_result_relation_info;
946 947
	if (resultRelationInfo != NULL)
	{
948 949
		heap_close(resultRelationInfo->ri_RelationDesc, NoLock);
		/* close indices on the result relation, too */
950 951 952
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
953
	/*
954
	 * close the "into" relation if necessary, again keeping lock
955
	 */
956 957
	if (estate->es_into_relation_descriptor != NULL)
		heap_close(estate->es_into_relation_descriptor, NoLock);
958 959 960 961 962 963 964 965 966 967

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

		heap_close(erm->relation, NoLock);
	}
968 969 970
}

/* ----------------------------------------------------------------
971 972 973 974 975 976 977 978
 *		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.
979 980 981 982 983 984 985 986
 *
 * ----------------------------------------------------------------
 */

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

static TupleTableSlot *
987 988
ExecutePlan(EState *estate,
			Plan *plan,
989
			CmdType operation,
990
			int offsetTuples,
991 992
			int numberTuples,
			ScanDirection direction,
993
			DestReceiver *destfunc)
994
{
995
	JunkFilter *junkfilter;
996
	TupleTableSlot *slot;
997
	ItemPointer tupleid = NULL;
998
	ItemPointerData tuple_ctid;
999
	int			current_tuple_count;
1000 1001
	TupleTableSlot *result;

B
Bruce Momjian 已提交
1002
	/*
B
Bruce Momjian 已提交
1003
	 * initialize local variables
1004
	 */
1005 1006 1007 1008
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
1009 1010
	/*
	 * Set the direction.
1011
	 */
1012 1013
	estate->es_direction = direction;

B
Bruce Momjian 已提交
1014
	/*
B
Bruce Momjian 已提交
1015 1016
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
1017 1018 1019 1020
	 */

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

B
Bruce Momjian 已提交
1022
		/*
B
Bruce Momjian 已提交
1023
		 * Execute the plan and obtain a tuple
1024 1025
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
1026
lnext:	;
1027 1028 1029 1030 1031 1032 1033 1034
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
1035

B
Bruce Momjian 已提交
1036
		/*
B
Bruce Momjian 已提交
1037 1038
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
1039 1040 1041 1042 1043
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
1044 1045
		}

B
Bruce Momjian 已提交
1046
		/*
B
Bruce Momjian 已提交
1047 1048 1049
		 * 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
1050 1051 1052 1053 1054 1055 1056
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

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

B
Bruce Momjian 已提交
1071
			/*
1072 1073 1074 1075 1076 1077 1078 1079 1080
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
1081
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1082 1083

				if (isNull)
1084
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1085 1086 1087 1088 1089 1090

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

B
Bruce Momjian 已提交
1095 1096
		lmark:	;
				foreach(l, estate->es_rowMark)
1097
				{
1098 1099 1100 1101 1102 1103
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
					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)
1125
							{
1126
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
1127
								return (NULL);
1128
							}
B
Bruce Momjian 已提交
1129 1130
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
1131
							{
B
Bruce Momjian 已提交
1132
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1133 1134 1135 1136 1137 1138 1139
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1140 1141 1142 1143 1144

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
1145 1146
							 */
							goto lnext;
1147 1148 1149

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
1150
							return (NULL);
1151 1152 1153
					}
				}
			}
1154

B
Bruce Momjian 已提交
1155
			/*
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
			 * 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 已提交
1168
		/*
B
Bruce Momjian 已提交
1169 1170
		 * 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 已提交
1171
		 * delete it from a relation, or modify some of its attributes.
1172 1173 1174 1175
		 */

		switch (operation)
		{
1176 1177
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1178 1179
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1180 1181 1182
							 estate);	/* */
				result = slot;
				break;
1183

1184 1185 1186 1187
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1188

1189 1190 1191 1192
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1193

1194
			case CMD_UPDATE:
1195
				ExecReplace(slot, tupleid, estate);
1196 1197
				result = NULL;
				break;
1198

1199 1200
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1201
				result = NULL;
1202
				break;
1203
		}
B
Bruce Momjian 已提交
1204

B
Bruce Momjian 已提交
1205
		/*
B
Bruce Momjian 已提交
1206 1207
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1208 1209 1210 1211
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1212
	}
1213

B
Bruce Momjian 已提交
1214
	/*
B
Bruce Momjian 已提交
1215 1216
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1217
	 */
1218
	return result;
1219 1220 1221
}

/* ----------------------------------------------------------------
1222
 *		ExecRetrieve
1223
 *
1224 1225 1226 1227 1228
 *		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.)
1229 1230 1231
 * ----------------------------------------------------------------
 */
static void
1232
ExecRetrieve(TupleTableSlot *slot,
1233
			 DestReceiver *destfunc,
1234
			 EState *estate)
1235
{
1236 1237
	HeapTuple	tuple;
	TupleDesc	attrtype;
1238

B
Bruce Momjian 已提交
1239
	/*
B
Bruce Momjian 已提交
1240
	 * get the heap tuple out of the tuple table slot
1241 1242 1243 1244
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1245
	/*
B
Bruce Momjian 已提交
1246
	 * insert the tuple into the "into relation"
1247 1248 1249 1250 1251 1252 1253
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1254
	/*
B
Bruce Momjian 已提交
1255
	 * send the tuple to the front end (or the screen)
1256
	 */
1257
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1258 1259
	IncrRetrieved();
	(estate->es_processed)++;
1260 1261 1262
}

/* ----------------------------------------------------------------
1263
 *		ExecAppend
1264
 *
1265 1266 1267
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1268 1269 1270 1271
 * ----------------------------------------------------------------
 */

static void
1272
ExecAppend(TupleTableSlot *slot,
1273
		   ItemPointer tupleid,
1274
		   EState *estate)
1275
{
1276 1277 1278 1279 1280
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1281

B
Bruce Momjian 已提交
1282
	/*
B
Bruce Momjian 已提交
1283
	 * get the heap tuple out of the tuple table slot
1284 1285 1286
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1287
	/*
B
Bruce Momjian 已提交
1288
	 * get information on the result relation
1289 1290 1291 1292
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1293
	/*
B
Bruce Momjian 已提交
1294
	 * have to add code to preform unique checking here. cim -12/1/89
1295 1296 1297 1298 1299 1300
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1301
		HeapTuple	newtuple;
1302 1303 1304 1305 1306 1307 1308 1309 1310

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1311
			heap_freetuple(tuple);
1312 1313 1314 1315
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1316
	/*
1317 1318 1319 1320
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1321
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1322

B
Bruce Momjian 已提交
1323
	/*
B
Bruce Momjian 已提交
1324
	 * insert the tuple
1325 1326 1327 1328 1329
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

B
Bruce Momjian 已提交
1330
	/*
B
Bruce Momjian 已提交
1331
	 * process indices
1332
	 *
B
Bruce Momjian 已提交
1333 1334 1335
	 * 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.
1336 1337 1338
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1339
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1340 1341 1342 1343
	(estate->es_processed)++;
	estate->es_lastoid = newId;

	/* AFTER ROW INSERT Triggers */
1344
	if (resultRelationDesc->trigdesc)
1345
		ExecARInsertTriggers(resultRelationDesc, tuple);
1346 1347 1348
}

/* ----------------------------------------------------------------
1349
 *		ExecDelete
1350
 *
1351 1352
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1353 1354 1355
 * ----------------------------------------------------------------
 */
static void
1356
ExecDelete(TupleTableSlot *slot,
1357
		   ItemPointer tupleid,
1358
		   EState *estate)
1359
{
B
Bruce Momjian 已提交
1360 1361 1362 1363
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1364

B
Bruce Momjian 已提交
1365
	/*
B
Bruce Momjian 已提交
1366
	 * get the result relation information
1367 1368 1369 1370 1371 1372 1373 1374
	 */
	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)
	{
1375
		bool		dodelete;
1376

V
Vadim B. Mikheev 已提交
1377
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1378 1379 1380 1381 1382

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

V
Vadim B. Mikheev 已提交
1383
	/*
B
Bruce Momjian 已提交
1384
	 * delete the tuple
1385
	 */
1386
ldelete:;
V
Vadim B. Mikheev 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1397 1398
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1399 1400
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1401 1402
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1403

V
Vadim B. Mikheev 已提交
1404
				if (!TupIsNull(epqslot))
1405 1406 1407 1408 1409
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1410 1411 1412 1413 1414 1415
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1416 1417 1418 1419

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

B
Bruce Momjian 已提交
1420
	/*
B
Bruce Momjian 已提交
1421 1422
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1423
	 *
B
Bruce Momjian 已提交
1424 1425 1426
	 * ... 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
1427 1428 1429
	 */

	/* AFTER ROW DELETE Triggers */
1430
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1431
		ExecARDeleteTriggers(estate, tupleid);
1432 1433 1434 1435

}

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

B
Bruce Momjian 已提交
1458
	/*
B
Bruce Momjian 已提交
1459
	 * abort the operation if not running transactions
1460 1461 1462 1463 1464 1465 1466
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1467
	/*
B
Bruce Momjian 已提交
1468
	 * get the heap tuple out of the tuple table slot
1469 1470 1471
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1472
	/*
B
Bruce Momjian 已提交
1473
	 * get the result relation information
1474 1475 1476 1477
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1478
	/*
B
Bruce Momjian 已提交
1479 1480 1481
	 * 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
1482 1483 1484 1485 1486 1487
	 */

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

V
Vadim B. Mikheev 已提交
1490
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1491 1492 1493 1494 1495 1496 1497

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1498
			heap_freetuple(tuple);
1499 1500 1501 1502
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1503
	/*
1504 1505 1506 1507
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1508
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1509

V
Vadim B. Mikheev 已提交
1510
	/*
B
Bruce Momjian 已提交
1511
	 * replace the heap tuple
1512
	 */
1513
lreplace:;
1514
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1524 1525
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1526 1527
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1528 1529
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1530

V
Vadim B. Mikheev 已提交
1531
				if (!TupIsNull(epqslot))
1532 1533
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1534 1535
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1536 1537 1538
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1539 1540 1541
			return;

		default:
1542
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1543
			return;
1544 1545 1546 1547 1548
	}

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

B
Bruce Momjian 已提交
1549
	/*
B
Bruce Momjian 已提交
1550 1551 1552 1553 1554
	 * 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
1555 1556
	 */

B
Bruce Momjian 已提交
1557
	/*
B
Bruce Momjian 已提交
1558
	 * process indices
1559
	 *
1560
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1561 1562 1563 1564
	 * 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.
1565 1566 1567 1568
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1569
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1570 1571

	/* AFTER ROW UPDATE Triggers */
1572
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1573
		ExecARUpdateTriggers(estate, tupleid, tuple);
1574
}
V
Vadim B. Mikheev 已提交
1575

M
 
Marc G. Fournier 已提交
1576
#ifdef NOT_USED
1577
static HeapTuple
1578
ExecAttrDefault(Relation rel, HeapTuple tuple)
V
Vadim B. Mikheev 已提交
1579
{
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
	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;
1592 1593 1594 1595 1596 1597

	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 */
1598 1599
	econtext->ecxt_param_list_info = NULL;		/* param list info */
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
	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 已提交
1619
			MemSet(repl, ' ', rel->rd_att->natts * sizeof(char));
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
		}

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

	}

	pfree(econtext);

	if (repl == NULL)
1631
		return tuple;
1632

1633
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1634 1635

	pfree(repl);
1636
	heap_freetuple(tuple);
1637 1638 1639
	pfree(replNull);
	pfree(replValue);

1640
	return newtuple;
1641

V
Vadim B. Mikheev 已提交
1642
}
1643

1644
#endif
V
Vadim B. Mikheev 已提交
1645

1646
static char *
1647
ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1648
{
1649 1650 1651
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
	ExprContext *econtext = makeNode(ExprContext);
1652
	TupleTableSlot *slot = makeNode(TupleTableSlot);
1653 1654 1655 1656
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *rtlist;
	List	   *qual;
	int			i;
1657 1658 1659 1660 1661 1662 1663

	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;
1664
	rte->relname = RelationGetRelationName(rel);
1665 1666
	rte->ref = makeNode(Attr);
	rte->ref->relname = rte->relname;
1667
	rte->relid = RelationGetRelid(rel);
1668
	/* inh, inFromCl, inJoinSet, skipAcl won't be used, leave them zero */
1669 1670 1671 1672 1673 1674 1675
	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 已提交
1676
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1677 1678
	econtext->ecxt_range_table = rtlist;		/* range table */

1679 1680 1681
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1682
			(List **) palloc(ncheck * sizeof(List *));
1683 1684 1685 1686 1687 1688 1689 1690

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

1691 1692
	for (i = 0; i < ncheck; i++)
	{
1693
		qual = estate->es_result_relation_constraints[i];
1694

1695 1696
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
1697 1698
		 * expression is not to be treated as a failure.  Therefore, tell
		 * ExecQual to return TRUE for NULL.
1699
		 */
1700
		if (!ExecQual(qual, econtext, true))
1701
			return check[i].ccname;
1702 1703 1704 1705 1706 1707 1708
	}

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

1709
	return (char *) NULL;
1710

V
Vadim B. Mikheev 已提交
1711 1712
}

1713
void
1714
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1715
{
1716 1717 1718 1719

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1720
	{
1721
		int			attrChk;
1722 1723 1724 1725

		for (attrChk = 1; attrChk <= rel->rd_att->natts; attrChk++)
		{
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
1726
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1727
					 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1728 1729 1730 1731 1732
		}
	}

	if (rel->rd_att->constr->num_check > 0)
	{
1733
		char	   *failed;
1734

1735
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1736
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1737 1738
	}

1739
	return;
V
Vadim B. Mikheev 已提交
1740
}
1741

B
Bruce Momjian 已提交
1742
TupleTableSlot *
1743 1744
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1745 1746 1747 1748 1749 1750 1751
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1752 1753 1754 1755 1756

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1757 1758
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1759 1760 1761 1762 1763 1764
		epq->rti = rti;
		endNode = false;
	}

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

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

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1844 1845
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1846 1847
	 */
	if (endNode)
1848
	{
1849
		ExecEndNode(epq->plan, epq->plan);
1850
		epqstate->es_tupleTable->next = 0;
1851
	}
1852 1853 1854 1855

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1856
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1857 1858 1859 1860
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1861
	if (estate->es_result_relation_info != NULL &&
1862 1863 1864 1865
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1866
		List	   *l;
1867

B
Bruce Momjian 已提交
1868
		foreach(l, estate->es_rowMark)
1869
		{
B
Bruce Momjian 已提交
1870
			if (((execRowMark *) lfirst(l))->rti == rti)
1871 1872
				break;
		}
B
Bruce Momjian 已提交
1873
		relation = ((execRowMark *) lfirst(l))->relation;
1874 1875
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1876
	for (;;)
1877 1878 1879 1880 1881 1882 1883
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1884 1885 1886 1887 1888
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1889

1890
			/*
B
Bruce Momjian 已提交
1891 1892
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1893 1894 1895 1896 1897 1898 1899
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1900

1901 1902 1903
			/*
			 * Nice! We got tuple - now copy it.
			 */
1904
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1905
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1906 1907 1908 1909
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1910

1911 1912
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1913 1914
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1915
		 */
B
Bruce Momjian 已提交
1916
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1917 1918 1919 1920 1921
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1922

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

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1946 1947 1948 1949
		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));
1950
	Assert(epqstate->es_tupleTable->next == 0);
1951 1952 1953
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1954 1955
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1956 1957 1958
	 */
	*tid = tuple.t_self;

1959
	return EvalPlanQualNext(estate);
1960 1961
}

B
Bruce Momjian 已提交
1962
static TupleTableSlot *
1963 1964
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1965 1966 1967 1968
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980

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

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

2011 2012 2013
	if (epq->rti == 0)			/* plans already shutdowned */
	{
		Assert(epq->estate.es_evalPlanQual == NULL);
2014
		return;
2015
	}
2016 2017 2018 2019

	for (;;)
	{
		ExecEndNode(epq->plan, epq->plan);
2020
		epqstate->es_tupleTable->next = 0;
2021 2022 2023 2024 2025
		if (epqstate->es_evTuple[epq->rti - 1] != NULL)
		{
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
			epqstate->es_evTuple[epq->rti - 1] = NULL;
		}
2026 2027 2028 2029
		/* pop old PQ from the stack */
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
		{
2030 2031
			epq->rti = 0;		/* this is the first (oldest) */
			estate->es_useEvalPlan = false;		/* PQ - mark as free */
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
			break;
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
		epqstate = &(epq->estate);
		estate->es_evalPlanQual = (Pointer) epq;
	}
}