execMain.c 50.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.111 2000/04/07 00:59:17 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
static void EndEvalPlanQual(EState *estate);
77 78 79 80 81 82 83 84
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);
85 86
/* end of local decls */

87

88
/* ----------------------------------------------------------------
89 90 91 92 93 94 95
 *		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.
96 97 98 99
 *
 * ----------------------------------------------------------------
 */
TupleDesc
100
ExecutorStart(QueryDesc *queryDesc, EState *estate)
101
{
102
	TupleDesc	result;
103 104 105

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

V
Vadim B. Mikheev 已提交
107 108
	if (queryDesc->plantree->nParamExec > 0)
	{
109 110 111
		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 已提交
112
	}
113

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

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

	return result;
141 142 143
}

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

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

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

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

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

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

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

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

232
				break;
B
Bruce Momjian 已提交
233

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

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

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

286 287 288
	switch (feature)
	{

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

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

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

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

342
	return result;
343 344 345
}

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

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

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

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

387 388 389 390 391 392 393

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

400 401 402 403 404 405 406 407 408
	/*
	 * 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);
409

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

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

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

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

431 432 433
		ExecCheckRTEPerms(rt_fetch(rm->rti, rangeTable),
						  CMD_UPDATE, true, false);
	}
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 470
	/*
	 * 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 已提交
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
		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)
493
			{
494 495 496 497 498 499 500 501 502 503 504 505 506 507
				/*
				 * 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);
				}
508
			}
509
			else
510
			{
511 512 513 514 515 516 517 518
				/* Append implements UNION, which must be a SELECT */
				List	   *rtables;

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

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

		default:
533
			break;
534
	}
535
}
536

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
/*
 * 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)
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 595
		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();
596

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

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

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

637

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

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

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

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

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

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

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

B
Bruce Momjian 已提交
694
	/*
B
Bruce Momjian 已提交
695 696 697
	 * 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.
698
	 */
699
	estate->es_BaseId = 1;
700

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

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

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

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

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

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

B
Bruce Momjian 已提交
734
		/*
735 736 737 738
		 * 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.
739
		 */
740 741
		if (resultRelationDesc->rd_rel->relhasindex &&
			operation != CMD_DELETE)
V
Vadim B. Mikheev 已提交
742
			ExecOpenIndices(resultRelationOid, resultRelationInfo);
743 744

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

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

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

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

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

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

789 790
		estate->es_tupleTable = tupleTable;
	}
791

B
Bruce Momjian 已提交
792
	/*
B
Bruce Momjian 已提交
793 794 795
	 * 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..
796 797 798
	 */
	ExecInitNode(plan, estate, NULL);

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

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

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

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

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

844
			estate->es_junkFilter = j;
845

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

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

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

		if (!parseTree->isPortal)
		{

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

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

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

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

886 887
				FreeTupleDesc(tupdesc);

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

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

	estate->es_into_relation_descriptor = intoRelationDesc;

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

907
	return tupType;
908 909 910
}

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

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

929 930 931 932 933 934
	/*
	 * shut down any PlanQual processing we were doing
	 */
	if (estate->es_evalPlanQual != NULL)
		EndEvalPlanQual(estate);

B
Bruce Momjian 已提交
935
	/*
B
Bruce Momjian 已提交
936
	 * shut down the query
937 938 939
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
940
	/*
B
Bruce Momjian 已提交
941
	 * destroy the executor "tuple" table.
942 943
	 */
	{
944
		TupleTable	tupleTable = (TupleTable) estate->es_tupleTable;
945

946
		ExecDropTupleTable(tupleTable, true);
947 948 949
		estate->es_tupleTable = NULL;
	}

B
Bruce Momjian 已提交
950
	/*
951 952
	 * close the result relations if necessary,
	 * but hold locks on them until xact commit
953 954 955
	 */
	if (resultRelationInfo != NULL)
	{
956
		Relation	resultRelationDesc;
957 958

		resultRelationDesc = resultRelationInfo->ri_RelationDesc;
959
		heap_close(resultRelationDesc, NoLock);
960

B
Bruce Momjian 已提交
961
		/*
B
Bruce Momjian 已提交
962
		 * close indices on the result relation
963 964 965 966
		 */
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
967
	/*
968
	 * close the "into" relation if necessary, again keeping lock
969 970
	 */
	if (intoRelationDesc != NULL)
971
		heap_close(intoRelationDesc, NoLock);
972 973 974 975 976 977 978 979 980 981

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

		heap_close(erm->relation, NoLock);
	}
982 983 984
}

/* ----------------------------------------------------------------
985 986 987 988 989 990 991 992
 *		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.
993 994 995 996 997 998 999 1000
 *
 * ----------------------------------------------------------------
 */

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

static TupleTableSlot *
1001 1002
ExecutePlan(EState *estate,
			Plan *plan,
1003
			CmdType operation,
1004
			int offsetTuples,
1005 1006
			int numberTuples,
			ScanDirection direction,
1007
			DestReceiver *destfunc)
1008
{
1009
	JunkFilter *junkfilter;
1010
	TupleTableSlot *slot;
1011
	ItemPointer tupleid = NULL;
1012
	ItemPointerData tuple_ctid;
1013
	int			current_tuple_count;
1014 1015
	TupleTableSlot *result;

B
Bruce Momjian 已提交
1016
	/*
B
Bruce Momjian 已提交
1017
	 * initialize local variables
1018
	 */
1019 1020 1021 1022
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
1023 1024
	/*
	 * Set the direction.
1025
	 */
1026 1027
	estate->es_direction = direction;

B
Bruce Momjian 已提交
1028
	/*
B
Bruce Momjian 已提交
1029 1030
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
1031 1032 1033 1034
	 */

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

B
Bruce Momjian 已提交
1036
		/*
B
Bruce Momjian 已提交
1037
		 * Execute the plan and obtain a tuple
1038 1039
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
1040
lnext:	;
1041 1042 1043 1044 1045 1046 1047 1048
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
1049

B
Bruce Momjian 已提交
1050
		/*
B
Bruce Momjian 已提交
1051 1052
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
1053 1054 1055 1056 1057
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
1058 1059
		}

B
Bruce Momjian 已提交
1060
		/*
B
Bruce Momjian 已提交
1061 1062 1063
		 * 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
1064 1065 1066 1067 1068 1069 1070
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

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

B
Bruce Momjian 已提交
1085
			/*
1086 1087 1088 1089 1090 1091 1092 1093 1094
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
1095
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1096 1097

				if (isNull)
1098
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1099 1100 1101 1102 1103 1104

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

B
Bruce Momjian 已提交
1109 1110
		lmark:	;
				foreach(l, estate->es_rowMark)
1111
				{
1112 1113 1114 1115 1116 1117
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
					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)
1139
							{
1140
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
1141
								return (NULL);
1142
							}
B
Bruce Momjian 已提交
1143 1144
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
1145
							{
B
Bruce Momjian 已提交
1146
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1147 1148 1149 1150 1151 1152 1153
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1154 1155 1156 1157 1158

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
1159 1160
							 */
							goto lnext;
1161 1162 1163

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
1164
							return (NULL);
1165 1166 1167
					}
				}
			}
1168

B
Bruce Momjian 已提交
1169
			/*
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
			 * 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 已提交
1182
		/*
B
Bruce Momjian 已提交
1183 1184
		 * 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 已提交
1185
		 * delete it from a relation, or modify some of its attributes.
1186 1187 1188 1189
		 */

		switch (operation)
		{
1190 1191
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1192 1193
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1194 1195 1196
							 estate);	/* */
				result = slot;
				break;
1197

1198 1199 1200 1201
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1202

1203 1204 1205 1206
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1207

1208
			case CMD_UPDATE:
1209
				ExecReplace(slot, tupleid, estate);
1210 1211
				result = NULL;
				break;
1212

1213 1214
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1215
				result = NULL;
1216
				break;
1217
		}
B
Bruce Momjian 已提交
1218

B
Bruce Momjian 已提交
1219
		/*
B
Bruce Momjian 已提交
1220 1221
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1222 1223 1224 1225
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1226
	}
1227

B
Bruce Momjian 已提交
1228
	/*
B
Bruce Momjian 已提交
1229 1230
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1231
	 */
1232
	return result;
1233 1234 1235
}

/* ----------------------------------------------------------------
1236
 *		ExecRetrieve
1237
 *
1238 1239 1240 1241 1242
 *		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.)
1243 1244 1245
 * ----------------------------------------------------------------
 */
static void
1246
ExecRetrieve(TupleTableSlot *slot,
1247
			 DestReceiver *destfunc,
1248
			 EState *estate)
1249
{
1250 1251
	HeapTuple	tuple;
	TupleDesc	attrtype;
1252

B
Bruce Momjian 已提交
1253
	/*
B
Bruce Momjian 已提交
1254
	 * get the heap tuple out of the tuple table slot
1255 1256 1257 1258
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1259
	/*
B
Bruce Momjian 已提交
1260
	 * insert the tuple into the "into relation"
1261 1262 1263 1264 1265 1266 1267
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1268
	/*
B
Bruce Momjian 已提交
1269
	 * send the tuple to the front end (or the screen)
1270
	 */
1271
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1272 1273
	IncrRetrieved();
	(estate->es_processed)++;
1274 1275 1276
}

/* ----------------------------------------------------------------
1277
 *		ExecAppend
1278
 *
1279 1280 1281
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1282 1283 1284 1285
 * ----------------------------------------------------------------
 */

static void
1286
ExecAppend(TupleTableSlot *slot,
1287
		   ItemPointer tupleid,
1288
		   EState *estate)
1289
{
1290 1291 1292 1293 1294
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1295

B
Bruce Momjian 已提交
1296
	/*
B
Bruce Momjian 已提交
1297
	 * get the heap tuple out of the tuple table slot
1298 1299 1300
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1301
	/*
B
Bruce Momjian 已提交
1302
	 * get information on the result relation
1303 1304 1305 1306
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1307
	/*
B
Bruce Momjian 已提交
1308
	 * have to add code to preform unique checking here. cim -12/1/89
1309 1310 1311 1312 1313 1314
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1315
		HeapTuple	newtuple;
1316 1317 1318 1319 1320 1321 1322 1323 1324

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1325
			heap_freetuple(tuple);
1326 1327 1328 1329
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1330
	/*
1331 1332 1333 1334
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1335
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1336

B
Bruce Momjian 已提交
1337
	/*
B
Bruce Momjian 已提交
1338
	 * insert the tuple
1339 1340 1341 1342 1343
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

B
Bruce Momjian 已提交
1344
	/*
B
Bruce Momjian 已提交
1345
	 * process indices
1346
	 *
B
Bruce Momjian 已提交
1347 1348 1349
	 * 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.
1350 1351 1352
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1353
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1354 1355 1356 1357
	(estate->es_processed)++;
	estate->es_lastoid = newId;

	/* AFTER ROW INSERT Triggers */
1358
	if (resultRelationDesc->trigdesc)
1359
		ExecARInsertTriggers(resultRelationDesc, tuple);
1360 1361 1362
}

/* ----------------------------------------------------------------
1363
 *		ExecDelete
1364
 *
1365 1366
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1367 1368 1369
 * ----------------------------------------------------------------
 */
static void
1370
ExecDelete(TupleTableSlot *slot,
1371
		   ItemPointer tupleid,
1372
		   EState *estate)
1373
{
B
Bruce Momjian 已提交
1374 1375 1376 1377
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1378

B
Bruce Momjian 已提交
1379
	/*
B
Bruce Momjian 已提交
1380
	 * get the result relation information
1381 1382 1383 1384 1385 1386 1387 1388
	 */
	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)
	{
1389
		bool		dodelete;
1390

V
Vadim B. Mikheev 已提交
1391
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1392 1393 1394 1395 1396

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

V
Vadim B. Mikheev 已提交
1397
	/*
B
Bruce Momjian 已提交
1398
	 * delete the tuple
1399
	 */
1400
ldelete:;
V
Vadim B. Mikheev 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1411 1412
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1413 1414
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1415 1416
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1417

V
Vadim B. Mikheev 已提交
1418
				if (!TupIsNull(epqslot))
1419 1420 1421 1422 1423
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1424 1425 1426 1427 1428 1429
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1430 1431 1432 1433

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

B
Bruce Momjian 已提交
1434
	/*
B
Bruce Momjian 已提交
1435 1436
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1437
	 *
B
Bruce Momjian 已提交
1438 1439 1440
	 * ... 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
1441 1442 1443
	 */

	/* AFTER ROW DELETE Triggers */
1444
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1445
		ExecARDeleteTriggers(estate, tupleid);
1446 1447 1448 1449

}

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

B
Bruce Momjian 已提交
1472
	/*
B
Bruce Momjian 已提交
1473
	 * abort the operation if not running transactions
1474 1475 1476 1477 1478 1479 1480
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1481
	/*
B
Bruce Momjian 已提交
1482
	 * get the heap tuple out of the tuple table slot
1483 1484 1485
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1486
	/*
B
Bruce Momjian 已提交
1487
	 * get the result relation information
1488 1489 1490 1491
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1492
	/*
B
Bruce Momjian 已提交
1493 1494 1495
	 * 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
1496 1497 1498 1499 1500 1501
	 */

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

V
Vadim B. Mikheev 已提交
1504
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1505 1506 1507 1508 1509 1510 1511

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1512
			heap_freetuple(tuple);
1513 1514 1515 1516
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1517
	/*
1518 1519 1520 1521
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1522
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1523

V
Vadim B. Mikheev 已提交
1524
	/*
B
Bruce Momjian 已提交
1525
	 * replace the heap tuple
1526
	 */
1527
lreplace:;
1528
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1538 1539
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1540 1541
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1542 1543
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1544

V
Vadim B. Mikheev 已提交
1545
				if (!TupIsNull(epqslot))
1546 1547
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1548 1549
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1550 1551 1552
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1553 1554 1555
			return;

		default:
1556
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1557
			return;
1558 1559 1560 1561 1562
	}

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

B
Bruce Momjian 已提交
1563
	/*
B
Bruce Momjian 已提交
1564 1565 1566 1567 1568
	 * 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
1569 1570
	 */

B
Bruce Momjian 已提交
1571
	/*
B
Bruce Momjian 已提交
1572
	 * process indices
1573
	 *
1574
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1575 1576 1577 1578
	 * 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.
1579 1580 1581 1582
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1583
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1584 1585

	/* AFTER ROW UPDATE Triggers */
1586
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1587
		ExecARUpdateTriggers(estate, tupleid, tuple);
1588
}
V
Vadim B. Mikheev 已提交
1589

M
 
Marc G. Fournier 已提交
1590
#ifdef NOT_USED
1591
static HeapTuple
1592
ExecAttrDefault(Relation rel, HeapTuple tuple)
V
Vadim B. Mikheev 已提交
1593
{
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
	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;
1606 1607 1608 1609 1610 1611

	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 */
1612 1613
	econtext->ecxt_param_list_info = NULL;		/* param list info */
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	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 已提交
1633
			MemSet(repl, ' ', rel->rd_att->natts * sizeof(char));
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
		}

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

	}

	pfree(econtext);

	if (repl == NULL)
1645
		return tuple;
1646

1647
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1648 1649

	pfree(repl);
1650
	heap_freetuple(tuple);
1651 1652 1653
	pfree(replNull);
	pfree(replValue);

1654
	return newtuple;
1655

V
Vadim B. Mikheev 已提交
1656
}
1657

1658
#endif
V
Vadim B. Mikheev 已提交
1659

1660
static char *
1661
ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1662
{
1663 1664 1665
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
	ExprContext *econtext = makeNode(ExprContext);
1666
	TupleTableSlot *slot = makeNode(TupleTableSlot);
1667 1668 1669 1670
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *rtlist;
	List	   *qual;
	int			i;
1671 1672 1673 1674 1675 1676 1677

	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;
1678
	rte->relname = RelationGetRelationName(rel);
1679 1680
	rte->ref = makeNode(Attr);
	rte->ref->relname = rte->relname;
1681
	rte->relid = RelationGetRelid(rel);
1682
	/* inh, inFromCl, inJoinSet, skipAcl won't be used, leave them zero */
1683 1684 1685 1686 1687 1688 1689
	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 已提交
1690
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1691 1692
	econtext->ecxt_range_table = rtlist;		/* range table */

1693 1694 1695
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1696
			(List **) palloc(ncheck * sizeof(List *));
1697 1698 1699 1700 1701 1702 1703 1704

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

1705 1706
	for (i = 0; i < ncheck; i++)
	{
1707
		qual = estate->es_result_relation_constraints[i];
1708

1709 1710 1711 1712 1713 1714
		/*
		 * 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))
1715
			return check[i].ccname;
1716 1717 1718 1719 1720 1721 1722
	}

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

1723
	return (char *) NULL;
1724

V
Vadim B. Mikheev 已提交
1725 1726
}

1727
void
1728
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1729
{
1730 1731 1732 1733

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1734
	{
1735
		int			attrChk;
1736 1737 1738 1739

		for (attrChk = 1; attrChk <= rel->rd_att->natts; attrChk++)
		{
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
1740
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1741
				  caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1742 1743 1744 1745 1746
		}
	}

	if (rel->rd_att->constr->num_check > 0)
	{
1747
		char	   *failed;
1748

1749
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1750
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1751 1752
	}

1753
	return;
V
Vadim B. Mikheev 已提交
1754
}
1755

B
Bruce Momjian 已提交
1756
TupleTableSlot *
1757 1758
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1759 1760 1761 1762 1763 1764 1765
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1766 1767 1768 1769 1770

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1771 1772
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1773 1774 1775 1776 1777 1778
		epq->rti = rti;
		endNode = false;
	}

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

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

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1858 1859
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1860 1861
	 */
	if (endNode)
1862
	{
1863
		ExecEndNode(epq->plan, epq->plan);
1864 1865
	    epqstate->es_tupleTable->next = 0;
	}
1866 1867 1868 1869

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1870
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1871 1872 1873 1874
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1875
	if (estate->es_result_relation_info != NULL &&
1876 1877 1878 1879
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1880
		List	   *l;
1881

B
Bruce Momjian 已提交
1882
		foreach(l, estate->es_rowMark)
1883
		{
B
Bruce Momjian 已提交
1884
			if (((execRowMark *) lfirst(l))->rti == rti)
1885 1886
				break;
		}
B
Bruce Momjian 已提交
1887
		relation = ((execRowMark *) lfirst(l))->relation;
1888 1889
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1890
	for (;;)
1891 1892 1893 1894 1895 1896 1897
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1898 1899 1900 1901 1902
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1903

1904
			/*
B
Bruce Momjian 已提交
1905 1906
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1907 1908 1909 1910 1911 1912 1913
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1914

1915 1916 1917
			/*
			 * Nice! We got tuple - now copy it.
			 */
1918
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1919
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1920 1921 1922 1923
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1924

1925 1926
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1927 1928
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1929
		 */
B
Bruce Momjian 已提交
1930
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1931 1932 1933 1934 1935
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1936

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

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1960 1961 1962 1963
		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));
1964
    Assert(epqstate->es_tupleTable->next == 0);
1965 1966 1967
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1968 1969
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1970 1971 1972 1973 1974 1975
	 */
	*tid = tuple.t_self;

	return (EvalPlanQualNext(estate));
}

B
Bruce Momjian 已提交
1976
static TupleTableSlot *
1977 1978
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1979 1980 1981 1982
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994

	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);
1995
	    epqstate->es_tupleTable->next = 0;
1996
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1997 1998
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1999 2000
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
2001 2002 2003 2004
		{
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and	  */
			return (NULL);					/* continue Query execution   */
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
		}
		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);
}
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049

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

	if (epq->rti == 0)			/* still live? */
		return;

	for (;;)
	{
		ExecEndNode(epq->plan, epq->plan);
	    epqstate->es_tupleTable->next = 0;
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
		{
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free */
			break;
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
		epqstate = &(epq->estate);
		estate->es_evalPlanQual = (Pointer) epq;
	}
}