execMain.c 44.9 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.105 2000/01/17 23:57:45 tgl 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
				/*
726 727
				 * Advance command counter so that the newly-created
				 * relation's catalog tuples will be visible to heap_open.
728
				 */
729
				CommandCounterIncrement();
730

731 732
				intoRelationDesc = heap_open(intoRelationId,
											 AccessExclusiveLock);
733 734 735 736 737 738
			}
		}
	}

	estate->es_into_relation_descriptor = intoRelationDesc;

739 740 741 742 743
	estate->es_origPlan = plan;
	estate->es_evalPlanQual = NULL;
	estate->es_evTuple = NULL;
	estate->es_useEvalPlan = false;

744
	return tupType;
745 746 747
}

/* ----------------------------------------------------------------
748 749 750
 *		EndPlan
 *
 *		Cleans up the query plan -- closes files and free up storages
751 752 753
 * ----------------------------------------------------------------
 */
static void
754
EndPlan(Plan *plan, EState *estate)
755
{
756 757
	RelationInfo *resultRelationInfo;
	Relation	intoRelationDesc;
758

B
Bruce Momjian 已提交
759
	/*
B
Bruce Momjian 已提交
760
	 * get information from state
761
	 */
762 763 764
	resultRelationInfo = estate->es_result_relation_info;
	intoRelationDesc = estate->es_into_relation_descriptor;

B
Bruce Momjian 已提交
765
	/*
B
Bruce Momjian 已提交
766
	 * shut down the query
767 768 769
	 */
	ExecEndNode(plan, plan);

B
Bruce Momjian 已提交
770
	/*
B
Bruce Momjian 已提交
771
	 * destroy the executor "tuple" table.
772 773
	 */
	{
774
		TupleTable	tupleTable = (TupleTable) estate->es_tupleTable;
775

776
		ExecDropTupleTable(tupleTable, true);
777 778 779
		estate->es_tupleTable = NULL;
	}

B
Bruce Momjian 已提交
780
	/*
781 782
	 * close the result relations if necessary,
	 * but hold locks on them until xact commit
783 784 785
	 */
	if (resultRelationInfo != NULL)
	{
786
		Relation	resultRelationDesc;
787 788

		resultRelationDesc = resultRelationInfo->ri_RelationDesc;
789
		heap_close(resultRelationDesc, NoLock);
790

B
Bruce Momjian 已提交
791
		/*
B
Bruce Momjian 已提交
792
		 * close indices on the result relation
793 794 795 796
		 */
		ExecCloseIndices(resultRelationInfo);
	}

B
Bruce Momjian 已提交
797
	/*
B
Bruce Momjian 已提交
798
	 * close the "into" relation if necessary
799 800
	 */
	if (intoRelationDesc != NULL)
801
		heap_close(intoRelationDesc, NoLock);
802 803 804
}

/* ----------------------------------------------------------------
805 806 807 808 809 810 811 812
 *		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.
813 814 815 816 817 818 819 820
 *
 * ----------------------------------------------------------------
 */

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

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

B
Bruce Momjian 已提交
836
	/*
B
Bruce Momjian 已提交
837
	 * initialize local variables
838
	 */
839 840 841 842
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
843 844
	/*
	 * Set the direction.
845
	 */
846 847
	estate->es_direction = direction;

B
Bruce Momjian 已提交
848
	/*
B
Bruce Momjian 已提交
849 850
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
851 852 853 854
	 */

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

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

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

B
Bruce Momjian 已提交
880
		/*
B
Bruce Momjian 已提交
881 882 883
		 * 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
884 885 886 887 888 889 890
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

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

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

				if (isNull)
918
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
919 920 921 922 923 924

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

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

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
979 980
							 */
							goto lnext;
981 982 983

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
984
							return (NULL);
985 986 987
					}
				}
			}
988

B
Bruce Momjian 已提交
989
			/*
990 991 992 993 994 995 996 997 998 999 1000 1001
			 * 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 已提交
1002
		/*
B
Bruce Momjian 已提交
1003 1004
		 * 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 已提交
1005
		 * delete it from a relation, or modify some of its attributes.
1006 1007 1008 1009
		 */

		switch (operation)
		{
1010 1011
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1012 1013
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1014 1015 1016
							 estate);	/* */
				result = slot;
				break;
1017

1018 1019 1020 1021
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1022

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

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

1033 1034
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1035
				result = NULL;
1036
				break;
1037
		}
B
Bruce Momjian 已提交
1038

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

B
Bruce Momjian 已提交
1048
	/*
B
Bruce Momjian 已提交
1049 1050
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1051
	 */
1052
	return result;
1053 1054 1055
}

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

B
Bruce Momjian 已提交
1073
	/*
B
Bruce Momjian 已提交
1074
	 * get the heap tuple out of the tuple table slot
1075 1076 1077 1078
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1079
	/*
B
Bruce Momjian 已提交
1080
	 * insert the tuple into the "into relation"
1081 1082 1083 1084 1085 1086 1087
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1088
	/*
B
Bruce Momjian 已提交
1089
	 * send the tuple to the front end (or the screen)
1090
	 */
1091
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1092 1093
	IncrRetrieved();
	(estate->es_processed)++;
1094 1095 1096
}

/* ----------------------------------------------------------------
1097
 *		ExecAppend
1098
 *
1099 1100 1101
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1102 1103 1104 1105
 * ----------------------------------------------------------------
 */

static void
1106
ExecAppend(TupleTableSlot *slot,
1107
		   ItemPointer tupleid,
1108
		   EState *estate)
1109
{
1110 1111 1112 1113 1114
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1115

B
Bruce Momjian 已提交
1116
	/*
B
Bruce Momjian 已提交
1117
	 * get the heap tuple out of the tuple table slot
1118 1119 1120
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1121
	/*
B
Bruce Momjian 已提交
1122
	 * get information on the result relation
1123 1124 1125 1126
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1127
	/*
B
Bruce Momjian 已提交
1128
	 * have to add code to preform unique checking here. cim -12/1/89
1129 1130 1131 1132 1133 1134
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1135
		HeapTuple	newtuple;
1136 1137 1138 1139 1140 1141 1142 1143 1144

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1145
			heap_freetuple(tuple);
1146 1147 1148 1149
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1150
	/*
1151 1152 1153 1154
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1155
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1156

B
Bruce Momjian 已提交
1157
	/*
B
Bruce Momjian 已提交
1158
	 * insert the tuple
1159 1160 1161 1162 1163
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

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

	/* AFTER ROW INSERT Triggers */
1178
	if (resultRelationDesc->trigdesc)
1179
		ExecARInsertTriggers(resultRelationDesc, tuple);
1180 1181 1182
}

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

B
Bruce Momjian 已提交
1199
	/*
B
Bruce Momjian 已提交
1200
	 * get the result relation information
1201 1202 1203 1204 1205 1206 1207 1208
	 */
	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)
	{
1209
		bool		dodelete;
1210

V
Vadim B. Mikheev 已提交
1211
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1212 1213 1214 1215 1216

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

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

		case HeapTupleMayBeUpdated:
			break;

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

V
Vadim B. Mikheev 已提交
1238
				if (!TupIsNull(epqslot))
1239 1240 1241 1242 1243
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1244 1245 1246 1247 1248 1249
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1250 1251 1252 1253

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

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

	/* AFTER ROW DELETE Triggers */
1264
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1265
		ExecARDeleteTriggers(estate, tupleid);
1266 1267 1268 1269

}

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

B
Bruce Momjian 已提交
1292
	/*
B
Bruce Momjian 已提交
1293
	 * abort the operation if not running transactions
1294 1295 1296 1297 1298 1299 1300
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1301
	/*
B
Bruce Momjian 已提交
1302
	 * get the heap tuple out of the tuple table slot
1303 1304 1305
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1306
	/*
B
Bruce Momjian 已提交
1307
	 * get the result relation information
1308 1309 1310 1311
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1312
	/*
B
Bruce Momjian 已提交
1313 1314 1315
	 * 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
1316 1317 1318 1319 1320 1321
	 */

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

V
Vadim B. Mikheev 已提交
1324
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1325 1326 1327 1328 1329 1330 1331

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1332
			heap_freetuple(tuple);
1333 1334 1335 1336
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1337
	/*
1338 1339 1340 1341
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1342
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1343

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

		case HeapTupleMayBeUpdated:
			break;

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

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

		default:
1376
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1377
			return;
1378 1379 1380 1381 1382
	}

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

B
Bruce Momjian 已提交
1383
	/*
B
Bruce Momjian 已提交
1384 1385 1386 1387 1388
	 * 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
1389 1390
	 */

B
Bruce Momjian 已提交
1391
	/*
B
Bruce Momjian 已提交
1392
	 * process indices
1393
	 *
1394
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1395 1396 1397 1398
	 * 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.
1399 1400 1401 1402
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1403
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1404 1405

	/* AFTER ROW UPDATE Triggers */
1406
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1407
		ExecARUpdateTriggers(estate, tupleid, tuple);
1408
}
V
Vadim B. Mikheev 已提交
1409

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

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

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

	}

	pfree(econtext);

	if (repl == NULL)
1465
		return tuple;
1466

1467
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1468 1469

	pfree(repl);
1470
	heap_freetuple(tuple);
1471 1472 1473
	pfree(replNull);
	pfree(replValue);

1474
	return newtuple;
1475

V
Vadim B. Mikheev 已提交
1476
}
1477

1478
#endif
V
Vadim B. Mikheev 已提交
1479

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

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

1513 1514 1515
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1516
			(List **) palloc(ncheck * sizeof(List *));
1517 1518 1519 1520 1521 1522 1523 1524

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

1525 1526
	for (i = 0; i < ncheck; i++)
	{
1527
		qual = estate->es_result_relation_constraints[i];
1528 1529 1530 1531

		res = ExecQual(qual, econtext);

		if (!res)
1532
			return check[i].ccname;
1533 1534 1535 1536 1537 1538 1539
	}

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

1540
	return (char *) NULL;
1541

V
Vadim B. Mikheev 已提交
1542 1543
}

1544
void
1545
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1546
{
1547 1548 1549 1550

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1551
	{
1552
		int			attrChk;
1553 1554 1555 1556

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

	if (rel->rd_att->constr->num_check > 0)
	{
1564
		char	   *failed;
1565

1566
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1567
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1568 1569
	}

1570
	return;
V
Vadim B. Mikheev 已提交
1571
}
1572

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

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1588 1589
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1590 1591 1592 1593 1594 1595
		epq->rti = rti;
		endNode = false;
	}

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

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

	epqstate = &(epq->estate);

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

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1687
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1688 1689 1690 1691
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1692
	if (estate->es_result_relation_info != NULL &&
1693 1694 1695 1696
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1697
		List	   *l;
1698

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

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1715 1716 1717 1718 1719
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1720

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

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

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

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

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1777 1778 1779 1780
		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));
1781
    Assert(epqstate->es_tupleTable->next == 0);
1782 1783 1784
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1785 1786
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1787 1788 1789 1790 1791 1792
	 */
	*tid = tuple.t_self;

	return (EvalPlanQualNext(estate));
}

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

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