execMain.c 45.1 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 25 26 27 28
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
29
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.103 1999/12/16 22:19:44 wieck Exp $
30 31 32
 *
 *-------------------------------------------------------------------------
 */
33 34
#include "postgres.h"

35 36
#include "access/heapam.h"
#include "catalog/heap.h"
37
#include "commands/trigger.h"
B
Bruce Momjian 已提交
38 39 40 41 42 43 44 45 46
#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"
47

48
void ExecCheckPerms(CmdType operation, int resultRelation, List *rangeTable,
49
			   Query *parseTree);
50 51 52


/* decls for local routines only used within this module */
53
static TupleDesc InitPlan(CmdType operation,
B
Bruce Momjian 已提交
54 55 56
		 Query *parseTree,
		 Plan *plan,
		 EState *estate);
57
static void EndPlan(Plan *plan,
B
Bruce Momjian 已提交
58
		EState *estate);
59
static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
B
Bruce Momjian 已提交
60 61 62 63
			CmdType operation,
			int offsetTuples,
			int numberTuples,
			ScanDirection direction,
64
			DestReceiver *destfunc);
65
static void ExecRetrieve(TupleTableSlot *slot,
66
			 DestReceiver *destfunc,
B
Bruce Momjian 已提交
67
			 EState *estate);
68
static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
69
		   EState *estate);
70
static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
71
		   EState *estate);
72
static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
73
			EState *estate);
74 75 76 77

TupleTableSlot *EvalPlanQual(EState *estate, Index rti, ItemPointer tid);
static TupleTableSlot *EvalPlanQualNext(EState *estate);

78 79 80 81

/* end of local decls */

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

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

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

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

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

	return result;
134 135 136
}

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

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

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

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

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

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

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

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

225
				break;
B
Bruce Momjian 已提交
226

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

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

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

279 280 281
	switch (feature)
	{

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

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

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

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

335
	return result;
336 337 338
}

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

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

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

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

380
void
381
ExecCheckPerms(CmdType operation,
382
			   int resultRelation,
383 384
			   List *rangeTable,
			   Query *parseTree)
385
{
386
	int			rtindex = 0;
387 388 389 390 391 392
	List	   *lp;
	List	   *qvars,
			   *tvars;
	int32		ok = 1,
				aclcheck_result = -1;
	char	   *opstr;
393
	char	   *relName = NULL;
394
	char	   *userName;
395

396
#define CHECK(MODE)		pg_aclcheck(relName, userName, MODE)
397 398 399 400 401

	userName = GetPgUserName();

	foreach(lp, rangeTable)
	{
402
		RangeTblEntry *rte = lfirst(lp);
403

404 405
		++rtindex;

M
Marc G. Fournier 已提交
406 407
		if (rte->skipAcl)
		{
408

M
Marc G. Fournier 已提交
409
			/*
410 411 412 413
			 * This happens if the access to this table is due to a view
			 * query rewriting - the rewrite handler checked the
			 * permissions against the view owner, so we just skip this
			 * entry.
M
Marc G. Fournier 已提交
414 415 416 417
			 */
			continue;
		}

418 419
		relName = rte->relname;
		if (rtindex == resultRelation)
420 421 422 423 424 425 426 427 428 429 430 431 432 433
		{						/* this is the result relation */
			qvars = pull_varnos(parseTree->qual);
			tvars = pull_varnos((Node *) parseTree->targetList);
			if (intMember(resultRelation, qvars) ||
				intMember(resultRelation, tvars))
			{
				/* result relation is scanned */
				ok = ((aclcheck_result = CHECK(ACL_RD)) == ACLCHECK_OK);
				opstr = "read";
				if (!ok)
					break;
			}
			switch (operation)
			{
434 435 436 437 438 439 440 441 442 443 444
				case CMD_INSERT:
					ok = ((aclcheck_result = CHECK(ACL_AP)) == ACLCHECK_OK) ||
						((aclcheck_result = CHECK(ACL_WR)) == ACLCHECK_OK);
					opstr = "append";
					break;
				case CMD_DELETE:
				case CMD_UPDATE:
					ok = ((aclcheck_result = CHECK(ACL_WR)) == ACLCHECK_OK);
					opstr = "write";
					break;
				default:
445
					elog(ERROR, "ExecCheckPerms: bogus operation %d",
446
						 operation);
447 448 449 450 451 452 453
			}
		}
		else
		{
			ok = ((aclcheck_result = CHECK(ACL_RD)) == ACLCHECK_OK);
			opstr = "read";
		}
454
		if (!ok)
455
			break;
456 457
	}
	if (!ok)
458
		elog(ERROR, "%s: %s", relName, aclcheck_error_strings[aclcheck_result]);
459

T
Tom Lane 已提交
460
	if (parseTree != NULL && parseTree->rowMark != NULL)
461 462 463
	{
		foreach(lp, parseTree->rowMark)
		{
B
Bruce Momjian 已提交
464
			RowMark    *rm = lfirst(lp);
465 466 467 468

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

469
			relName = rt_fetch(rm->rti, rangeTable)->relname;
470 471 472
			ok = ((aclcheck_result = CHECK(ACL_WR)) == ACLCHECK_OK);
			opstr = "write";
			if (!ok)
473
				elog(ERROR, "%s: %s", relName, aclcheck_error_strings[aclcheck_result]);
474 475
		}
	}
476 477
}

478 479 480 481 482 483 484
/* ===============================================================
 * ===============================================================
						 static routines follow
 * ===============================================================
 * ===============================================================
 */

485 486 487
typedef struct execRowMark
{
	Relation	relation;
488
	Index		rti;
489
	char		resname[32];
490
} execRowMark;
491

492 493
typedef struct evalPlanQual
{
B
Bruce Momjian 已提交
494 495 496 497
	Plan	   *plan;
	Index		rti;
	EState		estate;
	struct evalPlanQual *free;
498
} evalPlanQual;
499

500
/* ----------------------------------------------------------------
501 502 503 504
 *		InitPlan
 *
 *		Initializes the query plan: open files, allocate storage
 *		and start up the rule manager
505 506
 * ----------------------------------------------------------------
 */
507
static TupleDesc
508
InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
509
{
B
Bruce Momjian 已提交
510 511 512 513 514
	List	   *rangeTable;
	int			resultRelation;
	Relation	intoRelationDesc;
	TupleDesc	tupType;
	List	   *targetList;
515

B
Bruce Momjian 已提交
516
	/*
B
Bruce Momjian 已提交
517
	 * get information from query descriptor
518
	 */
519 520
	rangeTable = parseTree->rtable;
	resultRelation = parseTree->resultRelation;
521

522 523 524 525
#ifndef NO_SECURITY
	ExecCheckPerms(operation, resultRelation, rangeTable, parseTree);
#endif

B
Bruce Momjian 已提交
526
	/*
B
Bruce Momjian 已提交
527
	 * initialize the node's execution state
528
	 */
529 530
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
531
	/*
B
Bruce Momjian 已提交
532 533 534
	 * 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.
535
	 */
536
	estate->es_BaseId = 1;
537

B
Bruce Momjian 已提交
538
	/*
B
Bruce Momjian 已提交
539
	 * initialize result relation stuff
540
	 */
B
Bruce Momjian 已提交
541

542 543
	if (resultRelation != 0 && operation != CMD_SELECT)
	{
B
Bruce Momjian 已提交
544

B
Bruce Momjian 已提交
545
		/*
B
Bruce Momjian 已提交
546 547
		 * if we have a result relation, open it and initialize the result
		 * relation info stuff.
548
		 */
549 550 551 552 553
		RelationInfo *resultRelationInfo;
		Index		resultRelationIndex;
		RangeTblEntry *rtentry;
		Oid			resultRelationOid;
		Relation	resultRelationDesc;
554 555 556 557

		resultRelationIndex = resultRelation;
		rtentry = rt_fetch(resultRelationIndex, rangeTable);
		resultRelationOid = rtentry->relid;
558
		resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
559 560

		if (resultRelationDesc->rd_rel->relkind == RELKIND_SEQUENCE)
561
			elog(ERROR, "You can't change sequence relation %s",
562
				 RelationGetRelationName(resultRelationDesc));
563 564 565 566 567 568 569

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

B
Bruce Momjian 已提交
571
		/*
572 573 574 575
		 * 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.
576
		 */
577 578
		if (resultRelationDesc->rd_rel->relhasindex &&
			operation != CMD_DELETE)
V
Vadim B. Mikheev 已提交
579
			ExecOpenIndices(resultRelationOid, resultRelationInfo);
580 581

		estate->es_result_relation_info = resultRelationInfo;
582
	}
583 584
	else
	{
B
Bruce Momjian 已提交
585

B
Bruce Momjian 已提交
586
		/*
B
Bruce Momjian 已提交
587
		 * if no result relation, then set state appropriately
588 589 590 591
		 */
		estate->es_result_relation_info = NULL;
	}

592 593 594 595 596 597
	/*
	 * Have to lock relations selected for update
	 */
	estate->es_rowMark = NULL;
	if (parseTree->rowMark != NULL)
	{
B
Bruce Momjian 已提交
598 599 600 601 602
		Relation	relation;
		Oid			relid;
		RowMark    *rm;
		List	   *l;
		execRowMark *erm;
603 604 605 606

		foreach(l, parseTree->rowMark)
		{
			rm = lfirst(l);
607
			relid = rt_fetch(rm->rti, rangeTable)->relid;
608
			relation = heap_open(relid, RowShareLock);
609 610
			if (!(rm->info & ROW_MARK_FOR_UPDATE))
				continue;
B
Bruce Momjian 已提交
611
			erm = (execRowMark *) palloc(sizeof(execRowMark));
612
			erm->relation = relation;
613
			erm->rti = rm->rti;
614 615 616 617
			sprintf(erm->resname, "ctid%u", rm->rti);
			estate->es_rowMark = lappend(estate->es_rowMark, erm);
		}
	}
618

B
Bruce Momjian 已提交
619
	/*
B
Bruce Momjian 已提交
620
	 * initialize the executor "tuple" table.
621 622
	 */
	{
623 624
		int			nSlots = ExecCountSlotsNode(plan);
		TupleTable	tupleTable = ExecCreateTupleTable(nSlots + 10);		/* why add ten? - jolly */
625

626 627
		estate->es_tupleTable = tupleTable;
	}
628

B
Bruce Momjian 已提交
629
	/*
B
Bruce Momjian 已提交
630 631 632
	 * 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..
633 634 635
	 */
	ExecInitNode(plan, estate, NULL);

B
Bruce Momjian 已提交
636
	/*
B
Bruce Momjian 已提交
637 638 639
	 * get the tuple descriptor describing the type of tuples to return..
	 * (this is especially important if we are creating a relation with
	 * "retrieve into")
640 641 642 643
	 */
	tupType = ExecGetTupType(plan);		/* tuple descriptor */
	targetList = plan->targetlist;

B
Bruce Momjian 已提交
644
	/*
645 646 647 648
	 * 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.
649 650
	 */
	{
651 652 653
		bool		junk_filter_needed = false;
		List	   *tlist;

654
		switch (operation)
655
		{
656 657 658
			case CMD_SELECT:
			case CMD_INSERT:
				foreach(tlist, targetList)
659
				{
660 661 662 663 664 665 666
					TargetEntry *tle = (TargetEntry *) lfirst(tlist);

					if (tle->resdom->resjunk)
					{
						junk_filter_needed = true;
						break;
					}
667
				}
668 669 670 671 672 673 674
				break;
			case CMD_UPDATE:
			case CMD_DELETE:
				junk_filter_needed = true;
				break;
			default:
				break;
675 676
		}

677
		if (junk_filter_needed)
678
		{
679
			JunkFilter *j = ExecInitJunkFilter(targetList, tupType);
680

681
			estate->es_junkFilter = j;
682

683 684 685 686 687 688
			if (operation == CMD_SELECT)
				tupType = j->jf_cleanTupType;
		}
		else
			estate->es_junkFilter = NULL;
	}
689

B
Bruce Momjian 已提交
690
	/*
B
Bruce Momjian 已提交
691
	 * initialize the "into" relation
692 693 694 695 696
	 */
	intoRelationDesc = (Relation) NULL;

	if (operation == CMD_SELECT)
	{
697 698 699
		char	   *intoName;
		Oid			intoRelationId;
		TupleDesc	tupdesc;
700 701 702 703 704 705 706 707 708

		if (!parseTree->isPortal)
		{

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

B
Bruce Momjian 已提交
710
				/*
B
Bruce Momjian 已提交
711
				 * create the "into" relation
712 713 714 715 716 717 718 719
				 */
				intoName = parseTree->into;

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

720
				intoRelationId = heap_create_with_catalog(intoName,
B
Bruce Momjian 已提交
721
						   tupdesc, RELKIND_RELATION, parseTree->isTemp);
722

723 724
				FreeTupleDesc(tupdesc);

B
Bruce Momjian 已提交
725
				/*
B
Bruce Momjian 已提交
726 727 728
				 * XXX rather than having to call setheapoverride(true)
				 * and then back to false, we should change the arguments
				 * to heap_open() instead..
729 730
				 *
				 * XXX no, we should use commandCounterIncrement...
731 732 733
				 */
				setheapoverride(true);

734 735
				intoRelationDesc = heap_open(intoRelationId,
											 AccessExclusiveLock);
736 737 738 739 740 741 742 743

				setheapoverride(false);
			}
		}
	}

	estate->es_into_relation_descriptor = intoRelationDesc;

744 745 746 747 748
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_useEvalPlan = false;

749
	return tupType;
750 751 752
}

/* ----------------------------------------------------------------
753 754 755
 *		EndPlan
 *
 *		Cleans up the query plan -- closes files and free up storages
756 757 758
 * ----------------------------------------------------------------
 */
static void
759
EndPlan(Plan *plan, EState *estate)
760
{
761 762
	RelationInfo *resultRelationInfo;
	Relation	intoRelationDesc;
763

B
Bruce Momjian 已提交
764
	/*
B
Bruce Momjian 已提交
765
	 * get information from state
766
	 */
767 768 769
	resultRelationInfo = estate->es_result_relation_info;
	intoRelationDesc = estate->es_into_relation_descriptor;

B
Bruce Momjian 已提交
770
	/*
B
Bruce Momjian 已提交
771
	 * shut down the query
772 773 774
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
775
	/*
B
Bruce Momjian 已提交
776
	 * destroy the executor "tuple" table.
777 778
	 */
	{
779
		TupleTable	tupleTable = (TupleTable) estate->es_tupleTable;
780

781
		ExecDropTupleTable(tupleTable, true);
782 783 784
		estate->es_tupleTable = NULL;
	}

B
Bruce Momjian 已提交
785
	/*
786 787
	 * close the result relations if necessary,
	 * but hold locks on them until xact commit
788 789 790
	 */
	if (resultRelationInfo != NULL)
	{
791
		Relation	resultRelationDesc;
792 793

		resultRelationDesc = resultRelationInfo->ri_RelationDesc;
794
		heap_close(resultRelationDesc, NoLock);
795

B
Bruce Momjian 已提交
796
		/*
B
Bruce Momjian 已提交
797
		 * close indices on the result relation
798 799 800 801
		 */
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
802
	/*
B
Bruce Momjian 已提交
803
	 * close the "into" relation if necessary
804 805
	 */
	if (intoRelationDesc != NULL)
806
		heap_close(intoRelationDesc, NoLock);
807 808 809
}

/* ----------------------------------------------------------------
810 811 812 813 814 815 816 817
 *		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.
818 819 820 821 822 823 824 825
 *
 * ----------------------------------------------------------------
 */

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

static TupleTableSlot *
826 827
ExecutePlan(EState *estate,
			Plan *plan,
828
			CmdType operation,
829
			int offsetTuples,
830 831
			int numberTuples,
			ScanDirection direction,
832
			DestReceiver *destfunc)
833
{
834
	JunkFilter *junkfilter;
835
	TupleTableSlot *slot;
836
	ItemPointer tupleid = NULL;
837
	ItemPointerData tuple_ctid;
838
	int			current_tuple_count;
839 840
	TupleTableSlot *result;

B
Bruce Momjian 已提交
841
	/*
B
Bruce Momjian 已提交
842
	 * initialize local variables
843
	 */
844 845 846 847
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
848 849
	/*
	 * Set the direction.
850
	 */
851 852
	estate->es_direction = direction;

B
Bruce Momjian 已提交
853
	/*
B
Bruce Momjian 已提交
854 855
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
856 857 858 859
	 */

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

B
Bruce Momjian 已提交
861
		/*
B
Bruce Momjian 已提交
862
		 * Execute the plan and obtain a tuple
863 864
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
865
lnext:	;
866 867 868 869 870 871 872 873
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
874

B
Bruce Momjian 已提交
875
		/*
B
Bruce Momjian 已提交
876 877
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
878 879 880 881 882
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
883 884
		}

B
Bruce Momjian 已提交
885
		/*
B
Bruce Momjian 已提交
886 887 888
		 * 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
889 890 891 892 893 894 895
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

B
Bruce Momjian 已提交
896
		/*
B
Bruce Momjian 已提交
897 898
		 * if we have a junk filter, then project a new tuple with the
		 * junk removed.
899
		 *
B
Bruce Momjian 已提交
900
		 * Store this new "clean" tuple in the place of the original tuple.
901
		 *
B
Bruce Momjian 已提交
902
		 * Also, extract all the junk information we need.
903 904 905
		 */
		if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
		{
906 907 908
			Datum		datum;
			HeapTuple	newTuple;
			bool		isNull;
909

B
Bruce Momjian 已提交
910
			/*
911 912 913 914 915 916 917 918 919
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
920
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
921 922

				if (isNull)
923
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
924 925 926 927 928 929

				tupleid = (ItemPointer) DatumGetPointer(datum);
				tuple_ctid = *tupleid;	/* make sure we don't free the
										 * ctid!! */
				tupleid = &tuple_ctid;
			}
930 931
			else if (estate->es_rowMark != NULL)
			{
B
Bruce Momjian 已提交
932 933 934 935
				List	   *l;
				execRowMark *erm;
				Buffer		buffer;
				HeapTupleData tuple;
936
				TupleTableSlot *newSlot;
B
Bruce Momjian 已提交
937
				int			test;
938

B
Bruce Momjian 已提交
939 940
		lmark:	;
				foreach(l, estate->es_rowMark)
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
				{
					erm = lfirst(l);
					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)
964
							{
965
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
966
								return (NULL);
967
							}
B
Bruce Momjian 已提交
968 969
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
970
							{
B
Bruce Momjian 已提交
971
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
972 973 974 975 976 977 978
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
979 980 981 982 983

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
984 985
							 */
							goto lnext;
986 987 988

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
989
							return (NULL);
990 991 992
					}
				}
			}
993

B
Bruce Momjian 已提交
994
			/*
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
			 * 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 已提交
1007
		/*
B
Bruce Momjian 已提交
1008 1009 1010
		 * now that we have a tuple, do the appropriate thing with it..
		 * either return it to the user, add it to a relation someplace,
		 * delete it from a relation, or modify some of it's attributes.
1011 1012 1013 1014
		 */

		switch (operation)
		{
1015 1016
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1017 1018
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1019 1020 1021
							 estate);	/* */
				result = slot;
				break;
1022

1023 1024 1025 1026
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1027

1028 1029 1030 1031
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1032

1033
			case CMD_UPDATE:
1034
				ExecReplace(slot, tupleid, estate);
1035 1036
				result = NULL;
				break;
1037

1038 1039
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1040
				result = NULL;
1041
				break;
1042
		}
B
Bruce Momjian 已提交
1043

B
Bruce Momjian 已提交
1044
		/*
B
Bruce Momjian 已提交
1045 1046
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1047 1048 1049 1050
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1051
	}
1052

B
Bruce Momjian 已提交
1053
	/*
B
Bruce Momjian 已提交
1054 1055
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1056
	 */
1057
	return result;
1058 1059 1060
}

/* ----------------------------------------------------------------
1061
 *		ExecRetrieve
1062
 *
1063 1064 1065 1066 1067
 *		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.)
1068 1069 1070
 * ----------------------------------------------------------------
 */
static void
1071
ExecRetrieve(TupleTableSlot *slot,
1072
			 DestReceiver *destfunc,
1073
			 EState *estate)
1074
{
1075 1076
	HeapTuple	tuple;
	TupleDesc	attrtype;
1077

B
Bruce Momjian 已提交
1078
	/*
B
Bruce Momjian 已提交
1079
	 * get the heap tuple out of the tuple table slot
1080 1081 1082 1083
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1084
	/*
B
Bruce Momjian 已提交
1085
	 * insert the tuple into the "into relation"
1086 1087 1088 1089 1090 1091 1092
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1093
	/*
B
Bruce Momjian 已提交
1094
	 * send the tuple to the front end (or the screen)
1095
	 */
1096
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1097 1098
	IncrRetrieved();
	(estate->es_processed)++;
1099 1100 1101
}

/* ----------------------------------------------------------------
1102
 *		ExecAppend
1103
 *
1104 1105 1106
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1107 1108 1109 1110
 * ----------------------------------------------------------------
 */

static void
1111
ExecAppend(TupleTableSlot *slot,
1112
		   ItemPointer tupleid,
1113
		   EState *estate)
1114
{
1115 1116 1117 1118 1119
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1120

B
Bruce Momjian 已提交
1121
	/*
B
Bruce Momjian 已提交
1122
	 * get the heap tuple out of the tuple table slot
1123 1124 1125
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1126
	/*
B
Bruce Momjian 已提交
1127
	 * get information on the result relation
1128 1129 1130 1131
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1132
	/*
B
Bruce Momjian 已提交
1133
	 * have to add code to preform unique checking here. cim -12/1/89
1134 1135 1136 1137 1138 1139
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1140
		HeapTuple	newtuple;
1141 1142 1143 1144 1145 1146 1147 1148 1149

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1150
			heap_freetuple(tuple);
1151 1152 1153 1154
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1155
	/*
1156 1157 1158 1159
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1160
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1161

B
Bruce Momjian 已提交
1162
	/*
B
Bruce Momjian 已提交
1163
	 * insert the tuple
1164 1165 1166 1167 1168
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

B
Bruce Momjian 已提交
1169
	/*
B
Bruce Momjian 已提交
1170
	 * process indices
1171
	 *
B
Bruce Momjian 已提交
1172 1173 1174
	 * 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.
1175 1176 1177
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1178
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1179 1180 1181 1182
	(estate->es_processed)++;
	estate->es_lastoid = newId;

	/* AFTER ROW INSERT Triggers */
1183
	if (resultRelationDesc->trigdesc)
1184
		ExecARInsertTriggers(resultRelationDesc, tuple);
1185 1186 1187
}

/* ----------------------------------------------------------------
1188
 *		ExecDelete
1189
 *
1190 1191
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1192 1193 1194
 * ----------------------------------------------------------------
 */
static void
1195
ExecDelete(TupleTableSlot *slot,
1196
		   ItemPointer tupleid,
1197
		   EState *estate)
1198
{
B
Bruce Momjian 已提交
1199 1200 1201 1202
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1203

B
Bruce Momjian 已提交
1204
	/*
B
Bruce Momjian 已提交
1205
	 * get the result relation information
1206 1207 1208 1209 1210 1211 1212 1213
	 */
	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)
	{
1214
		bool		dodelete;
1215

V
Vadim B. Mikheev 已提交
1216
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1217 1218 1219 1220 1221

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

V
Vadim B. Mikheev 已提交
1222
	/*
B
Bruce Momjian 已提交
1223
	 * delete the tuple
1224
	 */
1225
ldelete:;
V
Vadim B. Mikheev 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1236 1237
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1238 1239
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1240 1241
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1242

V
Vadim B. Mikheev 已提交
1243
				if (!TupIsNull(epqslot))
1244 1245 1246 1247 1248
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1249 1250 1251 1252 1253 1254
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1255 1256 1257 1258

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

B
Bruce Momjian 已提交
1259
	/*
B
Bruce Momjian 已提交
1260 1261
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1262
	 *
B
Bruce Momjian 已提交
1263 1264 1265
	 * ... 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
1266 1267 1268
	 */

	/* AFTER ROW DELETE Triggers */
1269
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1270
		ExecARDeleteTriggers(estate, tupleid);
1271 1272 1273 1274

}

/* ----------------------------------------------------------------
1275
 *		ExecReplace
1276
 *
1277 1278 1279 1280 1281 1282
 *		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..
1283 1284 1285
 * ----------------------------------------------------------------
 */
static void
1286
ExecReplace(TupleTableSlot *slot,
1287
			ItemPointer tupleid,
1288
			EState *estate)
1289
{
B
Bruce Momjian 已提交
1290 1291 1292 1293 1294 1295
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
	int			numIndices;
1296

B
Bruce Momjian 已提交
1297
	/*
B
Bruce Momjian 已提交
1298
	 * abort the operation if not running transactions
1299 1300 1301 1302 1303 1304 1305
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1306
	/*
B
Bruce Momjian 已提交
1307
	 * get the heap tuple out of the tuple table slot
1308 1309 1310
	 */
	tuple = slot->val;

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

B
Bruce Momjian 已提交
1317
	/*
B
Bruce Momjian 已提交
1318 1319 1320
	 * 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
1321 1322 1323 1324 1325 1326
	 */

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

V
Vadim B. Mikheev 已提交
1329
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1330 1331 1332 1333 1334 1335 1336

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1337
			heap_freetuple(tuple);
1338 1339 1340 1341
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1342
	/*
1343 1344 1345 1346
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1347
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1348

V
Vadim B. Mikheev 已提交
1349
	/*
B
Bruce Momjian 已提交
1350
	 * replace the heap tuple
1351
	 */
1352
lreplace:;
1353
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1363 1364
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1365 1366
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1367 1368
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1369

V
Vadim B. Mikheev 已提交
1370
				if (!TupIsNull(epqslot))
1371 1372
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1373 1374
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1375 1376 1377
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1378 1379 1380
			return;

		default:
1381
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1382
			return;
1383 1384 1385 1386 1387
	}

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

B
Bruce Momjian 已提交
1388
	/*
B
Bruce Momjian 已提交
1389 1390 1391 1392 1393
	 * 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
1394 1395
	 */

B
Bruce Momjian 已提交
1396
	/*
B
Bruce Momjian 已提交
1397
	 * process indices
1398
	 *
1399
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1400 1401 1402 1403
	 * 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.
1404 1405 1406 1407
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1408
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1409 1410

	/* AFTER ROW UPDATE Triggers */
1411
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1412
		ExecARUpdateTriggers(estate, tupleid, tuple);
1413
}
V
Vadim B. Mikheev 已提交
1414

M
 
Marc G. Fournier 已提交
1415
#ifdef NOT_USED
1416
static HeapTuple
1417
ExecAttrDefault(Relation rel, HeapTuple tuple)
V
Vadim B. Mikheev 已提交
1418
{
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
	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;
1431 1432 1433 1434 1435 1436

	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 */
1437 1438
	econtext->ecxt_param_list_info = NULL;		/* param list info */
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
	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 已提交
1458
			MemSet(repl, ' ', rel->rd_att->natts * sizeof(char));
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
		}

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

	}

	pfree(econtext);

	if (repl == NULL)
1470
		return tuple;
1471

1472
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1473 1474

	pfree(repl);
1475
	heap_freetuple(tuple);
1476 1477 1478
	pfree(replNull);
	pfree(replValue);

1479
	return newtuple;
1480

V
Vadim B. Mikheev 已提交
1481
}
1482

1483
#endif
V
Vadim B. Mikheev 已提交
1484

1485
static char *
1486
ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1487
{
1488 1489 1490
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
	ExprContext *econtext = makeNode(ExprContext);
1491
	TupleTableSlot *slot = makeNode(TupleTableSlot);
1492 1493 1494 1495 1496
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *rtlist;
	List	   *qual;
	bool		res;
	int			i;
1497 1498 1499 1500 1501 1502 1503

	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;
1504
	rte->relname = RelationGetRelationName(rel);
1505
	rte->refname = rte->relname;
1506
	rte->relid = RelationGetRelid(rel);
1507
	/* inh, inFromCl, inJoinSet, skipAcl won't be used, leave them zero */
1508 1509 1510 1511 1512 1513 1514
	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 已提交
1515
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1516 1517
	econtext->ecxt_range_table = rtlist;		/* range table */

1518 1519 1520
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1521
			(List **) palloc(ncheck * sizeof(List *));
1522 1523 1524 1525 1526 1527 1528 1529

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

1530 1531
	for (i = 0; i < ncheck; i++)
	{
1532
		qual = estate->es_result_relation_constraints[i];
1533 1534 1535 1536

		res = ExecQual(qual, econtext);

		if (!res)
1537
			return check[i].ccname;
1538 1539 1540 1541 1542 1543 1544
	}

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

1545
	return (char *) NULL;
1546

V
Vadim B. Mikheev 已提交
1547 1548
}

1549
void
1550
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1551
{
1552 1553 1554 1555

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1556
	{
1557
		int			attrChk;
1558 1559 1560 1561

		for (attrChk = 1; attrChk <= rel->rd_att->natts; attrChk++)
		{
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
1562
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1563
				  caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1564 1565 1566 1567 1568
		}
	}

	if (rel->rd_att->constr->num_check > 0)
	{
1569
		char	   *failed;
1570

1571
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1572
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1573 1574
	}

1575
	return;
V
Vadim B. Mikheev 已提交
1576
}
1577

B
Bruce Momjian 已提交
1578
TupleTableSlot *
1579 1580
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1581 1582 1583 1584 1585 1586 1587
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1588 1589 1590 1591 1592

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1593 1594
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1595 1596 1597 1598 1599 1600
		epq->rti = rti;
		endNode = false;
	}

	/*
	 * If this is request for another RTE - Ra, - then we have to check
B
Bruce Momjian 已提交
1601 1602 1603
	 * 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? -:))
1604
	 */
B
Bruce Momjian 已提交
1605
	if (epq != NULL && epq->rti != rti &&
1606 1607 1608 1609 1610 1611
		epq->estate.es_evTuple[rti - 1] != NULL)
	{
		do
		{
			/* pop previous PlanQual from the stack */
			epqstate = &(epq->estate);
B
Bruce Momjian 已提交
1612
			oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1613 1614 1615
			Assert(oldepq->rti != 0);
			/* stop execution */
			ExecEndNode(epq->plan, epq->plan);
1616
		    epqstate->es_tupleTable->next = 0;
1617
			heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1618 1619 1620 1621 1622 1623 1624 1625
			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 已提交
1626
	/*
1627 1628 1629 1630 1631 1632
	 * 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 已提交
1633
		evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1634

1635
		if (newepq == NULL)		/* first call or freePQ stack is empty */
1636
		{
B
Bruce Momjian 已提交
1637
			newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1638 1639 1640
			/* Init EState */
			epqstate = &(newepq->estate);
			memset(epqstate, 0, sizeof(EState));
B
Bruce Momjian 已提交
1641
			epqstate->type = T_EState;
1642 1643 1644 1645 1646 1647
			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 已提交
1648 1649 1650
					palloc(estate->es_origPlan->nParamExec *
						   sizeof(ParamExecData));
			epqstate->es_tupleTable =
1651 1652 1653 1654
				ExecCreateTupleTable(estate->es_tupleTable->size);
			/* ... rest */
			newepq->plan = copyObject(estate->es_origPlan);
			newepq->free = NULL;
B
Bruce Momjian 已提交
1655
			epqstate->es_evTupleNull = (bool *)
1656 1657
				palloc(length(estate->es_range_table) * sizeof(bool));
			if (epq == NULL)	/* first call */
1658
			{
B
Bruce Momjian 已提交
1659
				epqstate->es_evTuple = (HeapTuple *)
1660
					palloc(length(estate->es_range_table) * sizeof(HeapTuple));
B
Bruce Momjian 已提交
1661 1662
				memset(epqstate->es_evTuple, 0,
					 length(estate->es_range_table) * sizeof(HeapTuple));
1663 1664 1665 1666 1667 1668 1669 1670
			}
			else
				epqstate->es_evTuple = epq->estate.es_evTuple;
		}
		else
			epqstate = &(newepq->estate);
		/* push current PQ to the stack */
		epqstate->es_evalPlanQual = (Pointer) epq;
1671 1672
		epq = newepq;
		estate->es_evalPlanQual = (Pointer) epq;
1673 1674 1675 1676 1677 1678 1679
		epq->rti = rti;
		endNode = false;
	}

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1680 1681
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1682 1683
	 */
	if (endNode)
1684
	{
1685
		ExecEndNode(epq->plan, epq->plan);
1686 1687
	    epqstate->es_tupleTable->next = 0;
	}
1688 1689 1690 1691

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1692
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1693 1694 1695 1696
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1697
	if (estate->es_result_relation_info != NULL &&
1698 1699 1700 1701
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1702
		List	   *l;
1703

B
Bruce Momjian 已提交
1704
		foreach(l, estate->es_rowMark)
1705
		{
B
Bruce Momjian 已提交
1706
			if (((execRowMark *) lfirst(l))->rti == rti)
1707 1708
				break;
		}
B
Bruce Momjian 已提交
1709
		relation = ((execRowMark *) lfirst(l))->relation;
1710 1711
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1712
	for (;;)
1713 1714 1715 1716 1717 1718 1719
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1720 1721 1722 1723 1724
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1725

1726
			/*
B
Bruce Momjian 已提交
1727 1728
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1729 1730 1731 1732 1733 1734 1735
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1736

1737 1738 1739
			/*
			 * Nice! We got tuple - now copy it.
			 */
1740
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1741
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1742 1743 1744 1745
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1746

1747 1748
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1749 1750
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1751
		 */
B
Bruce Momjian 已提交
1752
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1753 1754 1755 1756 1757
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1758

1759
		/*
B
Bruce Momjian 已提交
1760 1761
		 * Deleted or updated by this transaction. Do not (re-)start
		 * execution of this PQ. Continue previous PQ.
1762
		 */
B
Bruce Momjian 已提交
1763
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
		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
1774 1775 1776 1777
		{									
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and      */
			return (NULL);					/* continue Query execution   */
1778 1779 1780 1781
		}
	}

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1782 1783 1784 1785
		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));
1786
    Assert(epqstate->es_tupleTable->next == 0);
1787 1788 1789
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1790 1791
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1792 1793 1794 1795 1796 1797
	 */
	*tid = tuple.t_self;

	return (EvalPlanQualNext(estate));
}

B
Bruce Momjian 已提交
1798
static TupleTableSlot *
1799 1800
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1801 1802 1803 1804
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

	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);
1817
	    epqstate->es_tupleTable->next = 0;
1818
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1819 1820
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1821 1822
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
1823 1824 1825 1826
		{
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and	  */
			return (NULL);					/* continue Query execution   */
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
		}
		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);
}