execMain.c 45.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * execMain.c
4
 *	  top level executor interface routines
5 6
 *
 * INTERFACE ROUTINES
7 8 9
 *	ExecutorStart()
 *	ExecutorRun()
 *	ExecutorEnd()
10
 *
11 12 13 14 15 16 17 18 19 20 21 22 23
 *	The old ExecutorMain() has been replaced by ExecutorStart(),
 *	ExecutorRun() and ExecutorEnd()
 *
 *	These three procedures are the external interfaces to the executor.
 *	In each case, the query descriptor and the execution state is required
 *	 as arguments
 *
 *	ExecutorStart() must be called at the beginning of any execution of any
 *	query plan and ExecutorEnd() should always be called at the end of
 *	execution of a plan.
 *
 *	ExecutorRun accepts 'feature' and 'count' arguments that specify whether
 *	the plan is to be executed forwards, backwards, and for how many tuples.
24
 *
B
Add:  
Bruce Momjian 已提交
25 26
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
27 28 29
 *
 *
 * IDENTIFICATION
30
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.109 2000/02/15 03:36:49 thomas Exp $
31 32 33
 *
 *-------------------------------------------------------------------------
 */
34 35
#include "postgres.h"

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

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


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

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

79 80 81 82

/* end of local decls */

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

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

V
Vadim B. Mikheev 已提交
101 102
	if (queryDesc->plantree->nParamExec > 0)
	{
103 104 105
		estate->es_param_exec_vals = (ParamExecData *)
			palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
		memset(estate->es_param_exec_vals, 0, queryDesc->plantree->nParamExec * sizeof(ParamExecData));
V
Vadim B. Mikheev 已提交
106
	}
107

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

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

	return result;
135 136 137
}

/* ----------------------------------------------------------------
138 139 140 141 142 143 144
 *		ExecutorRun
 *
 *		This is the main routine of the executor module. It accepts
 *		the query descriptor from the traffic cop and executes the
 *		query plan.
 *
 *		ExecutorStart must have been called already.
145
 *
146 147 148 149 150 151
 *		the different features supported are:
 *			 EXEC_RUN:	retrieve all tuples in the forward direction
 *			 EXEC_FOR:	retrieve 'count' number of tuples in the forward dir
 *			 EXEC_BACK: retrieve 'count' number of tuples in the backward dir
 *			 EXEC_RETONE: return one tuple but don't 'retrieve' it
 *						   used in postquel function processing
152 153 154 155
 *
 *
 * ----------------------------------------------------------------
 */
156
TupleTableSlot *
B
Bruce Momjian 已提交
157 158
ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature,
			Node *limoffset, Node *limcount)
159
{
B
Bruce Momjian 已提交
160 161
	CmdType		operation;
	Plan	   *plan;
162
	TupleTableSlot *result;
B
Bruce Momjian 已提交
163 164 165 166
	CommandDest dest;
	DestReceiver *destfunc;
	int			offset = 0;
	int			count = 0;
167

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

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

B
Bruce Momjian 已提交
184
	/*
B
Bruce Momjian 已提交
185 186 187 188
	 * FIXME: the dest setup function ought to be handed the tuple desc
	 * for the tuples to be output, but I'm not quite sure how to get that
	 * info at this point.	For now, passing NULL is OK because no
	 * existing dest setup function actually uses the pointer.
189 190 191
	 */
	(*destfunc->setup) (destfunc, (TupleDesc) NULL);

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

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

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

213 214 215 216 217 218 219 220 221 222 223
				if (paramLI == NULL)
					elog(ERROR, "parameter for limit offset not in executor state");
				for (i = 0; paramLI[i].kind != PARAM_INVALID; i++)
				{
					if (paramLI[i].kind == PARAM_NUM && paramLI[i].id == poffset->paramid)
						break;
				}
				if (paramLI[i].kind == PARAM_INVALID)
					elog(ERROR, "parameter for limit offset not in executor state");
				if (paramLI[i].isnull)
					elog(ERROR, "limit offset cannot be NULL value");
B
Bruce Momjian 已提交
224 225
				offset = (int) (paramLI[i].value);

226
				break;
B
Bruce Momjian 已提交
227

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

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

B
Bruce Momjian 已提交
236
	/*
B
Bruce Momjian 已提交
237
	 * if given get the count of the LIMIT clause
238 239 240
	 */
	if (limcount != NULL)
	{
B
Bruce Momjian 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
		Const	   *ccount;
		Param	   *pcount;
		ParamListInfo paramLI;
		int			i;

		switch (nodeTag(limcount))
		{
			case T_Const:
				ccount = (Const *) limcount;
				count = (int) (ccount->constvalue);
				break;

			case T_Param:
				pcount = (Param *) limcount;
				paramLI = estate->es_param_list_info;

				if (paramLI == NULL)
					elog(ERROR, "parameter for limit count not in executor state");
				for (i = 0; paramLI[i].kind != PARAM_INVALID; i++)
				{
					if (paramLI[i].kind == PARAM_NUM && paramLI[i].id == pcount->paramid)
						break;
				}
				if (paramLI[i].kind == PARAM_INVALID)
					elog(ERROR, "parameter for limit count not in executor state");
				if (paramLI[i].isnull)
					elog(ERROR, "limit count cannot be NULL value");
				count = (int) (paramLI[i].value);

				break;

			default:
				elog(ERROR, "unexpected node type %d as limit count", nodeTag(limcount));
		}

		if (count < 0)
			elog(ERROR, "limit count cannot be negative");
278 279
	}

280 281 282
	switch (feature)
	{

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

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

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

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

336
	return result;
337 338 339
}

/* ----------------------------------------------------------------
340 341 342 343 344 345 346
 *		ExecutorEnd
 *
 *		This routine must be called at the end of any execution of any
 *		query plan
 *
 *		returns (AttrInfo*) which describes the attributes of the tuples to
 *		be returned by the query.
347 348 349 350
 *
 * ----------------------------------------------------------------
 */
void
351
ExecutorEnd(QueryDesc *queryDesc, EState *estate)
352
{
353 354
	/* sanity checks */
	Assert(queryDesc != NULL);
355

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

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

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

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

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

	userName = GetPgUserName();

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

405 406
		++rtindex;

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

M
Marc G. Fournier 已提交
410
			/*
411 412 413 414
			 * 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 已提交
415 416 417 418
			 */
			continue;
		}

419 420
		relName = rte->relname;
		if (rtindex == resultRelation)
421 422 423 424 425 426 427 428 429 430 431 432 433 434
		{						/* 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)
			{
435 436 437 438 439 440 441 442 443 444 445
				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:
446
					elog(ERROR, "ExecCheckPerms: bogus operation %d",
447
						 operation);
448 449 450 451 452 453 454
			}
		}
		else
		{
			ok = ((aclcheck_result = CHECK(ACL_RD)) == ACLCHECK_OK);
			opstr = "read";
		}
455
		if (!ok)
456
			break;
457 458
	}
	if (!ok)
459
		elog(ERROR, "%s: %s", relName, aclcheck_error_strings[aclcheck_result]);
460

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

593 594 595 596 597 598
	/*
	 * Have to lock relations selected for update
	 */
	estate->es_rowMark = NULL;
	if (parseTree->rowMark != NULL)
	{
B
Bruce Momjian 已提交
599
		List	   *l;
600 601 602

		foreach(l, parseTree->rowMark)
		{
603 604 605 606 607
			RowMark    *rm = lfirst(l);
			Oid			relid;
			Relation	relation;
			execRowMark *erm;

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

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

627 628
		estate->es_tupleTable = tupleTable;
	}
629

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

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

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

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

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

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

682
			estate->es_junkFilter = j;
683

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

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

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

		if (!parseTree->isPortal)
		{

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

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

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

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

724 725
				FreeTupleDesc(tupdesc);

B
Bruce Momjian 已提交
726
				/*
727 728
				 * Advance command counter so that the newly-created
				 * relation's catalog tuples will be visible to heap_open.
729
				 */
730
				CommandCounterIncrement();
731

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

	estate->es_into_relation_descriptor = intoRelationDesc;

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

745
	return tupType;
746 747 748
}

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

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

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

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

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

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

		resultRelationDesc = resultRelationInfo->ri_RelationDesc;
791
		heap_close(resultRelationDesc, NoLock);
792

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

B
Bruce Momjian 已提交
799
	/*
800
	 * close the "into" relation if necessary, again keeping lock
801 802
	 */
	if (intoRelationDesc != NULL)
803
		heap_close(intoRelationDesc, NoLock);
804 805 806 807 808 809 810 811 812 813

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

		heap_close(erm->relation, NoLock);
	}
814 815 816
}

/* ----------------------------------------------------------------
817 818 819 820 821 822 823 824
 *		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.
825 826 827 828 829 830 831 832
 *
 * ----------------------------------------------------------------
 */

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

static TupleTableSlot *
833 834
ExecutePlan(EState *estate,
			Plan *plan,
835
			CmdType operation,
836
			int offsetTuples,
837 838
			int numberTuples,
			ScanDirection direction,
839
			DestReceiver *destfunc)
840
{
841
	JunkFilter *junkfilter;
842
	TupleTableSlot *slot;
843
	ItemPointer tupleid = NULL;
844
	ItemPointerData tuple_ctid;
845
	int			current_tuple_count;
846 847
	TupleTableSlot *result;

B
Bruce Momjian 已提交
848
	/*
B
Bruce Momjian 已提交
849
	 * initialize local variables
850
	 */
851 852 853 854
	slot = NULL;
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
855 856
	/*
	 * Set the direction.
857
	 */
858 859
	estate->es_direction = direction;

B
Bruce Momjian 已提交
860
	/*
B
Bruce Momjian 已提交
861 862
	 * Loop until we've processed the proper number of tuples from the
	 * plan..
863 864 865 866
	 */

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

B
Bruce Momjian 已提交
868
		/*
B
Bruce Momjian 已提交
869
		 * Execute the plan and obtain a tuple
870 871
		 */
		/* at the top level, the parent of a plan (2nd arg) is itself */
B
Bruce Momjian 已提交
872
lnext:	;
873 874 875 876 877 878 879 880
		if (estate->es_useEvalPlan)
		{
			slot = EvalPlanQualNext(estate);
			if (TupIsNull(slot))
				slot = ExecProcNode(plan, plan);
		}
		else
			slot = ExecProcNode(plan, plan);
881

B
Bruce Momjian 已提交
882
		/*
B
Bruce Momjian 已提交
883 884
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
885 886 887 888 889
		 */
		if (TupIsNull(slot))
		{
			result = NULL;
			break;
890 891
		}

B
Bruce Momjian 已提交
892
		/*
B
Bruce Momjian 已提交
893 894 895
		 * 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
896 897 898 899 900 901 902
		 */
		if (offsetTuples > 0)
		{
			--offsetTuples;
			continue;
		}

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

B
Bruce Momjian 已提交
917
			/*
918 919 920 921 922 923 924 925 926
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				if (!ExecGetJunkAttribute(junkfilter,
										  slot,
										  "ctid",
										  &datum,
										  &isNull))
927
					elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
928 929

				if (isNull)
930
					elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
931 932 933 934 935 936

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

B
Bruce Momjian 已提交
941 942
		lmark:	;
				foreach(l, estate->es_rowMark)
943
				{
944 945 946 947 948 949
					execRowMark *erm = lfirst(l);
					Buffer		buffer;
					HeapTupleData tuple;
					TupleTableSlot *newSlot;
					int			test;

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
					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)
971
							{
972
								elog(ERROR, "Can't serialize access due to concurrent update");
B
Bruce Momjian 已提交
973
								return (NULL);
974
							}
B
Bruce Momjian 已提交
975 976
							else if (!(ItemPointerEquals(&(tuple.t_self),
								  (ItemPointer) DatumGetPointer(datum))))
977
							{
B
Bruce Momjian 已提交
978
								newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
979 980 981 982 983 984 985
								if (!(TupIsNull(newSlot)))
								{
									slot = newSlot;
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
986 987 988 989 990

							/*
							 * if tuple was deleted or PlanQual failed for
							 * updated tuple - we have not return this
							 * tuple!
991 992
							 */
							goto lnext;
993 994 995

						default:
							elog(ERROR, "Unknown status %u from heap_mark4update", test);
B
Bruce Momjian 已提交
996
							return (NULL);
997 998 999
					}
				}
			}
1000

B
Bruce Momjian 已提交
1001
			/*
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
			 * 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 已提交
1014
		/*
B
Bruce Momjian 已提交
1015 1016
		 * 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 已提交
1017
		 * delete it from a relation, or modify some of its attributes.
1018 1019 1020 1021
		 */

		switch (operation)
		{
1022 1023
			case CMD_SELECT:
				ExecRetrieve(slot,		/* slot containing tuple */
B
Bruce Momjian 已提交
1024 1025
							 destfunc,	/* destination's tuple-receiver
										 * obj */
1026 1027 1028
							 estate);	/* */
				result = slot;
				break;
1029

1030 1031 1032 1033
			case CMD_INSERT:
				ExecAppend(slot, tupleid, estate);
				result = NULL;
				break;
1034

1035 1036 1037 1038
			case CMD_DELETE:
				ExecDelete(slot, tupleid, estate);
				result = NULL;
				break;
1039

1040
			case CMD_UPDATE:
1041
				ExecReplace(slot, tupleid, estate);
1042 1043
				result = NULL;
				break;
1044

1045 1046
			default:
				elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1047
				result = NULL;
1048
				break;
1049
		}
B
Bruce Momjian 已提交
1050

B
Bruce Momjian 已提交
1051
		/*
B
Bruce Momjian 已提交
1052 1053
		 * check our tuple count.. if we've returned the proper number
		 * then return, else loop again and process more tuples..
1054 1055 1056 1057
		 */
		current_tuple_count += 1;
		if (numberTuples == current_tuple_count)
			break;
1058
	}
1059

B
Bruce Momjian 已提交
1060
	/*
B
Bruce Momjian 已提交
1061 1062
	 * here, result is either a slot containing a tuple in the case of a
	 * RETRIEVE or NULL otherwise.
1063
	 */
1064
	return result;
1065 1066 1067
}

/* ----------------------------------------------------------------
1068
 *		ExecRetrieve
1069
 *
1070 1071 1072 1073 1074
 *		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.)
1075 1076 1077
 * ----------------------------------------------------------------
 */
static void
1078
ExecRetrieve(TupleTableSlot *slot,
1079
			 DestReceiver *destfunc,
1080
			 EState *estate)
1081
{
1082 1083
	HeapTuple	tuple;
	TupleDesc	attrtype;
1084

B
Bruce Momjian 已提交
1085
	/*
B
Bruce Momjian 已提交
1086
	 * get the heap tuple out of the tuple table slot
1087 1088 1089 1090
	 */
	tuple = slot->val;
	attrtype = slot->ttc_tupleDescriptor;

B
Bruce Momjian 已提交
1091
	/*
B
Bruce Momjian 已提交
1092
	 * insert the tuple into the "into relation"
1093 1094 1095 1096 1097 1098 1099
	 */
	if (estate->es_into_relation_descriptor != NULL)
	{
		heap_insert(estate->es_into_relation_descriptor, tuple);
		IncrAppended();
	}

B
Bruce Momjian 已提交
1100
	/*
B
Bruce Momjian 已提交
1101
	 * send the tuple to the front end (or the screen)
1102
	 */
1103
	(*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1104 1105
	IncrRetrieved();
	(estate->es_processed)++;
1106 1107 1108
}

/* ----------------------------------------------------------------
1109
 *		ExecAppend
1110
 *
1111 1112 1113
 *		APPENDs are trickier.. we have to insert the tuple into
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1114 1115 1116 1117
 * ----------------------------------------------------------------
 */

static void
1118
ExecAppend(TupleTableSlot *slot,
1119
		   ItemPointer tupleid,
1120
		   EState *estate)
1121
{
1122 1123 1124 1125 1126
	HeapTuple	tuple;
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	int			numIndices;
	Oid			newId;
1127

B
Bruce Momjian 已提交
1128
	/*
B
Bruce Momjian 已提交
1129
	 * get the heap tuple out of the tuple table slot
1130 1131 1132
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1133
	/*
B
Bruce Momjian 已提交
1134
	 * get information on the result relation
1135 1136 1137 1138
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1139
	/*
B
Bruce Momjian 已提交
1140
	 * have to add code to preform unique checking here. cim -12/1/89
1141 1142 1143 1144 1145 1146
	 */

	/* BEFORE ROW INSERT Triggers */
	if (resultRelationDesc->trigdesc &&
	resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
	{
1147
		HeapTuple	newtuple;
1148 1149 1150 1151 1152 1153 1154 1155 1156

		newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1157
			heap_freetuple(tuple);
1158 1159 1160 1161
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1162
	/*
1163 1164 1165 1166
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1167
		ExecConstraints("ExecAppend", resultRelationDesc, tuple, estate);
1168

B
Bruce Momjian 已提交
1169
	/*
B
Bruce Momjian 已提交
1170
	 * insert the tuple
1171 1172 1173 1174 1175
	 */
	newId = heap_insert(resultRelationDesc,		/* relation desc */
						tuple); /* heap tuple */
	IncrAppended();

B
Bruce Momjian 已提交
1176
	/*
B
Bruce Momjian 已提交
1177
	 * process indices
1178
	 *
B
Bruce Momjian 已提交
1179 1180 1181
	 * 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.
1182 1183 1184
	 */
	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1185
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1186 1187 1188 1189
	(estate->es_processed)++;
	estate->es_lastoid = newId;

	/* AFTER ROW INSERT Triggers */
1190
	if (resultRelationDesc->trigdesc)
1191
		ExecARInsertTriggers(resultRelationDesc, tuple);
1192 1193 1194
}

/* ----------------------------------------------------------------
1195
 *		ExecDelete
1196
 *
1197 1198
 *		DELETE is like append, we delete the tuple and its
 *		index tuples.
1199 1200 1201
 * ----------------------------------------------------------------
 */
static void
1202
ExecDelete(TupleTableSlot *slot,
1203
		   ItemPointer tupleid,
1204
		   EState *estate)
1205
{
B
Bruce Momjian 已提交
1206 1207 1208 1209
	RelationInfo *resultRelationInfo;
	Relation	resultRelationDesc;
	ItemPointerData ctid;
	int			result;
1210

B
Bruce Momjian 已提交
1211
	/*
B
Bruce Momjian 已提交
1212
	 * get the result relation information
1213 1214 1215 1216 1217 1218 1219 1220
	 */
	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)
	{
1221
		bool		dodelete;
1222

V
Vadim B. Mikheev 已提交
1223
		dodelete = ExecBRDeleteTriggers(estate, tupleid);
1224 1225 1226 1227 1228

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

V
Vadim B. Mikheev 已提交
1229
	/*
B
Bruce Momjian 已提交
1230
	 * delete the tuple
1231
	 */
1232
ldelete:;
V
Vadim B. Mikheev 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
	result = heap_delete(resultRelationDesc, tupleid, &ctid);
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1243 1244
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1245 1246
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1247 1248
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1249

V
Vadim B. Mikheev 已提交
1250
				if (!TupIsNull(epqslot))
1251 1252 1253 1254 1255
				{
					*tupleid = ctid;
					goto ldelete;
				}
			}
V
Vadim B. Mikheev 已提交
1256 1257 1258 1259 1260 1261
			return;

		default:
			elog(ERROR, "Unknown status %u from heap_delete", result);
			return;
	}
1262 1263 1264 1265

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

B
Bruce Momjian 已提交
1266
	/*
B
Bruce Momjian 已提交
1267 1268
	 * Note: Normally one would think that we have to delete index tuples
	 * associated with the heap tuple now..
1269
	 *
B
Bruce Momjian 已提交
1270 1271 1272
	 * ... 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
1273 1274 1275
	 */

	/* AFTER ROW DELETE Triggers */
1276
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1277
		ExecARDeleteTriggers(estate, tupleid);
1278 1279 1280 1281

}

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

B
Bruce Momjian 已提交
1304
	/*
B
Bruce Momjian 已提交
1305
	 * abort the operation if not running transactions
1306 1307 1308 1309 1310 1311 1312
	 */
	if (IsBootstrapProcessingMode())
	{
		elog(DEBUG, "ExecReplace: replace can't run without transactions");
		return;
	}

B
Bruce Momjian 已提交
1313
	/*
B
Bruce Momjian 已提交
1314
	 * get the heap tuple out of the tuple table slot
1315 1316 1317
	 */
	tuple = slot->val;

B
Bruce Momjian 已提交
1318
	/*
B
Bruce Momjian 已提交
1319
	 * get the result relation information
1320 1321 1322 1323
	 */
	resultRelationInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelationInfo->ri_RelationDesc;

B
Bruce Momjian 已提交
1324
	/*
B
Bruce Momjian 已提交
1325 1326 1327
	 * 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
1328 1329 1330 1331 1332 1333
	 */

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

V
Vadim B. Mikheev 已提交
1336
		newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1337 1338 1339 1340 1341 1342 1343

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
			Assert(slot->ttc_shouldFree);
1344
			heap_freetuple(tuple);
1345 1346 1347 1348
			slot->val = tuple = newtuple;
		}
	}

B
Bruce Momjian 已提交
1349
	/*
1350 1351 1352 1353
	 * Check the constraints of a tuple
	 */

	if (resultRelationDesc->rd_att->constr)
1354
		ExecConstraints("ExecReplace", resultRelationDesc, tuple, estate);
1355

V
Vadim B. Mikheev 已提交
1356
	/*
B
Bruce Momjian 已提交
1357
	 * replace the heap tuple
1358
	 */
1359
lreplace:;
1360
	result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
V
Vadim B. Mikheev 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369
	switch (result)
	{
		case HeapTupleSelfUpdated:
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1370 1371
			if (XactIsoLevel == XACT_SERIALIZABLE)
				elog(ERROR, "Can't serialize access due to concurrent update");
1372 1373
			else if (!(ItemPointerEquals(tupleid, &ctid)))
			{
B
Bruce Momjian 已提交
1374 1375
				TupleTableSlot *epqslot = EvalPlanQual(estate,
						  resultRelationInfo->ri_RangeTableIndex, &ctid);
1376

V
Vadim B. Mikheev 已提交
1377
				if (!TupIsNull(epqslot))
1378 1379
				{
					*tupleid = ctid;
V
Vadim B. Mikheev 已提交
1380 1381
					tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
					slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1382 1383 1384
					goto lreplace;
				}
			}
V
Vadim B. Mikheev 已提交
1385 1386 1387
			return;

		default:
1388
			elog(ERROR, "Unknown status %u from heap_update", result);
V
Vadim B. Mikheev 已提交
1389
			return;
1390 1391 1392 1393 1394
	}

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

B
Bruce Momjian 已提交
1395
	/*
B
Bruce Momjian 已提交
1396 1397 1398 1399 1400
	 * 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
1401 1402
	 */

B
Bruce Momjian 已提交
1403
	/*
B
Bruce Momjian 已提交
1404
	 * process indices
1405
	 *
1406
	 * heap_update updates a tuple in the base relation by invalidating it
B
Bruce Momjian 已提交
1407 1408 1409 1410
	 * 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.
1411 1412 1413 1414
	 */

	numIndices = resultRelationInfo->ri_NumIndices;
	if (numIndices > 0)
1415
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1416 1417

	/* AFTER ROW UPDATE Triggers */
1418
	if (resultRelationDesc->trigdesc)
V
Vadim B. Mikheev 已提交
1419
		ExecARUpdateTriggers(estate, tupleid, tuple);
1420
}
V
Vadim B. Mikheev 已提交
1421

M
 
Marc G. Fournier 已提交
1422
#ifdef NOT_USED
1423
static HeapTuple
1424
ExecAttrDefault(Relation rel, HeapTuple tuple)
V
Vadim B. Mikheev 已提交
1425
{
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
	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;
1438 1439 1440 1441 1442 1443

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

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

	}

	pfree(econtext);

	if (repl == NULL)
1477
		return tuple;
1478

1479
	newtuple = heap_modifytuple(tuple, rel, replValue, replNull, repl);
1480 1481

	pfree(repl);
1482
	heap_freetuple(tuple);
1483 1484 1485
	pfree(replNull);
	pfree(replValue);

1486
	return newtuple;
1487

V
Vadim B. Mikheev 已提交
1488
}
1489

1490
#endif
V
Vadim B. Mikheev 已提交
1491

1492
static char *
1493
ExecRelCheck(Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1494
{
1495 1496 1497
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
	ExprContext *econtext = makeNode(ExprContext);
1498
	TupleTableSlot *slot = makeNode(TupleTableSlot);
1499 1500 1501 1502
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *rtlist;
	List	   *qual;
	int			i;
1503 1504 1505 1506 1507 1508 1509

	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;
1510
	rte->relname = RelationGetRelationName(rel);
1511 1512
	rte->ref = makeNode(Attr);
	rte->ref->relname = rte->relname;
1513
	rte->relid = RelationGetRelid(rel);
1514
	/* inh, inFromCl, inJoinSet, skipAcl won't be used, leave them zero */
1515 1516 1517 1518 1519 1520 1521
	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 已提交
1522
	econtext->ecxt_param_exec_vals = NULL;		/* exec param values */
1523 1524
	econtext->ecxt_range_table = rtlist;		/* range table */

1525 1526 1527
	if (estate->es_result_relation_constraints == NULL)
	{
		estate->es_result_relation_constraints =
B
Bruce Momjian 已提交
1528
			(List **) palloc(ncheck * sizeof(List *));
1529 1530 1531 1532 1533 1534 1535 1536

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

1537 1538
	for (i = 0; i < ncheck; i++)
	{
1539
		qual = estate->es_result_relation_constraints[i];
1540

1541 1542 1543 1544 1545 1546
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
		 * expression is not to be treated as a failure.  Therefore,
		 * tell ExecQual to return TRUE for NULL.
		 */
		if (! ExecQual(qual, econtext, true))
1547
			return check[i].ccname;
1548 1549 1550 1551 1552 1553 1554
	}

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

1555
	return (char *) NULL;
1556

V
Vadim B. Mikheev 已提交
1557 1558
}

1559
void
1560
ExecConstraints(char *caller, Relation rel, HeapTuple tuple, EState *estate)
V
Vadim B. Mikheev 已提交
1561
{
1562 1563 1564 1565

	Assert(rel->rd_att->constr);

	if (rel->rd_att->constr->has_not_null)
V
Vadim B. Mikheev 已提交
1566
	{
1567
		int			attrChk;
1568 1569 1570 1571

		for (attrChk = 1; attrChk <= rel->rd_att->natts; attrChk++)
		{
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull && heap_attisnull(tuple, attrChk))
1572
				elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1573
				  caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1574 1575 1576 1577 1578
		}
	}

	if (rel->rd_att->constr->num_check > 0)
	{
1579
		char	   *failed;
1580

1581
		if ((failed = ExecRelCheck(rel, tuple, estate)) != NULL)
1582
			elog(ERROR, "%s: rejected due to CHECK constraint %s", caller, failed);
1583 1584
	}

1585
	return;
V
Vadim B. Mikheev 已提交
1586
}
1587

B
Bruce Momjian 已提交
1588
TupleTableSlot *
1589 1590
EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
{
B
Bruce Momjian 已提交
1591 1592 1593 1594 1595 1596 1597
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	evalPlanQual *oldepq;
	EState	   *epqstate = NULL;
	Relation	relation;
	Buffer		buffer;
	HeapTupleData tuple;
	bool		endNode = true;
1598 1599 1600 1601 1602

	Assert(rti != 0);

	if (epq != NULL && epq->rti == 0)
	{
B
Bruce Momjian 已提交
1603 1604
		Assert(!(estate->es_useEvalPlan) &&
			   epq->estate.es_evalPlanQual == NULL);
1605 1606 1607 1608 1609 1610
		epq->rti = rti;
		endNode = false;
	}

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

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

	epqstate = &(epq->estate);

	/*
B
Bruce Momjian 已提交
1690 1691
	 * Ok - we're requested for the same RTE (-:)). I'm not sure about
	 * ability to use ExecReScan instead of ExecInitNode, so...
1692 1693
	 */
	if (endNode)
1694
	{
1695
		ExecEndNode(epq->plan, epq->plan);
1696 1697
	    epqstate->es_tupleTable->next = 0;
	}
1698 1699 1700 1701

	/* free old RTE' tuple */
	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
1702
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1703 1704 1705 1706
		epqstate->es_evTuple[epq->rti - 1] = NULL;
	}

	/* ** fetch tid tuple ** */
B
Bruce Momjian 已提交
1707
	if (estate->es_result_relation_info != NULL &&
1708 1709 1710 1711
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
B
Bruce Momjian 已提交
1712
		List	   *l;
1713

B
Bruce Momjian 已提交
1714
		foreach(l, estate->es_rowMark)
1715
		{
B
Bruce Momjian 已提交
1716
			if (((execRowMark *) lfirst(l))->rti == rti)
1717 1718
				break;
		}
B
Bruce Momjian 已提交
1719
		relation = ((execRowMark *) lfirst(l))->relation;
1720 1721
	}
	tuple.t_self = *tid;
B
Bruce Momjian 已提交
1722
	for (;;)
1723 1724 1725 1726 1727 1728 1729
	{
		heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
		if (tuple.t_data != NULL)
		{
			TransactionId xwait = SnapshotDirty->xmax;

			if (TransactionIdIsValid(SnapshotDirty->xmin))
1730 1731 1732 1733 1734
			{
				elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
				Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
				elog(ERROR, "Aborting this transaction");
			}
B
Bruce Momjian 已提交
1735

1736
			/*
B
Bruce Momjian 已提交
1737 1738
			 * If tuple is being updated by other transaction then we have
			 * to wait for its commit/abort.
1739 1740 1741 1742 1743 1744 1745
			 */
			if (TransactionIdIsValid(xwait))
			{
				ReleaseBuffer(buffer);
				XactLockTableWait(xwait);
				continue;
			}
B
Bruce Momjian 已提交
1746

1747 1748 1749
			/*
			 * Nice! We got tuple - now copy it.
			 */
1750
			if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1751
				heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1752 1753 1754 1755
			epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}
B
Bruce Momjian 已提交
1756

1757 1758
		/*
		 * Ops! Invalid tuple. Have to check is it updated or deleted.
B
Bruce Momjian 已提交
1759 1760
		 * Note that it's possible to get invalid SnapshotDirty->tid if
		 * tuple updated by this transaction. Have we to check this ?
1761
		 */
B
Bruce Momjian 已提交
1762
		if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1763 1764 1765 1766 1767
			!(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
		{
			tuple.t_self = SnapshotDirty->tid;	/* updated ... */
			continue;
		}
B
Bruce Momjian 已提交
1768

1769
		/*
B
Bruce Momjian 已提交
1770 1771
		 * Deleted or updated by this transaction. Do not (re-)start
		 * execution of this PQ. Continue previous PQ.
1772
		 */
B
Bruce Momjian 已提交
1773
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
		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
1784 1785 1786 1787
		{									
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and      */
			return (NULL);					/* continue Query execution   */
1788 1789 1790 1791
		}
	}

	if (estate->es_origPlan->nParamExec > 0)
B
Bruce Momjian 已提交
1792 1793 1794 1795
		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));
1796
    Assert(epqstate->es_tupleTable->next == 0);
1797 1798 1799
	ExecInitNode(epq->plan, epqstate, NULL);

	/*
B
Bruce Momjian 已提交
1800 1801
	 * For UPDATE/DELETE we have to return tid of actual row we're
	 * executing PQ for.
1802 1803 1804 1805 1806 1807
	 */
	*tid = tuple.t_self;

	return (EvalPlanQualNext(estate));
}

B
Bruce Momjian 已提交
1808
static TupleTableSlot *
1809 1810
EvalPlanQualNext(EState *estate)
{
B
Bruce Momjian 已提交
1811 1812 1813 1814
	evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
	EState	   *epqstate = &(epq->estate);
	evalPlanQual *oldepq;
	TupleTableSlot *slot;
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

	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);
1827
	    epqstate->es_tupleTable->next = 0;
1828
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1829 1830
		epqstate->es_evTuple[epq->rti - 1] = NULL;
		/* pop old PQ from the stack */
B
Bruce Momjian 已提交
1831 1832
		oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
		if (oldepq == (evalPlanQual *) NULL)
1833 1834 1835 1836
		{
			epq->rti = 0;					/* this is the first (oldest) */
			estate->es_useEvalPlan = false;	/* PQ - mark as free and	  */
			return (NULL);					/* continue Query execution   */
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
		}
		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);
}