execMain.c 79.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
 *	The old ExecutorMain() has been replaced by ExecutorStart(),
 *	ExecutorRun() and ExecutorEnd()
 *
 *	These three procedures are the external interfaces to the executor.
15
 *	In each case, the query descriptor is required as an argument.
16
 *
17
 *	ExecutorStart() must be called at the beginning of execution of any
18 19 20
 *	query plan and ExecutorEnd() should always be called at the end of
 *	execution of a plan.
 *
21
 *	ExecutorRun accepts direction and count arguments that specify whether
22
 *	the plan is to be executed forwards, backwards, and for how many tuples.
23
 *
24
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
25
 * Portions Copyright (c) 1994, Regents of the University of California
26 27 28
 *
 *
 * IDENTIFICATION
29
 *	  $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.303.2.3 2009/12/09 21:58:16 tgl Exp $
30 31 32
 *
 *-------------------------------------------------------------------------
 */
33 34
#include "postgres.h"

35
#include "access/heapam.h"
36
#include "access/reloptions.h"
37 38
#include "access/transam.h"
#include "access/xact.h"
39
#include "catalog/heap.h"
40
#include "catalog/namespace.h"
41
#include "catalog/toasting.h"
42
#include "commands/tablespace.h"
43
#include "commands/trigger.h"
B
Bruce Momjian 已提交
44
#include "executor/execdebug.h"
45
#include "executor/instrument.h"
46
#include "executor/nodeSubplan.h"
B
Bruce Momjian 已提交
47
#include "miscadmin.h"
48
#include "optimizer/clauses.h"
49
#include "parser/parse_clause.h"
50
#include "parser/parse_expr.h"
51
#include "parser/parsetree.h"
52
#include "storage/smgr.h"
B
Bruce Momjian 已提交
53
#include "utils/acl.h"
54
#include "utils/builtins.h"
55
#include "utils/lsyscache.h"
56
#include "utils/memutils.h"
57

58

59 60 61 62 63 64 65 66 67
typedef struct evalPlanQual
{
	Index		rti;
	EState	   *estate;
	PlanState  *planstate;
	struct evalPlanQual *next;	/* stack of active PlanQual plans */
	struct evalPlanQual *free;	/* list of free PlanQual plans */
} evalPlanQual;

68
/* decls for local routines only used within this module */
69
static void InitPlan(QueryDesc *queryDesc, int eflags);
70
static void initResultRelInfo(ResultRelInfo *resultRelInfo,
71
				  Relation resultRelationDesc,
B
Bruce Momjian 已提交
72
				  Index resultRelationIndex,
73 74
				  CmdType operation,
				  bool doInstrument);
75
static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
76
static void ExecEndPlan(PlanState *planstate, EState *estate);
77
static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
B
Bruce Momjian 已提交
78 79 80
			CmdType operation,
			long numberTuples,
			ScanDirection direction,
81
			DestReceiver *dest);
82
static void ExecSelect(TupleTableSlot *slot,
B
Bruce Momjian 已提交
83
		   DestReceiver *dest, EState *estate);
84
static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
85 86
		   TupleTableSlot *planSlot,
		   DestReceiver *dest, EState *estate);
87
static void ExecDelete(ItemPointer tupleid,
B
Bruce Momjian 已提交
88 89
		   TupleTableSlot *planSlot,
		   DestReceiver *dest, EState *estate);
90
static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
B
Bruce Momjian 已提交
91 92 93
		   TupleTableSlot *planSlot,
		   DestReceiver *dest, EState *estate);
static void ExecProcessReturning(ProjectionInfo *projectReturning,
94 95 96
					 TupleTableSlot *tupleSlot,
					 TupleTableSlot *planSlot,
					 DestReceiver *dest);
97
static TupleTableSlot *EvalPlanQualNext(EState *estate);
98
static void EndEvalPlanQual(EState *estate);
99
static void ExecCheckRTPerms(List *rangeTable);
100
static void ExecCheckRTEPerms(RangeTblEntry *rte);
101
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
102
static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
B
Bruce Momjian 已提交
103
				  evalPlanQual *priorepq);
104
static void EvalPlanQualStop(evalPlanQual *epq);
105 106 107 108 109 110
static void OpenIntoRel(QueryDesc *queryDesc);
static void CloseIntoRel(QueryDesc *queryDesc);
static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
static void intorel_shutdown(DestReceiver *self);
static void intorel_destroy(DestReceiver *self);
111

112 113
/* end of local decls */

114

115
/* ----------------------------------------------------------------
116 117 118 119 120
 *		ExecutorStart
 *
 *		This routine must be called at the beginning of any execution of any
 *		query plan
 *
121
 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
B
Bruce Momjian 已提交
122
 * clear why we bother to separate the two functions, but...).	The tupDesc
123 124
 * field of the QueryDesc is filled in to describe the tuples that will be
 * returned, and the internal fields (estate and planstate) are set up.
125
 *
126
 * eflags contains flag bits as described in executor.h.
127
 *
128 129
 * NB: the CurrentMemoryContext when this is called will become the parent
 * of the per-query context used for this Executor invocation.
130 131
 * ----------------------------------------------------------------
 */
132
void
133
ExecutorStart(QueryDesc *queryDesc, int eflags)
134
{
135
	EState	   *estate;
136
	MemoryContext oldcontext;
137

138
	/* sanity checks: queryDesc must not be started already */
139
	Assert(queryDesc != NULL);
140 141
	Assert(queryDesc->estate == NULL);

142
	/*
B
Bruce Momjian 已提交
143
	 * If the transaction is read-only, we need to check if any writes are
144
	 * planned to non-temporary tables.  EXPLAIN is considered read-only.
145
	 */
146
	if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
147
		ExecCheckXactReadOnly(queryDesc->plannedstmt);
148

149
	/*
150
	 * Build EState, switch into per-query memory context for startup.
151 152 153 154
	 */
	estate = CreateExecutorState();
	queryDesc->estate = estate;

155 156 157 158 159
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	/*
	 * Fill in parameters, if any, from queryDesc
	 */
160
	estate->es_param_list_info = queryDesc->params;
161

162
	if (queryDesc->plannedstmt->nParamExec > 0)
163
		estate->es_param_exec_vals = (ParamExecData *)
164
			palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	/*
	 * If non-read-only query, set the command ID to mark output tuples with
	 */
	switch (queryDesc->operation)
	{
		case CMD_SELECT:
			/* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
			if (queryDesc->plannedstmt->intoClause != NULL ||
				queryDesc->plannedstmt->rowMarks != NIL)
				estate->es_output_cid = GetCurrentCommandId(true);
			break;

		case CMD_INSERT:
		case CMD_DELETE:
		case CMD_UPDATE:
			estate->es_output_cid = GetCurrentCommandId(true);
			break;

		default:
			elog(ERROR, "unrecognized operation code: %d",
				 (int) queryDesc->operation);
			break;
	}

190
	/*
191
	 * Copy other important information into the EState
192
	 */
193 194 195
	estate->es_snapshot = queryDesc->snapshot;
	estate->es_crosscheck_snapshot = queryDesc->crosscheck_snapshot;
	estate->es_instrument = queryDesc->doInstrument;
196

197
	/*
198
	 * Initialize the plan state tree
199
	 */
200
	InitPlan(queryDesc, eflags);
201 202

	MemoryContextSwitchTo(oldcontext);
203 204 205
}

/* ----------------------------------------------------------------
206 207 208 209 210 211 212
 *		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.
213
 *
214 215 216
 *		If direction is NoMovementScanDirection then nothing is done
 *		except to start up/shut down the destination.  Otherwise,
 *		we retrieve up to 'count' tuples in the specified direction.
217
 *
218
 *		Note: count = 0 is interpreted as no portal limit, i.e., run to
219
 *		completion.
220
 *
221 222
 * ----------------------------------------------------------------
 */
223
TupleTableSlot *
224
ExecutorRun(QueryDesc *queryDesc,
225
			ScanDirection direction, long count)
226
{
227
	EState	   *estate;
228
	CmdType		operation;
229
	DestReceiver *dest;
230
	bool		sendTuples;
231
	TupleTableSlot *result;
232 233 234 235 236 237 238 239
	MemoryContext oldcontext;

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

	estate = queryDesc->estate;

	Assert(estate != NULL);
240

B
Bruce Momjian 已提交
241
	/*
242
	 * Switch into per-query memory context
243
	 */
244
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
245

B
Bruce Momjian 已提交
246
	/*
B
Bruce Momjian 已提交
247
	 * extract information from the query descriptor and the query feature.
248
	 */
249 250 251
	operation = queryDesc->operation;
	dest = queryDesc->dest;

B
Bruce Momjian 已提交
252
	/*
253
	 * startup tuple receiver, if we will be emitting tuples
254
	 */
255 256
	estate->es_processed = 0;
	estate->es_lastoid = InvalidOid;
257

258
	sendTuples = (operation == CMD_SELECT ||
259
				  queryDesc->plannedstmt->returningLists);
260 261 262

	if (sendTuples)
		(*dest->rStartup) (dest, operation, queryDesc->tupDesc);
263

264 265 266
	/*
	 * run plan
	 */
267
	if (ScanDirectionIsNoMovement(direction))
268 269 270
		result = NULL;
	else
		result = ExecutePlan(estate,
271
							 queryDesc->planstate,
272 273 274
							 operation,
							 count,
							 direction,
275
							 dest);
276

277
	/*
278
	 * shutdown tuple receiver, if we started it
279
	 */
280 281
	if (sendTuples)
		(*dest->rShutdown) (dest);
282

283 284
	MemoryContextSwitchTo(oldcontext);

285
	return result;
286 287 288
}

/* ----------------------------------------------------------------
289 290
 *		ExecutorEnd
 *
291
 *		This routine must be called at the end of execution of any
292
 *		query plan
293 294 295
 * ----------------------------------------------------------------
 */
void
296
ExecutorEnd(QueryDesc *queryDesc)
297
{
298
	EState	   *estate;
299
	MemoryContext oldcontext;
300

301 302
	/* sanity checks */
	Assert(queryDesc != NULL);
303

304 305
	estate = queryDesc->estate;

306
	Assert(estate != NULL);
307

308
	/*
309
	 * Switch into per-query memory context to run ExecEndPlan
310
	 */
311 312 313
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	ExecEndPlan(queryDesc->planstate, estate);
314

315 316 317 318 319 320
	/*
	 * Close the SELECT INTO relation if any
	 */
	if (estate->es_select_into)
		CloseIntoRel(queryDesc);

321
	/*
322
	 * Must switch out of context before destroying it
323
	 */
324
	MemoryContextSwitchTo(oldcontext);
325

326
	/*
327 328
	 * Release EState and per-query memory context.  This should release
	 * everything the executor has allocated.
329
	 */
330 331 332 333 334 335
	FreeExecutorState(estate);

	/* Reset queryDesc fields that no longer point to anything */
	queryDesc->tupDesc = NULL;
	queryDesc->estate = NULL;
	queryDesc->planstate = NULL;
336
}
337

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
/* ----------------------------------------------------------------
 *		ExecutorRewind
 *
 *		This routine may be called on an open queryDesc to rewind it
 *		to the start.
 * ----------------------------------------------------------------
 */
void
ExecutorRewind(QueryDesc *queryDesc)
{
	EState	   *estate;
	MemoryContext oldcontext;

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

	estate = queryDesc->estate;

	Assert(estate != NULL);

	/* It's probably not sensible to rescan updating queries */
	Assert(queryDesc->operation == CMD_SELECT);

	/*
	 * Switch into per-query memory context
	 */
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	/*
	 * rescan plan
	 */
	ExecReScan(queryDesc->planstate, NULL);

	MemoryContextSwitchTo(oldcontext);
}

374

375 376 377 378
/*
 * ExecCheckRTPerms
 *		Check access permissions for all relations listed in a range table.
 */
379
static void
380
ExecCheckRTPerms(List *rangeTable)
381
{
382
	ListCell   *l;
383

384
	foreach(l, rangeTable)
385
	{
386
		ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
387 388 389 390 391 392 393 394
	}
}

/*
 * ExecCheckRTEPerms
 *		Check access permissions for a single RTE.
 */
static void
395
ExecCheckRTEPerms(RangeTblEntry *rte)
396
{
397
	AclMode		requiredPerms;
398
	Oid			relOid;
B
Bruce Momjian 已提交
399
	Oid			userid;
400

B
Bruce Momjian 已提交
401
	/*
402
	 * Only plain-relation RTEs need to be checked here.  Function RTEs are
B
Bruce Momjian 已提交
403
	 * checked by init_fcache when the function is prepared for execution.
404
	 * Join, subquery, and special RTEs need no checks.
B
Bruce Momjian 已提交
405
	 */
406
	if (rte->rtekind != RTE_RELATION)
407 408
		return;

409 410 411 412 413 414 415
	/*
	 * No work if requiredPerms is empty.
	 */
	requiredPerms = rte->requiredPerms;
	if (requiredPerms == 0)
		return;

416
	relOid = rte->relid;
417 418

	/*
B
Bruce Momjian 已提交
419
	 * userid to check as: current user unless we have a setuid indication.
420
	 *
421 422 423 424
	 * Note: GetUserId() is presently fast enough that there's no harm in
	 * calling it separately for each RTE.	If that stops being true, we could
	 * call it once in ExecCheckRTPerms and pass the userid down from there.
	 * But for now, no need for the extra clutter.
425
	 */
426
	userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
427

428
	/*
B
Bruce Momjian 已提交
429
	 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
430
	 */
431 432 433 434
	if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
		!= requiredPerms)
		aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
					   get_rel_name(relOid));
435 436
}

437 438 439
/*
 * Check that the query does not imply any writes to non-temp tables.
 */
440
static void
441
ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
442
{
443 444
	ListCell   *l;

445 446 447 448 449
	/*
	 * CREATE TABLE AS or SELECT INTO?
	 *
	 * XXX should we allow this if the destination is temp?
	 */
450
	if (plannedstmt->intoClause != NULL)
451 452
		goto fail;

453
	/* Fail if write permissions are requested on any non-temp table */
454
	foreach(l, plannedstmt->rtable)
455
	{
456
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
457

458 459
		if (rte->rtekind != RTE_RELATION)
			continue;
460

461 462
		if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
			continue;
463

464 465
		if (isTempNamespace(get_rel_namespace(rte->relid)))
			continue;
466

467
		goto fail;
468 469 470 471 472
	}

	return;

fail:
473 474 475
	ereport(ERROR,
			(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
			 errmsg("transaction is read-only")));
476 477 478
}


479
/* ----------------------------------------------------------------
480 481 482 483
 *		InitPlan
 *
 *		Initializes the query plan: open files, allocate storage
 *		and start up the rule manager
484 485
 * ----------------------------------------------------------------
 */
486
static void
487
InitPlan(QueryDesc *queryDesc, int eflags)
488
{
489
	CmdType		operation = queryDesc->operation;
490 491 492
	PlannedStmt *plannedstmt = queryDesc->plannedstmt;
	Plan	   *plan = plannedstmt->planTree;
	List	   *rangeTable = plannedstmt->rtable;
B
Bruce Momjian 已提交
493
	EState	   *estate = queryDesc->estate;
494
	PlanState  *planstate;
B
Bruce Momjian 已提交
495
	TupleDesc	tupType;
496
	ListCell   *l;
497
	int			i;
498

499
	/*
500
	 * Do permissions checks
501
	 */
502
	ExecCheckRTPerms(rangeTable);
503

B
Bruce Momjian 已提交
504
	/*
B
Bruce Momjian 已提交
505
	 * initialize the node's execution state
506
	 */
507 508
	estate->es_range_table = rangeTable;

B
Bruce Momjian 已提交
509
	/*
510
	 * initialize result relation stuff
511
	 */
512
	if (plannedstmt->resultRelations)
513
	{
514 515
		List	   *resultRelations = plannedstmt->resultRelations;
		int			numResultRelations = list_length(resultRelations);
516
		ResultRelInfo *resultRelInfos;
517
		ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
518

519 520 521 522
		resultRelInfos = (ResultRelInfo *)
			palloc(numResultRelations * sizeof(ResultRelInfo));
		resultRelInfo = resultRelInfos;
		foreach(l, resultRelations)
523
		{
524 525 526 527 528 529
			Index		resultRelationIndex = lfirst_int(l);
			Oid			resultRelationOid;
			Relation	resultRelation;

			resultRelationOid = getrelid(resultRelationIndex, rangeTable);
			resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
530
			initResultRelInfo(resultRelInfo,
531 532
							  resultRelation,
							  resultRelationIndex,
533 534
							  operation,
							  estate->es_instrument);
535
			resultRelInfo++;
536 537 538 539 540
		}
		estate->es_result_relations = resultRelInfos;
		estate->es_num_result_relations = numResultRelations;
		/* Initialize to first or only result rel */
		estate->es_result_relation_info = resultRelInfos;
541
	}
542 543
	else
	{
B
Bruce Momjian 已提交
544
		/*
B
Bruce Momjian 已提交
545
		 * if no result relation, then set state appropriately
546
		 */
547 548
		estate->es_result_relations = NULL;
		estate->es_num_result_relations = 0;
549 550 551
		estate->es_result_relation_info = NULL;
	}

552
	/*
T
Tom Lane 已提交
553
	 * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
B
Bruce Momjian 已提交
554
	 * flag appropriately so that the plan tree will be initialized with the
555
	 * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
556
	 */
557
	estate->es_select_into = false;
558
	if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
559
	{
560
		estate->es_select_into = true;
561
		estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
562 563
	}

564
	/*
565
	 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
B
Bruce Momjian 已提交
566 567
	 * initialize the plan tree, else we'd be doing a lock upgrade. While we
	 * are at it, build the ExecRowMark list.
568
	 */
569
	estate->es_rowMarks = NIL;
570
	foreach(l, plannedstmt->rowMarks)
571
	{
572 573 574 575 576 577 578 579 580 581 582
		RowMarkClause *rc = (RowMarkClause *) lfirst(l);
		Oid			relid = getrelid(rc->rti, rangeTable);
		Relation	relation;
		ExecRowMark *erm;

		relation = heap_open(relid, RowShareLock);
		erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
		erm->relation = relation;
		erm->rti = rc->rti;
		erm->forUpdate = rc->forUpdate;
		erm->noWait = rc->noWait;
583 584
		/* We'll set up ctidAttno below */
		erm->ctidAttNo = InvalidAttrNumber;
585
		estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
586
	}
587

B
Bruce Momjian 已提交
588
	/*
589
	 * Initialize the executor "tuple" table.  We need slots for all the plan
B
Bruce Momjian 已提交
590 591
	 * nodes, plus possibly output slots for the junkfilter(s). At this point
	 * we aren't sure if we need junkfilters, so just add slots for them
592
	 * unconditionally.  Also, if it's not a SELECT, set up a slot for use for
593
	 * trigger output tuples.  Also, one for RETURNING-list evaluation.
594 595
	 */
	{
596 597 598 599 600 601 602
		int			nSlots;

		/* Slots for the main plan tree */
		nSlots = ExecCountSlotsNode(plan);
		/* Add slots for subplans and initplans */
		foreach(l, plannedstmt->subplans)
		{
B
Bruce Momjian 已提交
603
			Plan	   *subplan = (Plan *) lfirst(l);
604

605 606 607
			nSlots += ExecCountSlotsNode(subplan);
		}
		/* Add slots for junkfilter(s) */
608 609
		if (plannedstmt->resultRelations != NIL)
			nSlots += list_length(plannedstmt->resultRelations);
610 611
		else
			nSlots += 1;
612
		if (operation != CMD_SELECT)
613
			nSlots++;			/* for es_trig_tuple_slot */
614
		if (plannedstmt->returningLists)
615
			nSlots++;			/* for RETURNING projection */
616

617
		estate->es_tupleTable = ExecCreateTupleTable(nSlots);
618 619 620 621

		if (operation != CMD_SELECT)
			estate->es_trig_tuple_slot =
				ExecAllocTableSlot(estate->es_tupleTable);
622
	}
623

624
	/* mark EvalPlanQual not active */
625
	estate->es_plannedstmt = plannedstmt;
626 627
	estate->es_evalPlanQual = NULL;
	estate->es_evTupleNull = NULL;
628
	estate->es_evTuple = NULL;
629 630
	estate->es_useEvalPlan = false;

B
Bruce Momjian 已提交
631
	/*
B
Bruce Momjian 已提交
632 633
	 * Initialize private state information for each SubPlan.  We must do this
	 * before running ExecInitNode on the main query tree, since
634 635 636 637 638 639
	 * ExecInitSubPlan expects to be able to find these entries.
	 */
	Assert(estate->es_subplanstates == NIL);
	i = 1;						/* subplan indices count from 1 */
	foreach(l, plannedstmt->subplans)
	{
B
Bruce Momjian 已提交
640 641 642
		Plan	   *subplan = (Plan *) lfirst(l);
		PlanState  *subplanstate;
		int			sp_eflags;
643 644

		/*
B
Bruce Momjian 已提交
645 646 647
		 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
		 * it is a parameterless subplan (not initplan), we suggest that it be
		 * prepared to handle REWIND efficiently; otherwise there is no need.
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
		 */
		sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
		if (bms_is_member(i, plannedstmt->rewindPlanIDs))
			sp_eflags |= EXEC_FLAG_REWIND;

		subplanstate = ExecInitNode(subplan, estate, sp_eflags);

		estate->es_subplanstates = lappend(estate->es_subplanstates,
										   subplanstate);

		i++;
	}

	/*
	 * Initialize the private state information for all the nodes in the query
B
Bruce Momjian 已提交
663 664
	 * tree.  This opens files, allocates storage and leaves us ready to start
	 * processing tuples.
665
	 */
666
	planstate = ExecInitNode(plan, estate, eflags);
667

B
Bruce Momjian 已提交
668
	/*
B
Bruce Momjian 已提交
669 670 671
	 * Get the tuple descriptor describing the type of tuples to return. (this
	 * is especially important if we are creating a relation with "SELECT
	 * INTO")
672
	 */
673
	tupType = ExecGetResultType(planstate);
674

B
Bruce Momjian 已提交
675
	/*
B
Bruce Momjian 已提交
676 677 678 679 680 681
	 * Initialize the junk filter if needed.  SELECT and INSERT queries need a
	 * filter if there are any junk attrs in the tlist.  INSERT and SELECT
	 * INTO also need a filter if the plan may return raw disk tuples (else
	 * heap_insert will be scribbling on the source relation!). UPDATE and
	 * DELETE always need a filter, since there's always a junk 'ctid'
	 * attribute present --- no need to look first.
682 683 684
	 *
	 * This section of code is also a convenient place to verify that the
	 * output of an INSERT or UPDATE matches the target table(s).
685 686
	 */
	{
687
		bool		junk_filter_needed = false;
688
		ListCell   *tlist;
689

690
		switch (operation)
691
		{
692 693
			case CMD_SELECT:
			case CMD_INSERT:
694
				foreach(tlist, plan->targetlist)
695
				{
696 697
					TargetEntry *tle = (TargetEntry *) lfirst(tlist);

698
					if (tle->resjunk)
699 700 701 702
					{
						junk_filter_needed = true;
						break;
					}
703
				}
704
				if (!junk_filter_needed &&
705
					(operation == CMD_INSERT || estate->es_select_into) &&
706 707
					ExecMayReturnRawTuples(planstate))
					junk_filter_needed = true;
708 709 710 711 712 713 714
				break;
			case CMD_UPDATE:
			case CMD_DELETE:
				junk_filter_needed = true;
				break;
			default:
				break;
715 716
		}

717
		if (junk_filter_needed)
718
		{
719
			/*
B
Bruce Momjian 已提交
720 721 722
			 * If there are multiple result relations, each one needs its own
			 * junk filter.  Note this is only possible for UPDATE/DELETE, so
			 * we can't be fooled by some needing a filter and some not.
723
			 */
724
			if (list_length(plannedstmt->resultRelations) > 1)
725
			{
726 727
				PlanState **appendplans;
				int			as_nplans;
728 729 730 731 732
				ResultRelInfo *resultRelInfo;

				/* Top plan had better be an Append here. */
				Assert(IsA(plan, Append));
				Assert(((Append *) plan)->isTarget);
733 734 735 736
				Assert(IsA(planstate, AppendState));
				appendplans = ((AppendState *) planstate)->appendplans;
				as_nplans = ((AppendState *) planstate)->as_nplans;
				Assert(as_nplans == estate->es_num_result_relations);
737
				resultRelInfo = estate->es_result_relations;
738
				for (i = 0; i < as_nplans; i++)
739
				{
740
					PlanState  *subplan = appendplans[i];
741 742
					JunkFilter *j;

743 744 745 746
					if (operation == CMD_UPDATE)
						ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
											subplan->plan->targetlist);

747
					j = ExecInitJunkFilter(subplan->plan->targetlist,
B
Bruce Momjian 已提交
748 749
							resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
								  ExecAllocTableSlot(estate->es_tupleTable));
B
Bruce Momjian 已提交
750

751
					/*
B
Bruce Momjian 已提交
752 753 754 755
					 * Since it must be UPDATE/DELETE, there had better be a
					 * "ctid" junk attribute in the tlist ... but ctid could
					 * be at a different resno for each result relation. We
					 * look up the ctid resnos now and save them in the
756 757 758 759 760
					 * junkfilters.
					 */
					j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
					if (!AttributeNumberIsValid(j->jf_junkAttNo))
						elog(ERROR, "could not find junk ctid column");
761 762 763
					resultRelInfo->ri_junkFilter = j;
					resultRelInfo++;
				}
B
Bruce Momjian 已提交
764

765
				/*
B
Bruce Momjian 已提交
766 767
				 * Set active junkfilter too; at this point ExecInitAppend has
				 * already selected an active result relation...
768 769 770
				 */
				estate->es_junkFilter =
					estate->es_result_relation_info->ri_junkFilter;
771 772 773 774 775 776 777 778 779 780

				/*
				 * We currently can't support rowmarks in this case, because
				 * the associated junk CTIDs might have different resnos in
				 * different subplans.
				 */
				if (estate->es_rowMarks)
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
781 782 783 784
			}
			else
			{
				/* Normal case with just one JunkFilter */
785
				JunkFilter *j;
786

787 788 789 790
				if (operation == CMD_INSERT || operation == CMD_UPDATE)
					ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
										planstate->plan->targetlist);

791
				j = ExecInitJunkFilter(planstate->plan->targetlist,
792
									   tupType->tdhasoid,
B
Bruce Momjian 已提交
793
								  ExecAllocTableSlot(estate->es_tupleTable));
794 795 796
				estate->es_junkFilter = j;
				if (estate->es_result_relation_info)
					estate->es_result_relation_info->ri_junkFilter = j;
797

798
				if (operation == CMD_SELECT)
799 800
				{
					/* For SELECT, want to return the cleaned tuple type */
801
					tupType = j->jf_cleanTupType;
802 803 804 805 806 807 808 809
				}
				else if (operation == CMD_UPDATE || operation == CMD_DELETE)
				{
					/* For UPDATE/DELETE, find the ctid junk attr now */
					j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
					if (!AttributeNumberIsValid(j->jf_junkAttNo))
						elog(ERROR, "could not find junk ctid column");
				}
810 811 812 813 814 815 816 817 818 819 820 821 822

				/* For SELECT FOR UPDATE/SHARE, find the ctid attrs now */
				foreach(l, estate->es_rowMarks)
				{
					ExecRowMark *erm = (ExecRowMark *) lfirst(l);
					char		resname[32];

					snprintf(resname, sizeof(resname), "ctid%u", erm->rti);
					erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
					if (!AttributeNumberIsValid(erm->ctidAttNo))
						elog(ERROR, "could not find junk \"%s\" column",
							 resname);
				}
823
			}
824 825
		}
		else
826
		{
827 828 829 830
			if (operation == CMD_INSERT)
				ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
									planstate->plan->targetlist);

831
			estate->es_junkFilter = NULL;
832 833 834
			if (estate->es_rowMarks)
				elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
		}
835
	}
836

B
Bruce Momjian 已提交
837
	/*
838
	 * Initialize RETURNING projections if needed.
839
	 */
840
	if (plannedstmt->returningLists)
841
	{
842 843 844
		TupleTableSlot *slot;
		ExprContext *econtext;
		ResultRelInfo *resultRelInfo;
845

846
		/*
847 848
		 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
		 * We assume all the sublists will generate the same output tupdesc.
849
		 */
850
		tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
851
								 false);
852

853 854 855 856 857
		/* Set up a slot for the output of the RETURNING projection(s) */
		slot = ExecAllocTableSlot(estate->es_tupleTable);
		ExecSetSlotDescriptor(slot, tupType);
		/* Need an econtext too */
		econtext = CreateExprContext(estate);
858

859
		/*
B
Bruce Momjian 已提交
860 861
		 * Build a projection for each result rel.	Note that any SubPlans in
		 * the RETURNING lists get attached to the topmost plan node.
862
		 */
863
		Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
864
		resultRelInfo = estate->es_result_relations;
865
		foreach(l, plannedstmt->returningLists)
866
		{
B
Bruce Momjian 已提交
867 868
			List	   *rlist = (List *) lfirst(l);
			List	   *rliststate;
869

870 871
			rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
			resultRelInfo->ri_projectReturning =
872
				ExecBuildProjectionInfo(rliststate, econtext, slot,
B
Bruce Momjian 已提交
873
									 resultRelInfo->ri_RelationDesc->rd_att);
874
			resultRelInfo++;
875
		}
876 877
	}

878 879
	queryDesc->tupDesc = tupType;
	queryDesc->planstate = planstate;
880 881 882 883 884 885 886 887 888 889

	/*
	 * If doing SELECT INTO, initialize the "into" relation.  We must wait
	 * till now so we have the "clean" result tuple type to create the new
	 * table from.
	 *
	 * If EXPLAIN, skip creating the "into" relation.
	 */
	if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
		OpenIntoRel(queryDesc);
890 891
}

892 893 894 895 896
/*
 * Initialize ResultRelInfo data for one result relation
 */
static void
initResultRelInfo(ResultRelInfo *resultRelInfo,
897
				  Relation resultRelationDesc,
898
				  Index resultRelationIndex,
899 900
				  CmdType operation,
				  bool doInstrument)
901
{
902
	/*
B
Bruce Momjian 已提交
903 904
	 * Check valid relkind ... parser and/or planner should have noticed this
	 * already, but let's make sure.
905
	 */
906 907
	switch (resultRelationDesc->rd_rel->relkind)
	{
908 909 910
		case RELKIND_RELATION:
			/* OK */
			break;
911
		case RELKIND_SEQUENCE:
912 913
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
914
					 errmsg("cannot change sequence \"%s\"",
B
Bruce Momjian 已提交
915
							RelationGetRelationName(resultRelationDesc))));
916 917
			break;
		case RELKIND_TOASTVALUE:
918 919
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
920
					 errmsg("cannot change TOAST relation \"%s\"",
B
Bruce Momjian 已提交
921
							RelationGetRelationName(resultRelationDesc))));
922 923
			break;
		case RELKIND_VIEW:
924 925
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
926
					 errmsg("cannot change view \"%s\"",
B
Bruce Momjian 已提交
927
							RelationGetRelationName(resultRelationDesc))));
928
			break;
929 930 931 932 933 934
		default:
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("cannot change relation \"%s\"",
							RelationGetRelationName(resultRelationDesc))));
			break;
935 936
	}

937
	/* OK, fill in the node */
938 939 940 941 942 943 944
	MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
	resultRelInfo->type = T_ResultRelInfo;
	resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
	resultRelInfo->ri_RelationDesc = resultRelationDesc;
	resultRelInfo->ri_NumIndices = 0;
	resultRelInfo->ri_IndexRelationDescs = NULL;
	resultRelInfo->ri_IndexRelationInfo = NULL;
945 946
	/* make a copy so as not to depend on relcache info not changing... */
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
947 948
	if (resultRelInfo->ri_TrigDesc)
	{
B
Bruce Momjian 已提交
949
		int			n = resultRelInfo->ri_TrigDesc->numtriggers;
950 951 952 953 954 955 956 957 958 959 960 961 962

		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
			palloc0(n * sizeof(FmgrInfo));
		if (doInstrument)
			resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
		else
			resultRelInfo->ri_TrigInstrument = NULL;
	}
	else
	{
		resultRelInfo->ri_TrigFunctions = NULL;
		resultRelInfo->ri_TrigInstrument = NULL;
	}
963 964
	resultRelInfo->ri_ConstraintExprs = NULL;
	resultRelInfo->ri_junkFilter = NULL;
965
	resultRelInfo->ri_projectReturning = NULL;
966 967 968

	/*
	 * If there are indices on the result relation, open them and save
B
Bruce Momjian 已提交
969 970 971
	 * 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.
972 973 974 975 976 977
	 */
	if (resultRelationDesc->rd_rel->relhasindex &&
		operation != CMD_DELETE)
		ExecOpenIndices(resultRelInfo);
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
/*
 * Verify that the tuples to be produced by INSERT or UPDATE match the
 * target relation's rowtype
 *
 * We do this to guard against stale plans.  If plan invalidation is
 * functioning properly then we should never get a failure here, but better
 * safe than sorry.  Note that this is called after we have obtained lock
 * on the target rel, so the rowtype can't change underneath us.
 *
 * The plan output is represented by its targetlist, because that makes
 * handling the dropped-column case easier.
 */
static void
ExecCheckPlanOutput(Relation resultRel, List *targetList)
{
	TupleDesc	resultDesc = RelationGetDescr(resultRel);
	int			attno = 0;
	ListCell   *lc;

	foreach(lc, targetList)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(lc);
		Form_pg_attribute attr;

		if (tle->resjunk)
			continue;			/* ignore junk tlist items */

		if (attno >= resultDesc->natts)
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
					 errmsg("table row type and query-specified row type do not match"),
					 errdetail("Query has too many columns.")));
		attr = resultDesc->attrs[attno++];

		if (!attr->attisdropped)
		{
			/* Normal case: demand type match */
			if (exprType((Node *) tle->expr) != attr->atttypid)
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
						 errmsg("table row type and query-specified row type do not match"),
						 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
								   format_type_be(attr->atttypid),
								   attno,
								   format_type_be(exprType((Node *) tle->expr)))));
		}
		else
		{
			/*
			 * For a dropped column, we can't check atttypid (it's likely 0).
			 * In any case the planner has most likely inserted an INT4 null.
			 * What we insist on is just *some* NULL constant.
			 */
			if (!IsA(tle->expr, Const) ||
				!((Const *) tle->expr)->constisnull)
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
						 errmsg("table row type and query-specified row type do not match"),
						 errdetail("Query provides a value for a dropped column at ordinal position %d.",
								   attno)));
		}
	}
	if (attno != resultDesc->natts)
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("table row type and query-specified row type do not match"),
				 errdetail("Query has too few columns.")));
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
/*
 *		ExecGetTriggerResultRel
 *
 * Get a ResultRelInfo for a trigger target relation.  Most of the time,
 * triggers are fired on one of the result relations of the query, and so
 * we can just return a member of the es_result_relations array.  (Note: in
 * self-join situations there might be multiple members with the same OID;
 * if so it doesn't matter which one we pick.)  However, it is sometimes
 * necessary to fire triggers on other relations; this happens mainly when an
 * RI update trigger queues additional triggers on other relations, which will
B
Bruce Momjian 已提交
1057
 * be processed in the context of the outer query.	For efficiency's sake,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
 * we want to have a ResultRelInfo for those triggers too; that can avoid
 * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
 * ANALYZE to report the runtimes of such triggers.)  So we make additional
 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
 */
ResultRelInfo *
ExecGetTriggerResultRel(EState *estate, Oid relid)
{
	ResultRelInfo *rInfo;
	int			nr;
	ListCell   *l;
	Relation	rel;
	MemoryContext oldcontext;

	/* First, search through the query result relations */
	rInfo = estate->es_result_relations;
	nr = estate->es_num_result_relations;
	while (nr > 0)
	{
		if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
			return rInfo;
		rInfo++;
		nr--;
	}
	/* Nope, but maybe we already made an extra ResultRelInfo for it */
	foreach(l, estate->es_trig_target_relations)
	{
		rInfo = (ResultRelInfo *) lfirst(l);
		if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
			return rInfo;
	}
	/* Nope, so we need a new one */

	/*
	 * Open the target relation's relcache entry.  We assume that an
B
Bruce Momjian 已提交
1093 1094
	 * appropriate lock is still held by the backend from whenever the trigger
	 * event got queued, so we need take no new lock here.
1095 1096 1097 1098
	 */
	rel = heap_open(relid, NoLock);

	/*
B
Bruce Momjian 已提交
1099 1100 1101
	 * Make the new entry in the right context.  Currently, we don't need any
	 * index information in ResultRelInfos used only for triggers, so tell
	 * initResultRelInfo it's a DELETE.
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
	 */
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
	rInfo = makeNode(ResultRelInfo);
	initResultRelInfo(rInfo,
					  rel,
					  0,		/* dummy rangetable index */
					  CMD_DELETE,
					  estate->es_instrument);
	estate->es_trig_target_relations =
		lappend(estate->es_trig_target_relations, rInfo);
	MemoryContextSwitchTo(oldcontext);

	return rInfo;
}

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
/*
 *		ExecContextForcesOids
 *
 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
 * we need to ensure that result tuples have space for an OID iff they are
 * going to be stored into a relation that has OIDs.  In other contexts
 * we are free to choose whether to leave space for OIDs in result tuples
 * (we generally don't want to, but we do if a physical-tlist optimization
 * is possible).  This routine checks the plan context and returns TRUE if the
 * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
 * *hasoids is set to the required value.
 *
 * One reason this is ugly is that all plan nodes in the plan tree will emit
 * tuples with space for an OID, though we really only need the topmost node
 * to do so.  However, node types like Sort don't project new tuples but just
 * return their inputs, and in those cases the requirement propagates down
 * to the input node.  Eventually we might make this code smart enough to
 * recognize how far down the requirement really goes, but for now we just
 * make all plan nodes do the same thing if the top level forces the choice.
 *
 * We assume that estate->es_result_relation_info is already set up to
 * describe the target relation.  Note that in an UPDATE that spans an
 * inheritance tree, some of the target relations may have OIDs and some not.
 * We have to make the decisions on a per-relation basis as we initialize
 * each of the child plans of the topmost Append plan.
 *
 * SELECT INTO is even uglier, because we don't have the INTO relation's
 * descriptor available when this code runs; we have to look aside at a
 * flag set by InitPlan().
 */
bool
ExecContextForcesOids(PlanState *planstate, bool *hasoids)
{
	if (planstate->state->es_select_into)
	{
		*hasoids = planstate->state->es_into_oids;
		return true;
	}
	else
	{
		ResultRelInfo *ri = planstate->state->es_result_relation_info;

		if (ri != NULL)
		{
			Relation	rel = ri->ri_RelationDesc;

			if (rel != NULL)
			{
				*hasoids = rel->rd_rel->relhasoids;
				return true;
			}
		}
	}

	return false;
}

1174
/* ----------------------------------------------------------------
1175
 *		ExecEndPlan
1176
 *
1177
 *		Cleans up the query plan -- closes files and frees up storage
1178 1179 1180 1181 1182 1183
 *
 * NOTE: we are no longer very worried about freeing storage per se
 * in this code; FreeExecutorState should be guaranteed to release all
 * memory that needs to be released.  What we are worried about doing
 * is closing relations and dropping buffer pins.  Thus, for example,
 * tuple tables must be cleared or dropped to ensure pins are released.
1184 1185
 * ----------------------------------------------------------------
 */
1186
static void
1187
ExecEndPlan(PlanState *planstate, EState *estate)
1188
{
1189 1190
	ResultRelInfo *resultRelInfo;
	int			i;
1191
	ListCell   *l;
1192

1193 1194 1195 1196 1197 1198
	/*
	 * shut down any PlanQual processing we were doing
	 */
	if (estate->es_evalPlanQual != NULL)
		EndEvalPlanQual(estate);

B
Bruce Momjian 已提交
1199
	/*
1200
	 * shut down the node-type-specific query processing
1201
	 */
1202
	ExecEndNode(planstate);
1203

1204 1205 1206 1207 1208
	/*
	 * for subplans too
	 */
	foreach(l, estate->es_subplanstates)
	{
B
Bruce Momjian 已提交
1209
		PlanState  *subplanstate = (PlanState *) lfirst(l);
1210 1211 1212 1213

		ExecEndNode(subplanstate);
	}

B
Bruce Momjian 已提交
1214
	/*
B
Bruce Momjian 已提交
1215
	 * destroy the executor "tuple" table.
1216
	 */
1217 1218
	ExecDropTupleTable(estate->es_tupleTable, true);
	estate->es_tupleTable = NULL;
1219

B
Bruce Momjian 已提交
1220
	/*
B
Bruce Momjian 已提交
1221
	 * close the result relation(s) if any, but hold locks until xact commit.
1222
	 */
1223 1224
	resultRelInfo = estate->es_result_relations;
	for (i = estate->es_num_result_relations; i > 0; i--)
1225
	{
1226 1227 1228 1229
		/* Close indices and then the relation itself */
		ExecCloseIndices(resultRelInfo);
		heap_close(resultRelInfo->ri_RelationDesc, NoLock);
		resultRelInfo++;
1230 1231
	}

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
	/*
	 * likewise close any trigger target relations
	 */
	foreach(l, estate->es_trig_target_relations)
	{
		resultRelInfo = (ResultRelInfo *) lfirst(l);
		/* Close indices and then the relation itself */
		ExecCloseIndices(resultRelInfo);
		heap_close(resultRelInfo->ri_RelationDesc, NoLock);
	}

1243
	/*
1244
	 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1245
	 */
1246
	foreach(l, estate->es_rowMarks)
1247
	{
1248
		ExecRowMark *erm = lfirst(l);
1249 1250 1251

		heap_close(erm->relation, NoLock);
	}
1252 1253 1254
}

/* ----------------------------------------------------------------
1255 1256
 *		ExecutePlan
 *
1257
 *		processes the query plan to retrieve 'numberTuples' tuples in the
1258
 *		direction specified.
1259
 *
1260
 *		Retrieves all tuples if numberTuples is 0
1261
 *
1262
 *		result is either a slot containing the last tuple in the case
1263
 *		of a SELECT or NULL otherwise.
1264
 *
1265 1266
 * Note: the ctid attribute is a 'junk' attribute that is removed before the
 * user can see it
1267 1268 1269
 * ----------------------------------------------------------------
 */
static TupleTableSlot *
1270
ExecutePlan(EState *estate,
1271
			PlanState *planstate,
1272
			CmdType operation,
1273
			long numberTuples,
1274
			ScanDirection direction,
1275
			DestReceiver *dest)
1276
{
B
Bruce Momjian 已提交
1277
	JunkFilter *junkfilter;
1278
	TupleTableSlot *planSlot;
B
Bruce Momjian 已提交
1279 1280 1281 1282 1283
	TupleTableSlot *slot;
	ItemPointer tupleid = NULL;
	ItemPointerData tuple_ctid;
	long		current_tuple_count;
	TupleTableSlot *result;
1284

B
Bruce Momjian 已提交
1285
	/*
B
Bruce Momjian 已提交
1286
	 * initialize local variables
1287
	 */
1288 1289 1290
	current_tuple_count = 0;
	result = NULL;

B
Bruce Momjian 已提交
1291 1292
	/*
	 * Set the direction.
1293
	 */
1294 1295
	estate->es_direction = direction;

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	/*
	 * Process BEFORE EACH STATEMENT triggers
	 */
	switch (operation)
	{
		case CMD_UPDATE:
			ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_DELETE:
			ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_INSERT:
			ExecBSInsertTriggers(estate, estate->es_result_relation_info);
			break;
		default:
			/* do nothing */
1312
			break;
1313 1314
	}

B
Bruce Momjian 已提交
1315
	/*
B
Bruce Momjian 已提交
1316
	 * Loop until we've processed the proper number of tuples from the plan.
1317 1318 1319 1320
	 */

	for (;;)
	{
1321 1322
		/* Reset the per-output-tuple exprcontext */
		ResetPerTupleExprContext(estate);
B
Bruce Momjian 已提交
1323

B
Bruce Momjian 已提交
1324
		/*
B
Bruce Momjian 已提交
1325
		 * Execute the plan and obtain a tuple
1326
		 */
B
Bruce Momjian 已提交
1327
lnext:	;
1328 1329
		if (estate->es_useEvalPlan)
		{
1330 1331 1332
			planSlot = EvalPlanQualNext(estate);
			if (TupIsNull(planSlot))
				planSlot = ExecProcNode(planstate);
1333 1334
		}
		else
1335
			planSlot = ExecProcNode(planstate);
1336

B
Bruce Momjian 已提交
1337
		/*
B
Bruce Momjian 已提交
1338 1339
		 * if the tuple is null, then we assume there is nothing more to
		 * process so we just return null...
1340
		 */
1341
		if (TupIsNull(planSlot))
1342 1343 1344
		{
			result = NULL;
			break;
1345
		}
1346
		slot = planSlot;
1347

B
Bruce Momjian 已提交
1348
		/*
1349
		 * If we have a junk filter, then project a new tuple with the junk
B
Bruce Momjian 已提交
1350
		 * removed.
1351
		 *
1352
		 * Store this new "clean" tuple in the junkfilter's resultSlot.
B
Bruce Momjian 已提交
1353 1354
		 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
		 * because that tuple slot has the wrong descriptor.)
1355
		 *
1356
		 * But first, extract all the junk information we need.
1357
		 */
1358
		if ((junkfilter = estate->es_junkFilter) != NULL)
1359
		{
1360 1361 1362
			/*
			 * Process any FOR UPDATE or FOR SHARE locking requested.
			 */
1363
			if (estate->es_rowMarks != NIL)
1364
			{
1365
				ListCell   *l;
1366

B
Bruce Momjian 已提交
1367
		lmark:	;
1368
				foreach(l, estate->es_rowMarks)
1369
				{
1370
					ExecRowMark *erm = lfirst(l);
1371 1372
					Datum		datum;
					bool		isNull;
1373
					HeapTupleData tuple;
1374 1375 1376
					Buffer		buffer;
					ItemPointerData update_ctid;
					TransactionId update_xmax;
1377
					TupleTableSlot *newSlot;
B
Bruce Momjian 已提交
1378 1379
					LockTupleMode lockmode;
					HTSU_Result test;
1380

1381 1382 1383
					datum = ExecGetJunkAttribute(slot,
												 erm->ctidAttNo,
												 &isNull);
1384
					/* shouldn't ever get a null result... */
1385
					if (isNull)
1386
						elog(ERROR, "ctid is NULL");
1387

1388 1389
					tuple.t_self = *((ItemPointer) DatumGetPointer(datum));

1390
					if (erm->forUpdate)
1391 1392 1393 1394 1395
						lockmode = LockTupleExclusive;
					else
						lockmode = LockTupleShared;

					test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1396
										   &update_ctid, &update_xmax,
1397
										   estate->es_output_cid,
1398
										   lockmode, erm->noWait);
1399 1400 1401 1402
					ReleaseBuffer(buffer);
					switch (test)
					{
						case HeapTupleSelfUpdated:
1403 1404 1405
							/* treat it as deleted; do not process */
							goto lnext;

1406 1407 1408 1409
						case HeapTupleMayBeUpdated:
							break;

						case HeapTupleUpdated:
1410
							if (IsXactIsoLevelSerializable)
1411
								ereport(ERROR,
B
Bruce Momjian 已提交
1412 1413
								 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
								  errmsg("could not serialize access due to concurrent update")));
1414 1415
							if (!ItemPointerEquals(&update_ctid,
												   &tuple.t_self))
1416
							{
1417 1418 1419 1420
								/* updated, so look at updated version */
								newSlot = EvalPlanQual(estate,
													   erm->rti,
													   &update_ctid,
1421
													   update_xmax);
1422
								if (!TupIsNull(newSlot))
1423
								{
1424
									slot = planSlot = newSlot;
1425 1426 1427 1428
									estate->es_useEvalPlan = true;
									goto lmark;
								}
							}
B
Bruce Momjian 已提交
1429 1430 1431

							/*
							 * if tuple was deleted or PlanQual failed for
B
Bruce Momjian 已提交
1432
							 * updated tuple - we must not return this tuple!
1433 1434
							 */
							goto lnext;
1435 1436

						default:
1437
							elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1438
								 test);
1439
							return NULL;
1440 1441 1442
					}
				}
			}
1443

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
			/*
			 * extract the 'ctid' junk attribute.
			 */
			if (operation == CMD_UPDATE || operation == CMD_DELETE)
			{
				Datum		datum;
				bool		isNull;

				datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
											 &isNull);
				/* shouldn't ever get a null result... */
				if (isNull)
					elog(ERROR, "ctid is NULL");

				tupleid = (ItemPointer) DatumGetPointer(datum);
				tuple_ctid = *tupleid;	/* make sure we don't free the ctid!! */
				tupleid = &tuple_ctid;
			}

B
Bruce Momjian 已提交
1463
			/*
B
Bruce Momjian 已提交
1464 1465 1466
			 * Create a new "clean" tuple with all junk attributes removed. We
			 * don't need to do this for DELETE, however (there will in fact
			 * be no non-junk attributes in a DELETE!)
1467
			 */
1468 1469
			if (operation != CMD_DELETE)
				slot = ExecFilterJunk(junkfilter, slot);
1470
		}
1471

B
Bruce Momjian 已提交
1472
		/*
B
Bruce Momjian 已提交
1473 1474 1475
		 * now that we have a tuple, do the appropriate thing with it.. either
		 * return it to the user, add it to a relation someplace, delete it
		 * from a relation, or modify some of its attributes.
1476 1477 1478
		 */
		switch (operation)
		{
1479
			case CMD_SELECT:
1480
				ExecSelect(slot, dest, estate);
1481 1482
				result = slot;
				break;
1483

1484
			case CMD_INSERT:
1485
				ExecInsert(slot, tupleid, planSlot, dest, estate);
1486 1487
				result = NULL;
				break;
1488

1489
			case CMD_DELETE:
1490
				ExecDelete(tupleid, planSlot, dest, estate);
1491 1492
				result = NULL;
				break;
1493

1494
			case CMD_UPDATE:
1495
				ExecUpdate(slot, tupleid, planSlot, dest, estate);
1496 1497
				result = NULL;
				break;
1498

1499
			default:
1500 1501
				elog(ERROR, "unrecognized operation code: %d",
					 (int) operation);
1502
				result = NULL;
1503
				break;
1504
		}
B
Bruce Momjian 已提交
1505

B
Bruce Momjian 已提交
1506
		/*
B
Bruce Momjian 已提交
1507 1508 1509
		 * check our tuple count.. if we've processed the proper number then
		 * quit, else loop again and process more tuples.  Zero numberTuples
		 * means no limit.
1510
		 */
1511
		current_tuple_count++;
1512
		if (numberTuples && numberTuples == current_tuple_count)
1513
			break;
1514
	}
1515

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
	/*
	 * Process AFTER EACH STATEMENT triggers
	 */
	switch (operation)
	{
		case CMD_UPDATE:
			ExecASUpdateTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_DELETE:
			ExecASDeleteTriggers(estate, estate->es_result_relation_info);
			break;
		case CMD_INSERT:
			ExecASInsertTriggers(estate, estate->es_result_relation_info);
			break;
		default:
			/* do nothing */
1532
			break;
1533 1534
	}

B
Bruce Momjian 已提交
1535
	/*
B
Bruce Momjian 已提交
1536
	 * here, result is either a slot containing a tuple in the case of a
1537
	 * SELECT or NULL otherwise.
1538
	 */
1539
	return result;
1540 1541 1542
}

/* ----------------------------------------------------------------
1543
 *		ExecSelect
1544
 *
1545
 *		SELECTs are easy.. we just pass the tuple to the appropriate
1546
 *		output function.
1547 1548 1549
 * ----------------------------------------------------------------
 */
static void
1550
ExecSelect(TupleTableSlot *slot,
1551
		   DestReceiver *dest,
1552
		   EState *estate)
1553
{
1554
	(*dest->receiveSlot) (slot, dest);
1555 1556
	IncrRetrieved();
	(estate->es_processed)++;
1557 1558 1559
}

/* ----------------------------------------------------------------
1560
 *		ExecInsert
1561
 *
1562
 *		INSERTs are trickier.. we have to insert the tuple into
1563 1564
 *		the base relation and insert appropriate tuples into the
 *		index relations.
1565 1566 1567
 * ----------------------------------------------------------------
 */
static void
1568
ExecInsert(TupleTableSlot *slot,
1569
		   ItemPointer tupleid,
1570 1571
		   TupleTableSlot *planSlot,
		   DestReceiver *dest,
1572
		   EState *estate)
1573
{
1574
	HeapTuple	tuple;
1575
	ResultRelInfo *resultRelInfo;
1576 1577
	Relation	resultRelationDesc;
	Oid			newId;
1578

B
Bruce Momjian 已提交
1579
	/*
B
Bruce Momjian 已提交
1580 1581
	 * get the heap tuple out of the tuple table slot, making sure we have a
	 * writable copy
1582
	 */
1583
	tuple = ExecMaterializeSlot(slot);
1584

B
Bruce Momjian 已提交
1585
	/*
1586
	 * get information on the (current) result relation
1587
	 */
1588 1589
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1590 1591

	/* BEFORE ROW INSERT Triggers */
1592
	if (resultRelInfo->ri_TrigDesc &&
B
Bruce Momjian 已提交
1593
		resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1594
	{
1595
		HeapTuple	newtuple;
1596

1597
		newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1598 1599 1600 1601 1602 1603

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
1604
			/*
1605 1606
			 * Put the modified tuple into a slot for convenience of routines
			 * below.  We assume the tuple was allocated in per-tuple memory
B
Bruce Momjian 已提交
1607 1608
			 * context, and therefore will go away by itself. The tuple table
			 * slot should not try to clear it.
1609
			 */
1610 1611 1612
			TupleTableSlot *newslot = estate->es_trig_tuple_slot;

			if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1613
				ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1614 1615
			ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
			slot = newslot;
1616
			tuple = newtuple;
1617 1618 1619
		}
	}

B
Bruce Momjian 已提交
1620
	/*
1621
	 * Check the constraints of the tuple
1622 1623
	 */
	if (resultRelationDesc->rd_att->constr)
1624
		ExecConstraints(resultRelInfo, slot, estate);
1625

B
Bruce Momjian 已提交
1626
	/*
B
Bruce Momjian 已提交
1627
	 * insert the tuple
1628
	 *
B
Bruce Momjian 已提交
1629 1630
	 * Note: heap_insert returns the tid (location) of the new tuple in the
	 * t_self field.
1631
	 */
1632
	newId = heap_insert(resultRelationDesc, tuple,
1633
						estate->es_output_cid,
1634
						true, true);
1635

1636
	IncrAppended();
1637 1638
	(estate->es_processed)++;
	estate->es_lastoid = newId;
T
Tom Lane 已提交
1639
	setLastTid(&(tuple->t_self));
1640

B
Bruce Momjian 已提交
1641
	/*
1642
	 * insert index entries for tuple
1643
	 */
1644
	if (resultRelInfo->ri_NumIndices > 0)
1645
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1646 1647

	/* AFTER ROW INSERT Triggers */
1648
	ExecARInsertTriggers(estate, resultRelInfo, tuple);
1649 1650 1651 1652 1653

	/* Process RETURNING if present */
	if (resultRelInfo->ri_projectReturning)
		ExecProcessReturning(resultRelInfo->ri_projectReturning,
							 slot, planSlot, dest);
1654 1655 1656
}

/* ----------------------------------------------------------------
1657
 *		ExecDelete
1658
 *
1659 1660
 *		DELETE is like UPDATE, except that we delete the tuple and no
 *		index modifications are needed
1661 1662 1663
 * ----------------------------------------------------------------
 */
static void
1664 1665 1666
ExecDelete(ItemPointer tupleid,
		   TupleTableSlot *planSlot,
		   DestReceiver *dest,
1667
		   EState *estate)
1668
{
1669
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
1670
	Relation	resultRelationDesc;
B
Bruce Momjian 已提交
1671
	HTSU_Result result;
1672 1673
	ItemPointerData update_ctid;
	TransactionId update_xmax;
1674

B
Bruce Momjian 已提交
1675
	/*
1676
	 * get information on the (current) result relation
1677
	 */
1678 1679
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1680 1681

	/* BEFORE ROW DELETE Triggers */
1682
	if (resultRelInfo->ri_TrigDesc &&
B
Bruce Momjian 已提交
1683
		resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1684
	{
1685
		bool		dodelete;
1686

1687
		dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1688 1689 1690 1691 1692

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

V
Vadim B. Mikheev 已提交
1693
	/*
B
Bruce Momjian 已提交
1694
	 * delete the tuple
1695
	 *
1696 1697
	 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
	 * the row to be deleted is visible to that snapshot, and throw a can't-
B
Bruce Momjian 已提交
1698
	 * serialize error if not.	This is a special-case behavior needed for
1699
	 * referential integrity updates in serializable transactions.
1700
	 */
1701
ldelete:;
1702
	result = heap_delete(resultRelationDesc, tupleid,
1703
						 &update_ctid, &update_xmax,
1704
						 estate->es_output_cid,
1705
						 estate->es_crosscheck_snapshot,
B
Bruce Momjian 已提交
1706
						 true /* wait for commit */ );
V
Vadim B. Mikheev 已提交
1707 1708 1709
	switch (result)
	{
		case HeapTupleSelfUpdated:
1710
			/* already deleted by self; nothing to do */
V
Vadim B. Mikheev 已提交
1711 1712 1713 1714 1715 1716
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1717
			if (IsXactIsoLevelSerializable)
1718 1719
				ereport(ERROR,
						(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1720
						 errmsg("could not serialize access due to concurrent update")));
1721
			else if (!ItemPointerEquals(tupleid, &update_ctid))
1722
			{
1723
				TupleTableSlot *epqslot;
1724

1725 1726 1727
				epqslot = EvalPlanQual(estate,
									   resultRelInfo->ri_RangeTableIndex,
									   &update_ctid,
1728
									   update_xmax);
V
Vadim B. Mikheev 已提交
1729
				if (!TupIsNull(epqslot))
1730
				{
1731
					*tupleid = update_ctid;
1732 1733 1734
					goto ldelete;
				}
			}
1735
			/* tuple already deleted; nothing to do */
V
Vadim B. Mikheev 已提交
1736 1737 1738
			return;

		default:
1739
			elog(ERROR, "unrecognized heap_delete status: %u", result);
V
Vadim B. Mikheev 已提交
1740 1741
			return;
	}
1742 1743 1744 1745

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

B
Bruce Momjian 已提交
1746
	/*
B
Bruce Momjian 已提交
1747
	 * Note: Normally one would think that we have to delete index tuples
1748
	 * associated with the heap tuple now...
1749
	 *
1750 1751 1752
	 * ... but in POSTGRES, we have no need to do this because VACUUM will
	 * take care of it later.  We can't delete index tuples immediately
	 * anyway, since the tuple is still visible to other transactions.
1753 1754 1755
	 */

	/* AFTER ROW DELETE Triggers */
1756
	ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1757 1758 1759 1760 1761

	/* Process RETURNING if present */
	if (resultRelInfo->ri_projectReturning)
	{
		/*
B
Bruce Momjian 已提交
1762 1763
		 * We have to put the target tuple into a slot, which means first we
		 * gotta fetch it.	We can use the trigger tuple slot.
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
		 */
		TupleTableSlot *slot = estate->es_trig_tuple_slot;
		HeapTupleData deltuple;
		Buffer		delbuffer;

		deltuple.t_self = *tupleid;
		if (!heap_fetch(resultRelationDesc, SnapshotAny,
						&deltuple, &delbuffer, false, NULL))
			elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");

		if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
			ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
		ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);

		ExecProcessReturning(resultRelInfo->ri_projectReturning,
							 slot, planSlot, dest);

		ExecClearTuple(slot);
		ReleaseBuffer(delbuffer);
	}
1784 1785 1786
}

/* ----------------------------------------------------------------
1787
 *		ExecUpdate
1788
 *
1789 1790 1791 1792
 *		note: we can't run UPDATE queries with transactions
 *		off because UPDATEs are actually INSERTs and our
 *		scan will mistakenly loop forever, updating the tuple
 *		it just inserted..	This should be fixed but until it
1793 1794
 *		is, we don't want to get stuck in an infinite loop
 *		which corrupts your database..
1795 1796 1797
 * ----------------------------------------------------------------
 */
static void
1798
ExecUpdate(TupleTableSlot *slot,
B
Bruce Momjian 已提交
1799
		   ItemPointer tupleid,
1800 1801
		   TupleTableSlot *planSlot,
		   DestReceiver *dest,
B
Bruce Momjian 已提交
1802
		   EState *estate)
1803
{
B
Bruce Momjian 已提交
1804
	HeapTuple	tuple;
1805
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
1806
	Relation	resultRelationDesc;
B
Bruce Momjian 已提交
1807
	HTSU_Result result;
1808 1809
	ItemPointerData update_ctid;
	TransactionId update_xmax;
1810

B
Bruce Momjian 已提交
1811
	/*
B
Bruce Momjian 已提交
1812
	 * abort the operation if not running transactions
1813 1814
	 */
	if (IsBootstrapProcessingMode())
1815
		elog(ERROR, "cannot UPDATE during bootstrap");
1816

B
Bruce Momjian 已提交
1817
	/*
B
Bruce Momjian 已提交
1818 1819
	 * get the heap tuple out of the tuple table slot, making sure we have a
	 * writable copy
1820
	 */
1821
	tuple = ExecMaterializeSlot(slot);
1822

B
Bruce Momjian 已提交
1823
	/*
1824
	 * get information on the (current) result relation
1825
	 */
1826 1827
	resultRelInfo = estate->es_result_relation_info;
	resultRelationDesc = resultRelInfo->ri_RelationDesc;
1828 1829

	/* BEFORE ROW UPDATE Triggers */
1830
	if (resultRelInfo->ri_TrigDesc &&
B
Bruce Momjian 已提交
1831
		resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1832
	{
1833
		HeapTuple	newtuple;
1834

1835
		newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1836
										tupleid, tuple);
1837 1838 1839 1840 1841 1842

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

		if (newtuple != tuple)	/* modified by Trigger(s) */
		{
1843
			/*
1844 1845
			 * Put the modified tuple into a slot for convenience of routines
			 * below.  We assume the tuple was allocated in per-tuple memory
B
Bruce Momjian 已提交
1846 1847
			 * context, and therefore will go away by itself. The tuple table
			 * slot should not try to clear it.
1848
			 */
1849 1850 1851
			TupleTableSlot *newslot = estate->es_trig_tuple_slot;

			if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1852
				ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1853 1854
			ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
			slot = newslot;
1855
			tuple = newtuple;
1856 1857 1858
		}
	}

B
Bruce Momjian 已提交
1859
	/*
1860
	 * Check the constraints of the tuple
1861
	 *
1862 1863
	 * If we generate a new candidate tuple after EvalPlanQual testing, we
	 * must loop back here and recheck constraints.  (We don't need to redo
B
Bruce Momjian 已提交
1864 1865 1866
	 * triggers, however.  If there are any BEFORE triggers then trigger.c
	 * will have done heap_lock_tuple to lock the correct tuple, so there's no
	 * need to do them again.)
1867
	 */
1868
lreplace:;
1869
	if (resultRelationDesc->rd_att->constr)
1870
		ExecConstraints(resultRelInfo, slot, estate);
1871

V
Vadim B. Mikheev 已提交
1872
	/*
B
Bruce Momjian 已提交
1873
	 * replace the heap tuple
1874
	 *
1875 1876
	 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
	 * the row to be updated is visible to that snapshot, and throw a can't-
B
Bruce Momjian 已提交
1877
	 * serialize error if not.	This is a special-case behavior needed for
1878
	 * referential integrity updates in serializable transactions.
1879
	 */
1880
	result = heap_update(resultRelationDesc, tupleid, tuple,
1881
						 &update_ctid, &update_xmax,
1882
						 estate->es_output_cid,
1883
						 estate->es_crosscheck_snapshot,
B
Bruce Momjian 已提交
1884
						 true /* wait for commit */ );
V
Vadim B. Mikheev 已提交
1885 1886 1887
	switch (result)
	{
		case HeapTupleSelfUpdated:
1888
			/* already deleted by self; nothing to do */
V
Vadim B. Mikheev 已提交
1889 1890 1891 1892 1893 1894
			return;

		case HeapTupleMayBeUpdated:
			break;

		case HeapTupleUpdated:
1895
			if (IsXactIsoLevelSerializable)
1896 1897
				ereport(ERROR,
						(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1898
						 errmsg("could not serialize access due to concurrent update")));
1899
			else if (!ItemPointerEquals(tupleid, &update_ctid))
1900
			{
1901
				TupleTableSlot *epqslot;
1902

1903 1904 1905
				epqslot = EvalPlanQual(estate,
									   resultRelInfo->ri_RangeTableIndex,
									   &update_ctid,
1906
									   update_xmax);
V
Vadim B. Mikheev 已提交
1907
				if (!TupIsNull(epqslot))
1908
				{
1909
					*tupleid = update_ctid;
1910 1911
					slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
					tuple = ExecMaterializeSlot(slot);
1912 1913 1914
					goto lreplace;
				}
			}
1915
			/* tuple already deleted; nothing to do */
V
Vadim B. Mikheev 已提交
1916 1917 1918
			return;

		default:
1919
			elog(ERROR, "unrecognized heap_update status: %u", result);
V
Vadim B. Mikheev 已提交
1920
			return;
1921 1922 1923 1924 1925
	}

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

B
Bruce Momjian 已提交
1926
	/*
B
Bruce Momjian 已提交
1927 1928 1929
	 * 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 UPDATEs are actually DELETEs and INSERTs, and index tuple
1930
	 * deletion is done later by VACUUM (see notes in ExecDelete).	All we do
1931
	 * here is insert new index tuples.  -cim 9/27/89
1932 1933
	 */

B
Bruce Momjian 已提交
1934
	/*
1935
	 * insert index entries for tuple
1936
	 *
B
Bruce Momjian 已提交
1937 1938
	 * Note: heap_update returns the tid (location) of the new tuple in the
	 * t_self field.
1939 1940
	 *
	 * If it's a HOT update, we mustn't insert new index entries.
1941
	 */
1942
	if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
1943
		ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1944 1945

	/* AFTER ROW UPDATE Triggers */
1946
	ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1947 1948 1949 1950 1951

	/* Process RETURNING if present */
	if (resultRelInfo->ri_projectReturning)
		ExecProcessReturning(resultRelInfo->ri_projectReturning,
							 slot, planSlot, dest);
1952
}
V
Vadim B. Mikheev 已提交
1953

1954 1955 1956
/*
 * ExecRelCheck --- check that tuple meets constraints for result relation
 */
1957
static const char *
1958 1959
ExecRelCheck(ResultRelInfo *resultRelInfo,
			 TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
1960
{
1961
	Relation	rel = resultRelInfo->ri_RelationDesc;
1962 1963
	int			ncheck = rel->rd_att->constr->num_check;
	ConstrCheck *check = rel->rd_att->constr->check;
1964
	ExprContext *econtext;
1965
	MemoryContext oldContext;
1966 1967
	List	   *qual;
	int			i;
1968

1969 1970
	/*
	 * If first time through for this result relation, build expression
B
Bruce Momjian 已提交
1971 1972
	 * nodetrees for rel's constraint expressions.  Keep them in the per-query
	 * memory context so they'll survive throughout the query.
1973 1974 1975 1976 1977 1978 1979 1980
	 */
	if (resultRelInfo->ri_ConstraintExprs == NULL)
	{
		oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
		resultRelInfo->ri_ConstraintExprs =
			(List **) palloc(ncheck * sizeof(List *));
		for (i = 0; i < ncheck; i++)
		{
1981 1982
			/* ExecQual wants implicit-AND form */
			qual = make_ands_implicit(stringToNode(check[i].ccbin));
1983
			resultRelInfo->ri_ConstraintExprs[i] = (List *)
1984
				ExecPrepareExpr((Expr *) qual, estate);
1985 1986 1987 1988
		}
		MemoryContextSwitchTo(oldContext);
	}

1989
	/*
B
Bruce Momjian 已提交
1990 1991
	 * We will use the EState's per-tuple context for evaluating constraint
	 * expressions (creating it if it's not already there).
1992
	 */
1993
	econtext = GetPerTupleExprContext(estate);
1994

1995 1996 1997 1998
	/* Arrange for econtext's scan tuple to be the tuple under test */
	econtext->ecxt_scantuple = slot;

	/* And evaluate the constraints */
1999 2000
	for (i = 0; i < ncheck; i++)
	{
2001
		qual = resultRelInfo->ri_ConstraintExprs[i];
2002

2003 2004
		/*
		 * NOTE: SQL92 specifies that a NULL result from a constraint
2005 2006
		 * expression is not to be treated as a failure.  Therefore, tell
		 * ExecQual to return TRUE for NULL.
2007
		 */
2008
		if (!ExecQual(qual, econtext, true))
2009
			return check[i].ccname;
2010 2011
	}

2012
	/* NULL result means no error */
2013
	return NULL;
V
Vadim B. Mikheev 已提交
2014 2015
}

2016
void
2017
ExecConstraints(ResultRelInfo *resultRelInfo,
2018
				TupleTableSlot *slot, EState *estate)
V
Vadim B. Mikheev 已提交
2019
{
2020
	Relation	rel = resultRelInfo->ri_RelationDesc;
2021 2022 2023
	TupleConstr *constr = rel->rd_att->constr;

	Assert(constr);
2024

2025
	if (constr->has_not_null)
V
Vadim B. Mikheev 已提交
2026
	{
2027
		int			natts = rel->rd_att->natts;
2028
		int			attrChk;
2029

2030
		for (attrChk = 1; attrChk <= natts; attrChk++)
2031
		{
B
Bruce Momjian 已提交
2032
			if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2033
				slot_attisnull(slot, attrChk))
2034 2035
				ereport(ERROR,
						(errcode(ERRCODE_NOT_NULL_VIOLATION),
2036
						 errmsg("null value in column \"%s\" violates not-null constraint",
B
Bruce Momjian 已提交
2037
						NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2038 2039 2040
		}
	}

2041
	if (constr->num_check > 0)
2042
	{
B
Bruce Momjian 已提交
2043
		const char *failed;
2044

2045
		if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2046 2047
			ereport(ERROR,
					(errcode(ERRCODE_CHECK_VIOLATION),
2048
					 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2049
							RelationGetRelationName(rel), failed)));
2050
	}
V
Vadim B. Mikheev 已提交
2051
}
2052

2053 2054 2055 2056 2057 2058 2059 2060 2061
/*
 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
 *
 * projectReturning: RETURNING projection info for current result rel
 * tupleSlot: slot holding tuple actually inserted/updated/deleted
 * planSlot: slot holding tuple returned by top plan node
 * dest: where to send the output
 */
static void
B
Bruce Momjian 已提交
2062
ExecProcessReturning(ProjectionInfo *projectReturning,
2063 2064 2065 2066
					 TupleTableSlot *tupleSlot,
					 TupleTableSlot *planSlot,
					 DestReceiver *dest)
{
B
Bruce Momjian 已提交
2067 2068
	ExprContext *econtext = projectReturning->pi_exprContext;
	TupleTableSlot *retSlot;
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088

	/*
	 * Reset per-tuple memory context to free any expression evaluation
	 * storage allocated in the previous cycle.
	 */
	ResetExprContext(econtext);

	/* Make tuple and any needed join variables available to ExecProject */
	econtext->ecxt_scantuple = tupleSlot;
	econtext->ecxt_outertuple = planSlot;

	/* Compute the RETURNING expressions */
	retSlot = ExecProject(projectReturning, NULL);

	/* Send to dest */
	(*dest->receiveSlot) (retSlot, dest);

	ExecClearTuple(retSlot);
}

2089 2090 2091 2092 2093
/*
 * Check a modified tuple to see if we want to process its updated version
 * under READ COMMITTED rules.
 *
 * See backend/executor/README for some info about how this works.
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
 *
 *	estate - executor state data
 *	rti - rangetable index of table containing tuple
 *	*tid - t_ctid from the outdated tuple (ie, next updated version)
 *	priorXmax - t_xmax from the outdated tuple
 *
 * *tid is also an output parameter: it's modified to hold the TID of the
 * latest version of the tuple (note this may be changed even on failure)
 *
 * Returns a slot containing the new candidate update/delete tuple, or
 * NULL if we determine we shouldn't process the row.
2105
 */
B
Bruce Momjian 已提交
2106
TupleTableSlot *
2107
EvalPlanQual(EState *estate, Index rti,
2108
			 ItemPointer tid, TransactionId priorXmax)
2109
{
2110 2111
	evalPlanQual *epq;
	EState	   *epqstate;
B
Bruce Momjian 已提交
2112 2113
	Relation	relation;
	HeapTupleData tuple;
2114
	HeapTuple	copyTuple = NULL;
2115
	SnapshotData SnapshotDirty;
2116
	bool		endNode;
2117 2118 2119

	Assert(rti != 0);

2120 2121 2122 2123 2124 2125 2126 2127
	/*
	 * find relation containing target tuple
	 */
	if (estate->es_result_relation_info != NULL &&
		estate->es_result_relation_info->ri_RangeTableIndex == rti)
		relation = estate->es_result_relation_info->ri_RelationDesc;
	else
	{
2128
		ListCell   *l;
2129 2130

		relation = NULL;
2131
		foreach(l, estate->es_rowMarks)
2132
		{
2133
			if (((ExecRowMark *) lfirst(l))->rti == rti)
2134
			{
2135
				relation = ((ExecRowMark *) lfirst(l))->relation;
2136 2137 2138 2139
				break;
			}
		}
		if (relation == NULL)
2140
			elog(ERROR, "could not find RowMark for RT index %u", rti);
2141 2142 2143 2144 2145 2146 2147
	}

	/*
	 * fetch tid tuple
	 *
	 * Loop here to deal with updated or busy tuples
	 */
2148
	InitDirtySnapshot(SnapshotDirty);
2149 2150 2151 2152 2153
	tuple.t_self = *tid;
	for (;;)
	{
		Buffer		buffer;

2154
		if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2155
		{
2156 2157
			/*
			 * If xmin isn't what we're expecting, the slot must have been
B
Bruce Momjian 已提交
2158 2159 2160
			 * recycled and reused for an unrelated tuple.	This implies that
			 * the latest version of the row was deleted, so we need do
			 * nothing.  (Should be safe to examine xmin without getting
2161 2162 2163 2164 2165 2166 2167 2168 2169
			 * buffer's content lock, since xmin never changes in an existing
			 * tuple.)
			 */
			if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
									 priorXmax))
			{
				ReleaseBuffer(buffer);
				return NULL;
			}
2170

2171
			/* otherwise xmin should not be dirty... */
2172
			if (TransactionIdIsValid(SnapshotDirty.xmin))
2173
				elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2174 2175

			/*
B
Bruce Momjian 已提交
2176 2177
			 * If tuple is being updated by other transaction then we have to
			 * wait for its commit/abort.
2178
			 */
2179
			if (TransactionIdIsValid(SnapshotDirty.xmax))
2180 2181
			{
				ReleaseBuffer(buffer);
2182
				XactLockTableWait(SnapshotDirty.xmax);
2183
				continue;		/* loop back to repeat heap_fetch */
2184 2185
			}

2186 2187
			/*
			 * If tuple was inserted by our own transaction, we have to check
2188 2189 2190 2191
			 * cmin against es_output_cid: cmin >= current CID means our
			 * command cannot see the tuple, so we should ignore it.  Without
			 * this we are open to the "Halloween problem" of indefinitely
			 * re-updating the same tuple. (We need not check cmax because
B
Bruce Momjian 已提交
2192 2193 2194 2195
			 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
			 * transaction dead, regardless of cmax.)  We just checked that
			 * priorXmax == xmin, so we can test that variable instead of
			 * doing HeapTupleHeaderGetXmin again.
2196 2197
			 */
			if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2198
				HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2199 2200 2201 2202 2203
			{
				ReleaseBuffer(buffer);
				return NULL;
			}

2204 2205 2206 2207 2208 2209 2210 2211 2212
			/*
			 * We got tuple - now copy it for use by recheck query.
			 */
			copyTuple = heap_copytuple(&tuple);
			ReleaseBuffer(buffer);
			break;
		}

		/*
B
Bruce Momjian 已提交
2213 2214
		 * If the referenced slot was actually empty, the latest version of
		 * the row must have been deleted, so we need do nothing.
2215
		 */
2216
		if (tuple.t_data == NULL)
2217
		{
2218 2219
			ReleaseBuffer(buffer);
			return NULL;
2220 2221 2222
		}

		/*
2223
		 * As above, if xmin isn't what we're expecting, do nothing.
2224
		 */
2225 2226 2227 2228 2229 2230 2231 2232 2233
		if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
								 priorXmax))
		{
			ReleaseBuffer(buffer);
			return NULL;
		}

		/*
		 * If we get here, the tuple was found but failed SnapshotDirty.
B
Bruce Momjian 已提交
2234 2235 2236 2237 2238 2239
		 * Assuming the xmin is either a committed xact or our own xact (as it
		 * certainly should be if we're trying to modify the tuple), this must
		 * mean that the row was updated or deleted by either a committed xact
		 * or our own xact.  If it was deleted, we can ignore it; if it was
		 * updated then chain up to the next version and repeat the whole
		 * test.
2240
		 *
B
Bruce Momjian 已提交
2241 2242
		 * As above, it should be safe to examine xmax and t_ctid without the
		 * buffer content lock, because they can't be changing.
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
		 */
		if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
		{
			/* deleted, so forget about it */
			ReleaseBuffer(buffer);
			return NULL;
		}

		/* updated, so look at the updated row */
		tuple.t_self = tuple.t_data->t_ctid;
		/* updated row should have xmin matching this xmax */
		priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
		ReleaseBuffer(buffer);
		/* loop back to fetch next in chain */
2257 2258 2259
	}

	/*
B
Bruce Momjian 已提交
2260 2261
	 * For UPDATE/DELETE we have to return tid of actual row we're executing
	 * PQ for.
2262 2263 2264 2265
	 */
	*tid = tuple.t_self;

	/*
2266
	 * Need to run a recheck subquery.	Find or create a PQ stack entry.
2267
	 */
2268
	epq = estate->es_evalPlanQual;
2269 2270
	endNode = true;

2271 2272
	if (epq != NULL && epq->rti == 0)
	{
2273
		/* Top PQ stack entry is idle, so re-use it */
2274
		Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2275 2276 2277 2278 2279
		epq->rti = rti;
		endNode = false;
	}

	/*
B
Bruce Momjian 已提交
2280 2281 2282 2283
	 * If this is request for another RTE - Ra, - then we have to check 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? -:))
2284
	 */
B
Bruce Momjian 已提交
2285
	if (epq != NULL && epq->rti != rti &&
2286
		epq->estate->es_evTuple[rti - 1] != NULL)
2287 2288 2289
	{
		do
		{
2290 2291
			evalPlanQual *oldepq;

2292
			/* stop execution */
2293 2294 2295 2296
			EvalPlanQualStop(epq);
			/* pop previous PlanQual from the stack */
			oldepq = epq->next;
			Assert(oldepq && oldepq->rti != 0);
2297 2298 2299
			/* push current PQ to freePQ stack */
			oldepq->free = epq;
			epq = oldepq;
2300
			estate->es_evalPlanQual = epq;
2301 2302 2303
		} while (epq->rti != rti);
	}

B
Bruce Momjian 已提交
2304
	/*
B
Bruce Momjian 已提交
2305 2306
	 * If we are requested for another RTE then we have to suspend execution
	 * of current PlanQual and start execution for new one.
2307 2308 2309 2310
	 */
	if (epq == NULL || epq->rti != rti)
	{
		/* try to reuse plan used previously */
B
Bruce Momjian 已提交
2311
		evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2312

2313
		if (newepq == NULL)		/* first call or freePQ stack is empty */
2314
		{
2315
			newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2316
			newepq->free = NULL;
2317 2318
			newepq->estate = NULL;
			newepq->planstate = NULL;
2319 2320
		}
		else
2321
		{
2322 2323 2324
			/* recycle previously used PlanQual */
			Assert(newepq->estate == NULL);
			epq->free = NULL;
2325
		}
2326
		/* push current PQ to the stack */
2327
		newepq->next = epq;
2328
		epq = newepq;
2329
		estate->es_evalPlanQual = epq;
2330 2331 2332 2333
		epq->rti = rti;
		endNode = false;
	}

2334
	Assert(epq->rti == rti);
2335 2336

	/*
B
Bruce Momjian 已提交
2337 2338 2339 2340 2341 2342
	 * Ok - we're requested for the same RTE.  Unfortunately we still have to
	 * end and restart execution of the plan, because ExecReScan wouldn't
	 * ensure that upper plan nodes would reset themselves.  We could make
	 * that work if insertion of the target tuple were integrated with the
	 * Param mechanism somehow, so that the upper plan nodes know that their
	 * children's outputs have changed.
2343
	 *
B
Bruce Momjian 已提交
2344 2345
	 * Note that the stack of free evalPlanQual nodes is quite useless at the
	 * moment, since it only saves us from pallocing/releasing the
B
Bruce Momjian 已提交
2346 2347
	 * evalPlanQual nodes themselves.  But it will be useful once we implement
	 * ReScan instead of end/restart for re-using PlanQual nodes.
2348 2349
	 */
	if (endNode)
2350
	{
2351
		/* stop execution */
2352
		EvalPlanQualStop(epq);
2353
	}
2354

2355 2356 2357
	/*
	 * Initialize new recheck query.
	 *
B
Bruce Momjian 已提交
2358 2359
	 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
	 * instead copy down changeable state from the top plan (including
B
Bruce Momjian 已提交
2360 2361
	 * es_result_relation_info, es_junkFilter) and reset locally changeable
	 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2362 2363 2364
	 */
	EvalPlanQualStart(epq, estate, epq->next);

2365
	/*
B
Bruce Momjian 已提交
2366 2367
	 * free old RTE' tuple, if any, and store target tuple where relation's
	 * scan node will see it
2368
	 */
2369
	epqstate = epq->estate;
2370 2371 2372
	if (epqstate->es_evTuple[rti - 1] != NULL)
		heap_freetuple(epqstate->es_evTuple[rti - 1]);
	epqstate->es_evTuple[rti - 1] = copyTuple;
2373

2374
	return EvalPlanQualNext(estate);
2375 2376
}

B
Bruce Momjian 已提交
2377
static TupleTableSlot *
2378 2379
EvalPlanQualNext(EState *estate)
{
2380 2381
	evalPlanQual *epq = estate->es_evalPlanQual;
	MemoryContext oldcontext;
B
Bruce Momjian 已提交
2382
	TupleTableSlot *slot;
2383 2384 2385 2386

	Assert(epq->rti != 0);

lpqnext:;
2387
	oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2388
	slot = ExecProcNode(epq->planstate);
2389
	MemoryContextSwitchTo(oldcontext);
2390 2391 2392 2393 2394 2395

	/*
	 * No more tuples for this PQ. Continue previous one.
	 */
	if (TupIsNull(slot))
	{
2396 2397
		evalPlanQual *oldepq;

2398
		/* stop execution */
2399
		EvalPlanQualStop(epq);
2400
		/* pop old PQ from the stack */
2401 2402
		oldepq = epq->next;
		if (oldepq == NULL)
2403
		{
2404 2405 2406 2407
			/* this is the first (oldest) PQ - mark as free */
			epq->rti = 0;
			estate->es_useEvalPlan = false;
			/* and continue Query execution */
2408
			return NULL;
2409 2410 2411 2412 2413
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
2414
		estate->es_evalPlanQual = epq;
2415 2416 2417
		goto lpqnext;
	}

2418
	return slot;
2419
}
2420 2421 2422 2423

static void
EndEvalPlanQual(EState *estate)
{
2424
	evalPlanQual *epq = estate->es_evalPlanQual;
2425

2426 2427
	if (epq->rti == 0)			/* plans already shutdowned */
	{
2428
		Assert(epq->next == NULL);
2429
		return;
2430
	}
2431 2432 2433

	for (;;)
	{
2434 2435
		evalPlanQual *oldepq;

2436
		/* stop execution */
2437
		EvalPlanQualStop(epq);
2438
		/* pop old PQ from the stack */
2439 2440
		oldepq = epq->next;
		if (oldepq == NULL)
2441
		{
2442 2443 2444
			/* this is the first (oldest) PQ - mark as free */
			epq->rti = 0;
			estate->es_useEvalPlan = false;
2445 2446 2447 2448 2449 2450
			break;
		}
		Assert(oldepq->rti != 0);
		/* push current PQ to freePQ stack */
		oldepq->free = epq;
		epq = oldepq;
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
		estate->es_evalPlanQual = epq;
	}
}

/*
 * Start execution of one level of PlanQual.
 *
 * This is a cut-down version of ExecutorStart(): we copy some state from
 * the top-level estate rather than initializing it fresh.
 */
static void
EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
{
	EState	   *epqstate;
	int			rtsize;
	MemoryContext oldcontext;
2467
	ListCell   *l;
2468

2469
	rtsize = list_length(estate->es_range_table);
2470 2471 2472 2473 2474 2475

	epq->estate = epqstate = CreateExecutorState();

	oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);

	/*
B
Bruce Momjian 已提交
2476 2477 2478 2479
	 * The epqstates share the top query's copy of unchanging state such as
	 * the snapshot, rangetable, result-rel info, and external Param info.
	 * They need their own copies of local state, including a tuple table,
	 * es_param_exec_vals, etc.
2480 2481 2482
	 */
	epqstate->es_direction = ForwardScanDirection;
	epqstate->es_snapshot = estate->es_snapshot;
2483
	epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2484
	epqstate->es_range_table = estate->es_range_table;
2485
	epqstate->es_output_cid = estate->es_output_cid;
2486 2487 2488 2489
	epqstate->es_result_relations = estate->es_result_relations;
	epqstate->es_num_result_relations = estate->es_num_result_relations;
	epqstate->es_result_relation_info = estate->es_result_relation_info;
	epqstate->es_junkFilter = estate->es_junkFilter;
2490
	/* es_trig_target_relations must NOT be copied */
2491
	epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2492
	epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2493
	epqstate->es_param_list_info = estate->es_param_list_info;
2494
	if (estate->es_plannedstmt->nParamExec > 0)
2495
		epqstate->es_param_exec_vals = (ParamExecData *)
2496
			palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2497
	epqstate->es_rowMarks = estate->es_rowMarks;
2498
	epqstate->es_instrument = estate->es_instrument;
2499 2500
	epqstate->es_select_into = estate->es_select_into;
	epqstate->es_into_oids = estate->es_into_oids;
2501
	epqstate->es_plannedstmt = estate->es_plannedstmt;
B
Bruce Momjian 已提交
2502

2503
	/*
B
Bruce Momjian 已提交
2504 2505 2506
	 * Each epqstate must have its own es_evTupleNull state, but all the stack
	 * entries share es_evTuple state.	This allows sub-rechecks to inherit
	 * the value being examined by an outer recheck.
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
	 */
	epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
	if (priorepq == NULL)
		/* first PQ stack entry */
		epqstate->es_evTuple = (HeapTuple *)
			palloc0(rtsize * sizeof(HeapTuple));
	else
		/* later stack entries share the same storage */
		epqstate->es_evTuple = priorepq->estate->es_evTuple;

2517 2518 2519
	/*
	 * Create sub-tuple-table; we needn't redo the CountSlots work though.
	 */
2520 2521 2522
	epqstate->es_tupleTable =
		ExecCreateTupleTable(estate->es_tupleTable->size);

2523
	/*
B
Bruce Momjian 已提交
2524 2525
	 * Initialize private state information for each SubPlan.  We must do this
	 * before running ExecInitNode on the main query tree, since
2526 2527 2528 2529 2530
	 * ExecInitSubPlan expects to be able to find these entries.
	 */
	Assert(epqstate->es_subplanstates == NIL);
	foreach(l, estate->es_plannedstmt->subplans)
	{
B
Bruce Momjian 已提交
2531 2532
		Plan	   *subplan = (Plan *) lfirst(l);
		PlanState  *subplanstate;
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544

		subplanstate = ExecInitNode(subplan, epqstate, 0);

		epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
											 subplanstate);
	}

	/*
	 * 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.
	 */
2545
	epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2546 2547 2548 2549 2550 2551 2552 2553 2554

	MemoryContextSwitchTo(oldcontext);
}

/*
 * End execution of one level of PlanQual.
 *
 * This is a cut-down version of ExecutorEnd(); basically we want to do most
 * of the normal cleanup, but *not* close result relations (which we are
B
Bruce Momjian 已提交
2555
 * just sharing from the outer query).	We do, however, have to close any
2556
 * trigger target relations that got opened, since those are not shared.
2557 2558 2559 2560 2561 2562
 */
static void
EvalPlanQualStop(evalPlanQual *epq)
{
	EState	   *epqstate = epq->estate;
	MemoryContext oldcontext;
2563
	ListCell   *l;
2564 2565 2566 2567 2568

	oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);

	ExecEndNode(epq->planstate);

2569 2570
	foreach(l, epqstate->es_subplanstates)
	{
B
Bruce Momjian 已提交
2571
		PlanState  *subplanstate = (PlanState *) lfirst(l);
2572 2573 2574 2575

		ExecEndNode(subplanstate);
	}

2576 2577 2578 2579 2580 2581 2582
	ExecDropTupleTable(epqstate->es_tupleTable, true);
	epqstate->es_tupleTable = NULL;

	if (epqstate->es_evTuple[epq->rti - 1] != NULL)
	{
		heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
		epqstate->es_evTuple[epq->rti - 1] = NULL;
2583
	}
2584

2585 2586 2587 2588 2589 2590 2591 2592 2593
	foreach(l, epqstate->es_trig_target_relations)
	{
		ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);

		/* Close indices and then the relation itself */
		ExecCloseIndices(resultRelInfo);
		heap_close(resultRelInfo->ri_RelationDesc, NoLock);
	}

2594 2595 2596 2597 2598 2599
	MemoryContextSwitchTo(oldcontext);

	FreeExecutorState(epqstate);

	epq->estate = NULL;
	epq->planstate = NULL;
2600
}
2601

2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
/*
 * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
 *
 * Ordinarily this is just the one mentioned in the QueryDesc, but if we
 * are looking at a row returned by the EvalPlanQual machinery, we need
 * to look at the subsidiary state instead.
 */
PlanState *
ExecGetActivePlanTree(QueryDesc *queryDesc)
{
	EState	   *estate = queryDesc->estate;

	if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
		return estate->es_evalPlanQual->planstate;
	else
		return queryDesc->planstate;
}

2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646

/*
 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
 *
 * We implement SELECT INTO by diverting SELECT's normal output with
 * a specialized DestReceiver type.
 *
 * TODO: remove some of the INTO-specific cruft from EState, and keep
 * it in the DestReceiver instead.
 */

typedef struct
{
	DestReceiver pub;			/* publicly-known function pointers */
	EState	   *estate;			/* EState we are working with */
} DR_intorel;

/*
 * OpenIntoRel --- actually create the SELECT INTO target relation
 *
 * This also replaces QueryDesc->dest with the special DestReceiver for
 * SELECT INTO.  We assume that the correct result tuple type has already
 * been placed in queryDesc->tupDesc.
 */
static void
OpenIntoRel(QueryDesc *queryDesc)
{
2647
	IntoClause *into = queryDesc->plannedstmt->intoClause;
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
	EState	   *estate = queryDesc->estate;
	Relation	intoRelationDesc;
	char	   *intoName;
	Oid			namespaceId;
	Oid			tablespaceId;
	Datum		reloptions;
	AclResult	aclresult;
	Oid			intoRelationId;
	TupleDesc	tupdesc;
	DR_intorel *myState;

2659 2660
	Assert(into);

2661 2662 2663 2664 2665
	/*
	 * XXX This code needs to be kept in sync with DefineRelation().
	 * Maybe we should try to use that function instead.
	 */

2666 2667 2668
	/*
	 * Check consistency of arguments
	 */
2669
	if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2670 2671 2672 2673
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
				 errmsg("ON COMMIT can only be used on temporary tables")));

2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
	/*
	 * Security check: disallow creating temp tables from security-restricted
	 * code.  This is needed because calling code might not expect untrusted
	 * tables to appear in pg_temp at the front of its search path.
	 */
	if (into->rel->istemp && InSecurityRestrictedOperation())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("cannot create temporary table within security-restricted operation")));

2684 2685 2686
	/*
	 * Find namespace to create in, check its permissions
	 */
2687 2688
	intoName = into->rel->relname;
	namespaceId = RangeVarGetCreationNamespace(into->rel);
2689 2690 2691 2692 2693 2694 2695 2696

	aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
									  ACL_CREATE);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
					   get_namespace_name(namespaceId));

	/*
2697
	 * Select tablespace to use.  If not specified, use default tablespace
2698 2699
	 * (which may in turn default to database's default).
	 */
2700
	if (into->tableSpaceName)
2701
	{
2702
		tablespaceId = get_tablespace_oid(into->tableSpaceName);
2703 2704 2705 2706
		if (!OidIsValid(tablespaceId))
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_OBJECT),
					 errmsg("tablespace \"%s\" does not exist",
2707
							into->tableSpaceName)));
B
Bruce Momjian 已提交
2708 2709
	}
	else
2710
	{
2711
		tablespaceId = GetDefaultTablespace(into->rel->istemp);
2712 2713 2714 2715
		/* note InvalidOid is OK in this case */
	}

	/* Check permissions except when using the database's default space */
2716
	if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
	{
		AclResult	aclresult;

		aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
										   ACL_CREATE);

		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
						   get_tablespace_name(tablespaceId));
	}

	/* Parse and validate any reloptions */
	reloptions = transformRelOptions((Datum) 0,
2730
									 into->options,
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
									 true,
									 false);
	(void) heap_reloptions(RELKIND_RELATION, reloptions, true);

	/* have to copy the actual tupdesc to get rid of any constraints */
	tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);

	/* Now we can actually create the new relation */
	intoRelationId = heap_create_with_catalog(intoName,
											  namespaceId,
											  tablespaceId,
											  InvalidOid,
											  GetUserId(),
											  tupdesc,
											  RELKIND_RELATION,
											  false,
											  true,
											  0,
2749
											  into->onCommit,
2750 2751 2752 2753 2754 2755
											  reloptions,
											  allowSystemTableMods);

	FreeTupleDesc(tupdesc);

	/*
B
Bruce Momjian 已提交
2756 2757
	 * Advance command counter so that the newly-created relation's catalog
	 * tuples will be visible to heap_open.
2758 2759 2760 2761 2762
	 */
	CommandCounterIncrement();

	/*
	 * If necessary, create a TOAST table for the INTO relation. Note that
B
Bruce Momjian 已提交
2763 2764
	 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
	 * the TOAST table will be visible for insertion.
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
	 */
	AlterTableCreateToastTable(intoRelationId);

	/*
	 * And open the constructed table for writing.
	 */
	intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);

	/* use_wal off requires rd_targblock be initially invalid */
	Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);

	/*
	 * We can skip WAL-logging the insertions, unless PITR is in use.
	 */
	estate->es_into_relation_use_wal = XLogArchivingActive();
	estate->es_into_relation_descriptor = intoRelationDesc;

	/*
	 * Now replace the query's DestReceiver with one for SELECT INTO
	 */
	queryDesc->dest = CreateDestReceiver(DestIntoRel, NULL);
	myState = (DR_intorel *) queryDesc->dest;
	Assert(myState->pub.mydest == DestIntoRel);
	myState->estate = estate;
}

/*
 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
 */
static void
CloseIntoRel(QueryDesc *queryDesc)
{
	EState	   *estate = queryDesc->estate;

	/* OpenIntoRel might never have gotten called */
	if (estate->es_into_relation_descriptor)
	{
2802 2803
		/* If we skipped using WAL, must heap_sync before commit */
		if (!estate->es_into_relation_use_wal)
2804
			heap_sync(estate->es_into_relation_descriptor);
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858

		/* close rel, but keep lock until commit */
		heap_close(estate->es_into_relation_descriptor, NoLock);

		estate->es_into_relation_descriptor = NULL;
	}
}

/*
 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
 *
 * Since CreateDestReceiver doesn't accept the parameters we'd need,
 * we just leave the private fields empty here.  OpenIntoRel will
 * fill them in.
 */
DestReceiver *
CreateIntoRelDestReceiver(void)
{
	DR_intorel *self = (DR_intorel *) palloc(sizeof(DR_intorel));

	self->pub.receiveSlot = intorel_receive;
	self->pub.rStartup = intorel_startup;
	self->pub.rShutdown = intorel_shutdown;
	self->pub.rDestroy = intorel_destroy;
	self->pub.mydest = DestIntoRel;

	self->estate = NULL;

	return (DestReceiver *) self;
}

/*
 * intorel_startup --- executor startup
 */
static void
intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
{
	/* no-op */
}

/*
 * intorel_receive --- receive one tuple
 */
static void
intorel_receive(TupleTableSlot *slot, DestReceiver *self)
{
	DR_intorel *myState = (DR_intorel *) self;
	EState	   *estate = myState->estate;
	HeapTuple	tuple;

	tuple = ExecCopySlotTuple(slot);

	heap_insert(estate->es_into_relation_descriptor,
				tuple,
2859
				estate->es_output_cid,
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
				estate->es_into_relation_use_wal,
				false);			/* never any point in using FSM */

	/* We know this is a newly created relation, so there are no indexes */

	heap_freetuple(tuple);

	IncrAppended();
}

/*
 * intorel_shutdown --- executor end
 */
static void
intorel_shutdown(DestReceiver *self)
{
	/* no-op */
}

/*
 * intorel_destroy --- release DestReceiver object
 */
static void
intorel_destroy(DestReceiver *self)
{
	pfree(self);
}