]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
Modify processing of DECLARE CURSOR and EXPLAIN so that they can resolve the
[postgresql] / src / backend / executor / execMain.c
1 /*-------------------------------------------------------------------------
2  *
3  * execMain.c
4  *        top level executor interface routines
5  *
6  * INTERFACE ROUTINES
7  *      ExecutorStart()
8  *      ExecutorRun()
9  *      ExecutorEnd()
10  *
11  *      The old ExecutorMain() has been replaced by ExecutorStart(),
12  *      ExecutorRun() and ExecutorEnd()
13  *
14  *      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  *      query plan and ExecutorEnd() should always be called at the end of
19  *      execution of a plan.
20  *
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-2007, PostgreSQL Global Development Group
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.293 2007/04/27 22:05:47 tgl Exp $
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/transam.h"
38 #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"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "executor/nodeSubplan.h"
47 #include "miscadmin.h"
48 #include "optimizer/clauses.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parsetree.h"
51 #include "storage/smgr.h"
52 #include "utils/acl.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55
56
57 typedef struct evalPlanQual
58 {
59         Index           rti;
60         EState     *estate;
61         PlanState  *planstate;
62         struct evalPlanQual *next;      /* stack of active PlanQual plans */
63         struct evalPlanQual *free;      /* list of free PlanQual plans */
64 } evalPlanQual;
65
66 /* decls for local routines only used within this module */
67 static void InitPlan(QueryDesc *queryDesc, int eflags);
68 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
69                                   Index resultRelationIndex,
70                                   List *rangeTable,
71                                   CmdType operation,
72                                   bool doInstrument);
73 static void ExecEndPlan(PlanState *planstate, EState *estate);
74 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
75                         CmdType operation,
76                         long numberTuples,
77                         ScanDirection direction,
78                         DestReceiver *dest);
79 static void ExecSelect(TupleTableSlot *slot,
80                    DestReceiver *dest, EState *estate);
81 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
82                    TupleTableSlot *planSlot,
83                    DestReceiver *dest, EState *estate);
84 static void ExecDelete(ItemPointer tupleid,
85                    TupleTableSlot *planSlot,
86                    DestReceiver *dest, EState *estate);
87 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
88                    TupleTableSlot *planSlot,
89                    DestReceiver *dest, EState *estate);
90 static void ExecProcessReturning(ProjectionInfo *projectReturning,
91                                          TupleTableSlot *tupleSlot,
92                                          TupleTableSlot *planSlot,
93                                          DestReceiver *dest);
94 static TupleTableSlot *EvalPlanQualNext(EState *estate);
95 static void EndEvalPlanQual(EState *estate);
96 static void ExecCheckRTPerms(List *rangeTable);
97 static void ExecCheckRTEPerms(RangeTblEntry *rte);
98 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
99 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
100                                   evalPlanQual *priorepq);
101 static void EvalPlanQualStop(evalPlanQual *epq);
102 static void OpenIntoRel(QueryDesc *queryDesc);
103 static void CloseIntoRel(QueryDesc *queryDesc);
104 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
105 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
106 static void intorel_shutdown(DestReceiver *self);
107 static void intorel_destroy(DestReceiver *self);
108
109 /* end of local decls */
110
111
112 /* ----------------------------------------------------------------
113  *              ExecutorStart
114  *
115  *              This routine must be called at the beginning of any execution of any
116  *              query plan
117  *
118  * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
119  * clear why we bother to separate the two functions, but...).  The tupDesc
120  * field of the QueryDesc is filled in to describe the tuples that will be
121  * returned, and the internal fields (estate and planstate) are set up.
122  *
123  * eflags contains flag bits as described in executor.h.
124  *
125  * NB: the CurrentMemoryContext when this is called will become the parent
126  * of the per-query context used for this Executor invocation.
127  * ----------------------------------------------------------------
128  */
129 void
130 ExecutorStart(QueryDesc *queryDesc, int eflags)
131 {
132         EState     *estate;
133         MemoryContext oldcontext;
134
135         /* sanity checks: queryDesc must not be started already */
136         Assert(queryDesc != NULL);
137         Assert(queryDesc->estate == NULL);
138
139         /*
140          * If the transaction is read-only, we need to check if any writes are
141          * planned to non-temporary tables.  EXPLAIN is considered read-only.
142          */
143         if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
144                 ExecCheckXactReadOnly(queryDesc->plannedstmt);
145
146         /*
147          * Build EState, switch into per-query memory context for startup.
148          */
149         estate = CreateExecutorState();
150         queryDesc->estate = estate;
151
152         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
153
154         /*
155          * Fill in parameters, if any, from queryDesc
156          */
157         estate->es_param_list_info = queryDesc->params;
158
159         if (queryDesc->plannedstmt->nParamExec > 0)
160                 estate->es_param_exec_vals = (ParamExecData *)
161                         palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
162
163         /*
164          * Copy other important information into the EState
165          */
166         estate->es_snapshot = queryDesc->snapshot;
167         estate->es_crosscheck_snapshot = queryDesc->crosscheck_snapshot;
168         estate->es_instrument = queryDesc->doInstrument;
169
170         /*
171          * Initialize the plan state tree
172          */
173         InitPlan(queryDesc, eflags);
174
175         MemoryContextSwitchTo(oldcontext);
176 }
177
178 /* ----------------------------------------------------------------
179  *              ExecutorRun
180  *
181  *              This is the main routine of the executor module. It accepts
182  *              the query descriptor from the traffic cop and executes the
183  *              query plan.
184  *
185  *              ExecutorStart must have been called already.
186  *
187  *              If direction is NoMovementScanDirection then nothing is done
188  *              except to start up/shut down the destination.  Otherwise,
189  *              we retrieve up to 'count' tuples in the specified direction.
190  *
191  *              Note: count = 0 is interpreted as no portal limit, i.e., run to
192  *              completion.
193  *
194  * ----------------------------------------------------------------
195  */
196 TupleTableSlot *
197 ExecutorRun(QueryDesc *queryDesc,
198                         ScanDirection direction, long count)
199 {
200         EState     *estate;
201         CmdType         operation;
202         DestReceiver *dest;
203         bool            sendTuples;
204         TupleTableSlot *result;
205         MemoryContext oldcontext;
206
207         /* sanity checks */
208         Assert(queryDesc != NULL);
209
210         estate = queryDesc->estate;
211
212         Assert(estate != NULL);
213
214         /*
215          * Switch into per-query memory context
216          */
217         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
218
219         /*
220          * extract information from the query descriptor and the query feature.
221          */
222         operation = queryDesc->operation;
223         dest = queryDesc->dest;
224
225         /*
226          * startup tuple receiver, if we will be emitting tuples
227          */
228         estate->es_processed = 0;
229         estate->es_lastoid = InvalidOid;
230
231         sendTuples = (operation == CMD_SELECT ||
232                                   queryDesc->plannedstmt->returningLists);
233
234         if (sendTuples)
235                 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
236
237         /*
238          * run plan
239          */
240         if (ScanDirectionIsNoMovement(direction))
241                 result = NULL;
242         else
243                 result = ExecutePlan(estate,
244                                                          queryDesc->planstate,
245                                                          operation,
246                                                          count,
247                                                          direction,
248                                                          dest);
249
250         /*
251          * shutdown tuple receiver, if we started it
252          */
253         if (sendTuples)
254                 (*dest->rShutdown) (dest);
255
256         MemoryContextSwitchTo(oldcontext);
257
258         return result;
259 }
260
261 /* ----------------------------------------------------------------
262  *              ExecutorEnd
263  *
264  *              This routine must be called at the end of execution of any
265  *              query plan
266  * ----------------------------------------------------------------
267  */
268 void
269 ExecutorEnd(QueryDesc *queryDesc)
270 {
271         EState     *estate;
272         MemoryContext oldcontext;
273
274         /* sanity checks */
275         Assert(queryDesc != NULL);
276
277         estate = queryDesc->estate;
278
279         Assert(estate != NULL);
280
281         /*
282          * Switch into per-query memory context to run ExecEndPlan
283          */
284         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
285
286         ExecEndPlan(queryDesc->planstate, estate);
287
288         /*
289          * Close the SELECT INTO relation if any
290          */
291         if (estate->es_select_into)
292                 CloseIntoRel(queryDesc);
293
294         /*
295          * Must switch out of context before destroying it
296          */
297         MemoryContextSwitchTo(oldcontext);
298
299         /*
300          * Release EState and per-query memory context.  This should release
301          * everything the executor has allocated.
302          */
303         FreeExecutorState(estate);
304
305         /* Reset queryDesc fields that no longer point to anything */
306         queryDesc->tupDesc = NULL;
307         queryDesc->estate = NULL;
308         queryDesc->planstate = NULL;
309 }
310
311 /* ----------------------------------------------------------------
312  *              ExecutorRewind
313  *
314  *              This routine may be called on an open queryDesc to rewind it
315  *              to the start.
316  * ----------------------------------------------------------------
317  */
318 void
319 ExecutorRewind(QueryDesc *queryDesc)
320 {
321         EState     *estate;
322         MemoryContext oldcontext;
323
324         /* sanity checks */
325         Assert(queryDesc != NULL);
326
327         estate = queryDesc->estate;
328
329         Assert(estate != NULL);
330
331         /* It's probably not sensible to rescan updating queries */
332         Assert(queryDesc->operation == CMD_SELECT);
333
334         /*
335          * Switch into per-query memory context
336          */
337         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
338
339         /*
340          * rescan plan
341          */
342         ExecReScan(queryDesc->planstate, NULL);
343
344         MemoryContextSwitchTo(oldcontext);
345 }
346
347
348 /*
349  * ExecCheckRTPerms
350  *              Check access permissions for all relations listed in a range table.
351  */
352 static void
353 ExecCheckRTPerms(List *rangeTable)
354 {
355         ListCell   *l;
356
357         foreach(l, rangeTable)
358         {
359                 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
360         }
361 }
362
363 /*
364  * ExecCheckRTEPerms
365  *              Check access permissions for a single RTE.
366  */
367 static void
368 ExecCheckRTEPerms(RangeTblEntry *rte)
369 {
370         AclMode         requiredPerms;
371         Oid                     relOid;
372         Oid                     userid;
373
374         /*
375          * Only plain-relation RTEs need to be checked here.  Function RTEs are
376          * checked by init_fcache when the function is prepared for execution.
377          * Join, subquery, and special RTEs need no checks.
378          */
379         if (rte->rtekind != RTE_RELATION)
380                 return;
381
382         /*
383          * No work if requiredPerms is empty.
384          */
385         requiredPerms = rte->requiredPerms;
386         if (requiredPerms == 0)
387                 return;
388
389         relOid = rte->relid;
390
391         /*
392          * userid to check as: current user unless we have a setuid indication.
393          *
394          * Note: GetUserId() is presently fast enough that there's no harm in
395          * calling it separately for each RTE.  If that stops being true, we could
396          * call it once in ExecCheckRTPerms and pass the userid down from there.
397          * But for now, no need for the extra clutter.
398          */
399         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
400
401         /*
402          * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
403          */
404         if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
405                 != requiredPerms)
406                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
407                                            get_rel_name(relOid));
408 }
409
410 /*
411  * Check that the query does not imply any writes to non-temp tables.
412  */
413 static void
414 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
415 {
416         ListCell   *l;
417
418         /*
419          * CREATE TABLE AS or SELECT INTO?
420          *
421          * XXX should we allow this if the destination is temp?
422          */
423         if (plannedstmt->intoClause != NULL)
424                 goto fail;
425
426         /* Fail if write permissions are requested on any non-temp table */
427         foreach(l, plannedstmt->rtable)
428         {
429                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
430
431                 if (rte->rtekind != RTE_RELATION)
432                         continue;
433
434                 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
435                         continue;
436
437                 if (isTempNamespace(get_rel_namespace(rte->relid)))
438                         continue;
439
440                 goto fail;
441         }
442
443         return;
444
445 fail:
446         ereport(ERROR,
447                         (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
448                          errmsg("transaction is read-only")));
449 }
450
451
452 /* ----------------------------------------------------------------
453  *              InitPlan
454  *
455  *              Initializes the query plan: open files, allocate storage
456  *              and start up the rule manager
457  * ----------------------------------------------------------------
458  */
459 static void
460 InitPlan(QueryDesc *queryDesc, int eflags)
461 {
462         CmdType         operation = queryDesc->operation;
463         PlannedStmt *plannedstmt = queryDesc->plannedstmt;
464         Plan       *plan = plannedstmt->planTree;
465         List       *rangeTable = plannedstmt->rtable;
466         EState     *estate = queryDesc->estate;
467         PlanState  *planstate;
468         TupleDesc       tupType;
469         ListCell   *l;
470         int                     i;
471
472         /*
473          * Do permissions checks
474          */
475         ExecCheckRTPerms(rangeTable);
476
477         /*
478          * initialize the node's execution state
479          */
480         estate->es_range_table = rangeTable;
481
482         /*
483          * initialize result relation stuff
484          */
485         if (plannedstmt->resultRelations)
486         {
487                 List       *resultRelations = plannedstmt->resultRelations;
488                 int                     numResultRelations = list_length(resultRelations);
489                 ResultRelInfo *resultRelInfos;
490                 ResultRelInfo *resultRelInfo;
491
492                 resultRelInfos = (ResultRelInfo *)
493                         palloc(numResultRelations * sizeof(ResultRelInfo));
494                 resultRelInfo = resultRelInfos;
495                 foreach(l, resultRelations)
496                 {
497                         initResultRelInfo(resultRelInfo,
498                                                           lfirst_int(l),
499                                                           rangeTable,
500                                                           operation,
501                                                           estate->es_instrument);
502                         resultRelInfo++;
503                 }
504                 estate->es_result_relations = resultRelInfos;
505                 estate->es_num_result_relations = numResultRelations;
506                 /* Initialize to first or only result rel */
507                 estate->es_result_relation_info = resultRelInfos;
508         }
509         else
510         {
511                 /*
512                  * if no result relation, then set state appropriately
513                  */
514                 estate->es_result_relations = NULL;
515                 estate->es_num_result_relations = 0;
516                 estate->es_result_relation_info = NULL;
517         }
518
519         /*
520          * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
521          * flag appropriately so that the plan tree will be initialized with the
522          * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
523          */
524         estate->es_select_into = false;
525         if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
526         {
527                 estate->es_select_into = true;
528                 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
529         }
530
531         /*
532          * Have to lock relations selected FOR UPDATE/FOR SHARE before we
533          * initialize the plan tree, else we'd be doing a lock upgrade.
534          * While we are at it, build the ExecRowMark list.
535          */
536         estate->es_rowMarks = NIL;
537         foreach(l, plannedstmt->rowMarks)
538         {
539                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
540                 Oid                     relid = getrelid(rc->rti, rangeTable);
541                 Relation        relation;
542                 ExecRowMark *erm;
543
544                 relation = heap_open(relid, RowShareLock);
545                 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
546                 erm->relation = relation;
547                 erm->rti = rc->rti;
548                 erm->forUpdate = rc->forUpdate;
549                 erm->noWait = rc->noWait;
550                 /* We'll set up ctidAttno below */
551                 erm->ctidAttNo = InvalidAttrNumber;
552                 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
553         }
554
555         /*
556          * Initialize the executor "tuple" table.  We need slots for all the plan
557          * nodes, plus possibly output slots for the junkfilter(s). At this point
558          * we aren't sure if we need junkfilters, so just add slots for them
559          * unconditionally.  Also, if it's not a SELECT, set up a slot for use for
560          * trigger output tuples.  Also, one for RETURNING-list evaluation.
561          */
562         {
563                 int                     nSlots;
564
565                 /* Slots for the main plan tree */
566                 nSlots = ExecCountSlotsNode(plan);
567                 /* Add slots for subplans and initplans */
568                 foreach(l, plannedstmt->subplans)
569                 {
570                         Plan   *subplan = (Plan *) lfirst(l);
571
572                         nSlots += ExecCountSlotsNode(subplan);
573                 }
574                 /* Add slots for junkfilter(s) */
575                 if (plannedstmt->resultRelations != NIL)
576                         nSlots += list_length(plannedstmt->resultRelations);
577                 else
578                         nSlots += 1;
579                 if (operation != CMD_SELECT)
580                         nSlots++;                       /* for es_trig_tuple_slot */
581                 if (plannedstmt->returningLists)
582                         nSlots++;                       /* for RETURNING projection */
583
584                 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
585
586                 if (operation != CMD_SELECT)
587                         estate->es_trig_tuple_slot =
588                                 ExecAllocTableSlot(estate->es_tupleTable);
589         }
590
591         /* mark EvalPlanQual not active */
592         estate->es_plannedstmt = plannedstmt;
593         estate->es_evalPlanQual = NULL;
594         estate->es_evTupleNull = NULL;
595         estate->es_evTuple = NULL;
596         estate->es_useEvalPlan = false;
597
598         /*
599          * Initialize private state information for each SubPlan.  We must do
600          * this before running ExecInitNode on the main query tree, since
601          * ExecInitSubPlan expects to be able to find these entries.
602          */
603         Assert(estate->es_subplanstates == NIL);
604         i = 1;                                          /* subplan indices count from 1 */
605         foreach(l, plannedstmt->subplans)
606         {
607                 Plan   *subplan = (Plan *) lfirst(l);
608                 PlanState *subplanstate;
609                 int             sp_eflags;
610
611                 /*
612                  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE.
613                  * If it is a parameterless subplan (not initplan), we suggest that it
614                  * be prepared to handle REWIND efficiently; otherwise there is no
615                  * need.
616                  */
617                 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
618                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
619                         sp_eflags |= EXEC_FLAG_REWIND;
620
621                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
622
623                 estate->es_subplanstates = lappend(estate->es_subplanstates,
624                                                                                    subplanstate);
625
626                 i++;
627         }
628
629         /*
630          * Initialize the private state information for all the nodes in the query
631          * tree.  This opens files, allocates storage and leaves us ready to start
632          * processing tuples.
633          */
634         planstate = ExecInitNode(plan, estate, eflags);
635
636         /*
637          * Get the tuple descriptor describing the type of tuples to return. (this
638          * is especially important if we are creating a relation with "SELECT
639          * INTO")
640          */
641         tupType = ExecGetResultType(planstate);
642
643         /*
644          * Initialize the junk filter if needed.  SELECT and INSERT queries need a
645          * filter if there are any junk attrs in the tlist.  INSERT and SELECT
646          * INTO also need a filter if the plan may return raw disk tuples (else
647          * heap_insert will be scribbling on the source relation!). UPDATE and
648          * DELETE always need a filter, since there's always a junk 'ctid'
649          * attribute present --- no need to look first.
650          */
651         {
652                 bool            junk_filter_needed = false;
653                 ListCell   *tlist;
654
655                 switch (operation)
656                 {
657                         case CMD_SELECT:
658                         case CMD_INSERT:
659                                 foreach(tlist, plan->targetlist)
660                                 {
661                                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
662
663                                         if (tle->resjunk)
664                                         {
665                                                 junk_filter_needed = true;
666                                                 break;
667                                         }
668                                 }
669                                 if (!junk_filter_needed &&
670                                         (operation == CMD_INSERT || estate->es_select_into) &&
671                                         ExecMayReturnRawTuples(planstate))
672                                         junk_filter_needed = true;
673                                 break;
674                         case CMD_UPDATE:
675                         case CMD_DELETE:
676                                 junk_filter_needed = true;
677                                 break;
678                         default:
679                                 break;
680                 }
681
682                 if (junk_filter_needed)
683                 {
684                         /*
685                          * If there are multiple result relations, each one needs its own
686                          * junk filter.  Note this is only possible for UPDATE/DELETE, so
687                          * we can't be fooled by some needing a filter and some not.
688                          */
689                         if (list_length(plannedstmt->resultRelations) > 1)
690                         {
691                                 PlanState **appendplans;
692                                 int                     as_nplans;
693                                 ResultRelInfo *resultRelInfo;
694
695                                 /* Top plan had better be an Append here. */
696                                 Assert(IsA(plan, Append));
697                                 Assert(((Append *) plan)->isTarget);
698                                 Assert(IsA(planstate, AppendState));
699                                 appendplans = ((AppendState *) planstate)->appendplans;
700                                 as_nplans = ((AppendState *) planstate)->as_nplans;
701                                 Assert(as_nplans == estate->es_num_result_relations);
702                                 resultRelInfo = estate->es_result_relations;
703                                 for (i = 0; i < as_nplans; i++)
704                                 {
705                                         PlanState  *subplan = appendplans[i];
706                                         JunkFilter *j;
707
708                                         j = ExecInitJunkFilter(subplan->plan->targetlist,
709                                                         resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
710                                                                   ExecAllocTableSlot(estate->es_tupleTable));
711                                         /*
712                                          * Since it must be UPDATE/DELETE, there had better be
713                                          * a "ctid" junk attribute in the tlist ... but ctid could
714                                          * be at a different resno for each result relation.
715                                          * We look up the ctid resnos now and save them in the
716                                          * junkfilters.
717                                          */
718                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
719                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
720                                                 elog(ERROR, "could not find junk ctid column");
721                                         resultRelInfo->ri_junkFilter = j;
722                                         resultRelInfo++;
723                                 }
724
725                                 /*
726                                  * Set active junkfilter too; at this point ExecInitAppend has
727                                  * already selected an active result relation...
728                                  */
729                                 estate->es_junkFilter =
730                                         estate->es_result_relation_info->ri_junkFilter;
731                         }
732                         else
733                         {
734                                 /* Normal case with just one JunkFilter */
735                                 JunkFilter *j;
736
737                                 j = ExecInitJunkFilter(planstate->plan->targetlist,
738                                                                            tupType->tdhasoid,
739                                                                   ExecAllocTableSlot(estate->es_tupleTable));
740                                 estate->es_junkFilter = j;
741                                 if (estate->es_result_relation_info)
742                                         estate->es_result_relation_info->ri_junkFilter = j;
743
744                                 if (operation == CMD_SELECT)
745                                 {
746                                         /* For SELECT, want to return the cleaned tuple type */
747                                         tupType = j->jf_cleanTupType;
748                                         /* For SELECT FOR UPDATE/SHARE, find the ctid attrs now */
749                                         foreach(l, estate->es_rowMarks)
750                                         {
751                                                 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
752                                                 char            resname[32];
753
754                                                 snprintf(resname, sizeof(resname), "ctid%u", erm->rti);
755                                                 erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
756                                                 if (!AttributeNumberIsValid(erm->ctidAttNo))
757                                                         elog(ERROR, "could not find junk \"%s\" column",
758                                                                  resname);
759                                         }
760                                 }
761                                 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
762                                 {
763                                         /* For UPDATE/DELETE, find the ctid junk attr now */
764                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
765                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
766                                                 elog(ERROR, "could not find junk ctid column");
767                                 }
768                         }
769                 }
770                 else
771                         estate->es_junkFilter = NULL;
772         }
773
774         /*
775          * Initialize RETURNING projections if needed.
776          */
777         if (plannedstmt->returningLists)
778         {
779                 TupleTableSlot *slot;
780                 ExprContext *econtext;
781                 ResultRelInfo *resultRelInfo;
782
783                 /*
784                  * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
785                  * We assume all the sublists will generate the same output tupdesc.
786                  */
787                 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
788                                                                  false);
789
790                 /* Set up a slot for the output of the RETURNING projection(s) */
791                 slot = ExecAllocTableSlot(estate->es_tupleTable);
792                 ExecSetSlotDescriptor(slot, tupType);
793                 /* Need an econtext too */
794                 econtext = CreateExprContext(estate);
795
796                 /*
797                  * Build a projection for each result rel.      Note that any SubPlans in
798                  * the RETURNING lists get attached to the topmost plan node.
799                  */
800                 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
801                 resultRelInfo = estate->es_result_relations;
802                 foreach(l, plannedstmt->returningLists)
803                 {
804                         List       *rlist = (List *) lfirst(l);
805                         List       *rliststate;
806
807                         rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
808                         resultRelInfo->ri_projectReturning =
809                                 ExecBuildProjectionInfo(rliststate, econtext, slot,
810                                                                            resultRelInfo->ri_RelationDesc->rd_att);
811                         resultRelInfo++;
812                 }
813         }
814
815         queryDesc->tupDesc = tupType;
816         queryDesc->planstate = planstate;
817
818         /*
819          * If doing SELECT INTO, initialize the "into" relation.  We must wait
820          * till now so we have the "clean" result tuple type to create the new
821          * table from.
822          *
823          * If EXPLAIN, skip creating the "into" relation.
824          */
825         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
826                 OpenIntoRel(queryDesc);
827 }
828
829 /*
830  * Initialize ResultRelInfo data for one result relation
831  */
832 static void
833 initResultRelInfo(ResultRelInfo *resultRelInfo,
834                                   Index resultRelationIndex,
835                                   List *rangeTable,
836                                   CmdType operation,
837                                   bool doInstrument)
838 {
839         Oid                     resultRelationOid;
840         Relation        resultRelationDesc;
841
842         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
843         resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
844
845         switch (resultRelationDesc->rd_rel->relkind)
846         {
847                 case RELKIND_SEQUENCE:
848                         ereport(ERROR,
849                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
850                                          errmsg("cannot change sequence \"%s\"",
851                                                         RelationGetRelationName(resultRelationDesc))));
852                         break;
853                 case RELKIND_TOASTVALUE:
854                         ereport(ERROR,
855                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
856                                          errmsg("cannot change TOAST relation \"%s\"",
857                                                         RelationGetRelationName(resultRelationDesc))));
858                         break;
859                 case RELKIND_VIEW:
860                         ereport(ERROR,
861                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
862                                          errmsg("cannot change view \"%s\"",
863                                                         RelationGetRelationName(resultRelationDesc))));
864                         break;
865         }
866
867         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
868         resultRelInfo->type = T_ResultRelInfo;
869         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
870         resultRelInfo->ri_RelationDesc = resultRelationDesc;
871         resultRelInfo->ri_NumIndices = 0;
872         resultRelInfo->ri_IndexRelationDescs = NULL;
873         resultRelInfo->ri_IndexRelationInfo = NULL;
874         /* make a copy so as not to depend on relcache info not changing... */
875         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
876         if (resultRelInfo->ri_TrigDesc)
877         {
878                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
879
880                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
881                         palloc0(n * sizeof(FmgrInfo));
882                 if (doInstrument)
883                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
884                 else
885                         resultRelInfo->ri_TrigInstrument = NULL;
886         }
887         else
888         {
889                 resultRelInfo->ri_TrigFunctions = NULL;
890                 resultRelInfo->ri_TrigInstrument = NULL;
891         }
892         resultRelInfo->ri_ConstraintExprs = NULL;
893         resultRelInfo->ri_junkFilter = NULL;
894         resultRelInfo->ri_projectReturning = NULL;
895
896         /*
897          * If there are indices on the result relation, open them and save
898          * descriptors in the result relation info, so that we can add new index
899          * entries for the tuples we add/update.  We need not do this for a
900          * DELETE, however, since deletion doesn't affect indexes.
901          */
902         if (resultRelationDesc->rd_rel->relhasindex &&
903                 operation != CMD_DELETE)
904                 ExecOpenIndices(resultRelInfo);
905 }
906
907 /*
908  *              ExecContextForcesOids
909  *
910  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
911  * we need to ensure that result tuples have space for an OID iff they are
912  * going to be stored into a relation that has OIDs.  In other contexts
913  * we are free to choose whether to leave space for OIDs in result tuples
914  * (we generally don't want to, but we do if a physical-tlist optimization
915  * is possible).  This routine checks the plan context and returns TRUE if the
916  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
917  * *hasoids is set to the required value.
918  *
919  * One reason this is ugly is that all plan nodes in the plan tree will emit
920  * tuples with space for an OID, though we really only need the topmost node
921  * to do so.  However, node types like Sort don't project new tuples but just
922  * return their inputs, and in those cases the requirement propagates down
923  * to the input node.  Eventually we might make this code smart enough to
924  * recognize how far down the requirement really goes, but for now we just
925  * make all plan nodes do the same thing if the top level forces the choice.
926  *
927  * We assume that estate->es_result_relation_info is already set up to
928  * describe the target relation.  Note that in an UPDATE that spans an
929  * inheritance tree, some of the target relations may have OIDs and some not.
930  * We have to make the decisions on a per-relation basis as we initialize
931  * each of the child plans of the topmost Append plan.
932  *
933  * SELECT INTO is even uglier, because we don't have the INTO relation's
934  * descriptor available when this code runs; we have to look aside at a
935  * flag set by InitPlan().
936  */
937 bool
938 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
939 {
940         if (planstate->state->es_select_into)
941         {
942                 *hasoids = planstate->state->es_into_oids;
943                 return true;
944         }
945         else
946         {
947                 ResultRelInfo *ri = planstate->state->es_result_relation_info;
948
949                 if (ri != NULL)
950                 {
951                         Relation        rel = ri->ri_RelationDesc;
952
953                         if (rel != NULL)
954                         {
955                                 *hasoids = rel->rd_rel->relhasoids;
956                                 return true;
957                         }
958                 }
959         }
960
961         return false;
962 }
963
964 /* ----------------------------------------------------------------
965  *              ExecEndPlan
966  *
967  *              Cleans up the query plan -- closes files and frees up storage
968  *
969  * NOTE: we are no longer very worried about freeing storage per se
970  * in this code; FreeExecutorState should be guaranteed to release all
971  * memory that needs to be released.  What we are worried about doing
972  * is closing relations and dropping buffer pins.  Thus, for example,
973  * tuple tables must be cleared or dropped to ensure pins are released.
974  * ----------------------------------------------------------------
975  */
976 static void
977 ExecEndPlan(PlanState *planstate, EState *estate)
978 {
979         ResultRelInfo *resultRelInfo;
980         int                     i;
981         ListCell   *l;
982
983         /*
984          * shut down any PlanQual processing we were doing
985          */
986         if (estate->es_evalPlanQual != NULL)
987                 EndEvalPlanQual(estate);
988
989         /*
990          * shut down the node-type-specific query processing
991          */
992         ExecEndNode(planstate);
993
994         /*
995          * for subplans too
996          */
997         foreach(l, estate->es_subplanstates)
998         {
999                 PlanState *subplanstate = (PlanState *) lfirst(l);
1000
1001                 ExecEndNode(subplanstate);
1002         }
1003
1004         /*
1005          * destroy the executor "tuple" table.
1006          */
1007         ExecDropTupleTable(estate->es_tupleTable, true);
1008         estate->es_tupleTable = NULL;
1009
1010         /*
1011          * close the result relation(s) if any, but hold locks until xact commit.
1012          */
1013         resultRelInfo = estate->es_result_relations;
1014         for (i = estate->es_num_result_relations; i > 0; i--)
1015         {
1016                 /* Close indices and then the relation itself */
1017                 ExecCloseIndices(resultRelInfo);
1018                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1019                 resultRelInfo++;
1020         }
1021
1022         /*
1023          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1024          */
1025         foreach(l, estate->es_rowMarks)
1026         {
1027                 ExecRowMark *erm = lfirst(l);
1028
1029                 heap_close(erm->relation, NoLock);
1030         }
1031 }
1032
1033 /* ----------------------------------------------------------------
1034  *              ExecutePlan
1035  *
1036  *              processes the query plan to retrieve 'numberTuples' tuples in the
1037  *              direction specified.
1038  *
1039  *              Retrieves all tuples if numberTuples is 0
1040  *
1041  *              result is either a slot containing the last tuple in the case
1042  *              of a SELECT or NULL otherwise.
1043  *
1044  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1045  * user can see it
1046  * ----------------------------------------------------------------
1047  */
1048 static TupleTableSlot *
1049 ExecutePlan(EState *estate,
1050                         PlanState *planstate,
1051                         CmdType operation,
1052                         long numberTuples,
1053                         ScanDirection direction,
1054                         DestReceiver *dest)
1055 {
1056         JunkFilter *junkfilter;
1057         TupleTableSlot *planSlot;
1058         TupleTableSlot *slot;
1059         ItemPointer tupleid = NULL;
1060         ItemPointerData tuple_ctid;
1061         long            current_tuple_count;
1062         TupleTableSlot *result;
1063
1064         /*
1065          * initialize local variables
1066          */
1067         current_tuple_count = 0;
1068         result = NULL;
1069
1070         /*
1071          * Set the direction.
1072          */
1073         estate->es_direction = direction;
1074
1075         /*
1076          * Process BEFORE EACH STATEMENT triggers
1077          */
1078         switch (operation)
1079         {
1080                 case CMD_UPDATE:
1081                         ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1082                         break;
1083                 case CMD_DELETE:
1084                         ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1085                         break;
1086                 case CMD_INSERT:
1087                         ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1088                         break;
1089                 default:
1090                         /* do nothing */
1091                         break;
1092         }
1093
1094         /*
1095          * Loop until we've processed the proper number of tuples from the plan.
1096          */
1097
1098         for (;;)
1099         {
1100                 /* Reset the per-output-tuple exprcontext */
1101                 ResetPerTupleExprContext(estate);
1102
1103                 /*
1104                  * Execute the plan and obtain a tuple
1105                  */
1106 lnext:  ;
1107                 if (estate->es_useEvalPlan)
1108                 {
1109                         planSlot = EvalPlanQualNext(estate);
1110                         if (TupIsNull(planSlot))
1111                                 planSlot = ExecProcNode(planstate);
1112                 }
1113                 else
1114                         planSlot = ExecProcNode(planstate);
1115
1116                 /*
1117                  * if the tuple is null, then we assume there is nothing more to
1118                  * process so we just return null...
1119                  */
1120                 if (TupIsNull(planSlot))
1121                 {
1122                         result = NULL;
1123                         break;
1124                 }
1125                 slot = planSlot;
1126
1127                 /*
1128                  * if we have a junk filter, then project a new tuple with the junk
1129                  * removed.
1130                  *
1131                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1132                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1133                  * because that tuple slot has the wrong descriptor.)
1134                  *
1135                  * Also, extract all the junk information we need.
1136                  */
1137                 if ((junkfilter = estate->es_junkFilter) != NULL)
1138                 {
1139                         Datum           datum;
1140                         bool            isNull;
1141
1142                         /*
1143                          * extract the 'ctid' junk attribute.
1144                          */
1145                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
1146                         {
1147                                 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1148                                                                                          &isNull);
1149                                 /* shouldn't ever get a null result... */
1150                                 if (isNull)
1151                                         elog(ERROR, "ctid is NULL");
1152
1153                                 tupleid = (ItemPointer) DatumGetPointer(datum);
1154                                 tuple_ctid = *tupleid;  /* make sure we don't free the ctid!! */
1155                                 tupleid = &tuple_ctid;
1156                         }
1157
1158                         /*
1159                          * Process any FOR UPDATE or FOR SHARE locking requested.
1160                          */
1161                         else if (estate->es_rowMarks != NIL)
1162                         {
1163                                 ListCell   *l;
1164
1165                 lmark:  ;
1166                                 foreach(l, estate->es_rowMarks)
1167                                 {
1168                                         ExecRowMark *erm = lfirst(l);
1169                                         HeapTupleData tuple;
1170                                         Buffer          buffer;
1171                                         ItemPointerData update_ctid;
1172                                         TransactionId update_xmax;
1173                                         TupleTableSlot *newSlot;
1174                                         LockTupleMode lockmode;
1175                                         HTSU_Result test;
1176
1177                                         datum = ExecGetJunkAttribute(slot,
1178                                                                                                  erm->ctidAttNo,
1179                                                                                                  &isNull);
1180                                         /* shouldn't ever get a null result... */
1181                                         if (isNull)
1182                                                 elog(ERROR, "ctid is NULL");
1183
1184                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1185
1186                                         if (erm->forUpdate)
1187                                                 lockmode = LockTupleExclusive;
1188                                         else
1189                                                 lockmode = LockTupleShared;
1190
1191                                         test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1192                                                                                    &update_ctid, &update_xmax,
1193                                                                                    estate->es_snapshot->curcid,
1194                                                                                    lockmode, erm->noWait);
1195                                         ReleaseBuffer(buffer);
1196                                         switch (test)
1197                                         {
1198                                                 case HeapTupleSelfUpdated:
1199                                                         /* treat it as deleted; do not process */
1200                                                         goto lnext;
1201
1202                                                 case HeapTupleMayBeUpdated:
1203                                                         break;
1204
1205                                                 case HeapTupleUpdated:
1206                                                         if (IsXactIsoLevelSerializable)
1207                                                                 ereport(ERROR,
1208                                                                  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1209                                                                   errmsg("could not serialize access due to concurrent update")));
1210                                                         if (!ItemPointerEquals(&update_ctid,
1211                                                                                                    &tuple.t_self))
1212                                                         {
1213                                                                 /* updated, so look at updated version */
1214                                                                 newSlot = EvalPlanQual(estate,
1215                                                                                                            erm->rti,
1216                                                                                                            &update_ctid,
1217                                                                                                            update_xmax,
1218                                                                                                 estate->es_snapshot->curcid);
1219                                                                 if (!TupIsNull(newSlot))
1220                                                                 {
1221                                                                         slot = planSlot = newSlot;
1222                                                                         estate->es_useEvalPlan = true;
1223                                                                         goto lmark;
1224                                                                 }
1225                                                         }
1226
1227                                                         /*
1228                                                          * if tuple was deleted or PlanQual failed for
1229                                                          * updated tuple - we must not return this tuple!
1230                                                          */
1231                                                         goto lnext;
1232
1233                                                 default:
1234                                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1235                                                                  test);
1236                                                         return NULL;
1237                                         }
1238                                 }
1239                         }
1240
1241                         /*
1242                          * Create a new "clean" tuple with all junk attributes removed. We
1243                          * don't need to do this for DELETE, however (there will in fact
1244                          * be no non-junk attributes in a DELETE!)
1245                          */
1246                         if (operation != CMD_DELETE)
1247                                 slot = ExecFilterJunk(junkfilter, slot);
1248                 }
1249
1250                 /*
1251                  * now that we have a tuple, do the appropriate thing with it.. either
1252                  * return it to the user, add it to a relation someplace, delete it
1253                  * from a relation, or modify some of its attributes.
1254                  */
1255                 switch (operation)
1256                 {
1257                         case CMD_SELECT:
1258                                 ExecSelect(slot, dest, estate);
1259                                 result = slot;
1260                                 break;
1261
1262                         case CMD_INSERT:
1263                                 ExecInsert(slot, tupleid, planSlot, dest, estate);
1264                                 result = NULL;
1265                                 break;
1266
1267                         case CMD_DELETE:
1268                                 ExecDelete(tupleid, planSlot, dest, estate);
1269                                 result = NULL;
1270                                 break;
1271
1272                         case CMD_UPDATE:
1273                                 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1274                                 result = NULL;
1275                                 break;
1276
1277                         default:
1278                                 elog(ERROR, "unrecognized operation code: %d",
1279                                          (int) operation);
1280                                 result = NULL;
1281                                 break;
1282                 }
1283
1284                 /*
1285                  * check our tuple count.. if we've processed the proper number then
1286                  * quit, else loop again and process more tuples.  Zero numberTuples
1287                  * means no limit.
1288                  */
1289                 current_tuple_count++;
1290                 if (numberTuples && numberTuples == current_tuple_count)
1291                         break;
1292         }
1293
1294         /*
1295          * Process AFTER EACH STATEMENT triggers
1296          */
1297         switch (operation)
1298         {
1299                 case CMD_UPDATE:
1300                         ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1301                         break;
1302                 case CMD_DELETE:
1303                         ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1304                         break;
1305                 case CMD_INSERT:
1306                         ExecASInsertTriggers(estate, estate->es_result_relation_info);
1307                         break;
1308                 default:
1309                         /* do nothing */
1310                         break;
1311         }
1312
1313         /*
1314          * here, result is either a slot containing a tuple in the case of a
1315          * SELECT or NULL otherwise.
1316          */
1317         return result;
1318 }
1319
1320 /* ----------------------------------------------------------------
1321  *              ExecSelect
1322  *
1323  *              SELECTs are easy.. we just pass the tuple to the appropriate
1324  *              output function.
1325  * ----------------------------------------------------------------
1326  */
1327 static void
1328 ExecSelect(TupleTableSlot *slot,
1329                    DestReceiver *dest,
1330                    EState *estate)
1331 {
1332         (*dest->receiveSlot) (slot, dest);
1333         IncrRetrieved();
1334         (estate->es_processed)++;
1335 }
1336
1337 /* ----------------------------------------------------------------
1338  *              ExecInsert
1339  *
1340  *              INSERTs are trickier.. we have to insert the tuple into
1341  *              the base relation and insert appropriate tuples into the
1342  *              index relations.
1343  * ----------------------------------------------------------------
1344  */
1345 static void
1346 ExecInsert(TupleTableSlot *slot,
1347                    ItemPointer tupleid,
1348                    TupleTableSlot *planSlot,
1349                    DestReceiver *dest,
1350                    EState *estate)
1351 {
1352         HeapTuple       tuple;
1353         ResultRelInfo *resultRelInfo;
1354         Relation        resultRelationDesc;
1355         Oid                     newId;
1356
1357         /*
1358          * get the heap tuple out of the tuple table slot, making sure we have a
1359          * writable copy
1360          */
1361         tuple = ExecMaterializeSlot(slot);
1362
1363         /*
1364          * get information on the (current) result relation
1365          */
1366         resultRelInfo = estate->es_result_relation_info;
1367         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1368
1369         /* BEFORE ROW INSERT Triggers */
1370         if (resultRelInfo->ri_TrigDesc &&
1371                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1372         {
1373                 HeapTuple       newtuple;
1374
1375                 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1376
1377                 if (newtuple == NULL)   /* "do nothing" */
1378                         return;
1379
1380                 if (newtuple != tuple)  /* modified by Trigger(s) */
1381                 {
1382                         /*
1383                          * Put the modified tuple into a slot for convenience of routines
1384                          * below.  We assume the tuple was allocated in per-tuple memory
1385                          * context, and therefore will go away by itself. The tuple table
1386                          * slot should not try to clear it.
1387                          */
1388                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1389
1390                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1391                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1392                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1393                         slot = newslot;
1394                         tuple = newtuple;
1395                 }
1396         }
1397
1398         /*
1399          * Check the constraints of the tuple
1400          */
1401         if (resultRelationDesc->rd_att->constr)
1402                 ExecConstraints(resultRelInfo, slot, estate);
1403
1404         /*
1405          * insert the tuple
1406          *
1407          * Note: heap_insert returns the tid (location) of the new tuple in the
1408          * t_self field.
1409          */
1410         newId = heap_insert(resultRelationDesc, tuple,
1411                                                 estate->es_snapshot->curcid,
1412                                                 true, true);
1413
1414         IncrAppended();
1415         (estate->es_processed)++;
1416         estate->es_lastoid = newId;
1417         setLastTid(&(tuple->t_self));
1418
1419         /*
1420          * insert index entries for tuple
1421          */
1422         if (resultRelInfo->ri_NumIndices > 0)
1423                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1424
1425         /* AFTER ROW INSERT Triggers */
1426         ExecARInsertTriggers(estate, resultRelInfo, tuple);
1427
1428         /* Process RETURNING if present */
1429         if (resultRelInfo->ri_projectReturning)
1430                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1431                                                          slot, planSlot, dest);
1432 }
1433
1434 /* ----------------------------------------------------------------
1435  *              ExecDelete
1436  *
1437  *              DELETE is like UPDATE, except that we delete the tuple and no
1438  *              index modifications are needed
1439  * ----------------------------------------------------------------
1440  */
1441 static void
1442 ExecDelete(ItemPointer tupleid,
1443                    TupleTableSlot *planSlot,
1444                    DestReceiver *dest,
1445                    EState *estate)
1446 {
1447         ResultRelInfo *resultRelInfo;
1448         Relation        resultRelationDesc;
1449         HTSU_Result result;
1450         ItemPointerData update_ctid;
1451         TransactionId update_xmax;
1452
1453         /*
1454          * get information on the (current) result relation
1455          */
1456         resultRelInfo = estate->es_result_relation_info;
1457         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1458
1459         /* BEFORE ROW DELETE Triggers */
1460         if (resultRelInfo->ri_TrigDesc &&
1461                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1462         {
1463                 bool            dodelete;
1464
1465                 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1466                                                                                 estate->es_snapshot->curcid);
1467
1468                 if (!dodelete)                  /* "do nothing" */
1469                         return;
1470         }
1471
1472         /*
1473          * delete the tuple
1474          *
1475          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1476          * the row to be deleted is visible to that snapshot, and throw a can't-
1477          * serialize error if not.      This is a special-case behavior needed for
1478          * referential integrity updates in serializable transactions.
1479          */
1480 ldelete:;
1481         result = heap_delete(resultRelationDesc, tupleid,
1482                                                  &update_ctid, &update_xmax,
1483                                                  estate->es_snapshot->curcid,
1484                                                  estate->es_crosscheck_snapshot,
1485                                                  true /* wait for commit */ );
1486         switch (result)
1487         {
1488                 case HeapTupleSelfUpdated:
1489                         /* already deleted by self; nothing to do */
1490                         return;
1491
1492                 case HeapTupleMayBeUpdated:
1493                         break;
1494
1495                 case HeapTupleUpdated:
1496                         if (IsXactIsoLevelSerializable)
1497                                 ereport(ERROR,
1498                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1499                                                  errmsg("could not serialize access due to concurrent update")));
1500                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1501                         {
1502                                 TupleTableSlot *epqslot;
1503
1504                                 epqslot = EvalPlanQual(estate,
1505                                                                            resultRelInfo->ri_RangeTableIndex,
1506                                                                            &update_ctid,
1507                                                                            update_xmax,
1508                                                                            estate->es_snapshot->curcid);
1509                                 if (!TupIsNull(epqslot))
1510                                 {
1511                                         *tupleid = update_ctid;
1512                                         goto ldelete;
1513                                 }
1514                         }
1515                         /* tuple already deleted; nothing to do */
1516                         return;
1517
1518                 default:
1519                         elog(ERROR, "unrecognized heap_delete status: %u", result);
1520                         return;
1521         }
1522
1523         IncrDeleted();
1524         (estate->es_processed)++;
1525
1526         /*
1527          * Note: Normally one would think that we have to delete index tuples
1528          * associated with the heap tuple now...
1529          *
1530          * ... but in POSTGRES, we have no need to do this because VACUUM will
1531          * take care of it later.  We can't delete index tuples immediately
1532          * anyway, since the tuple is still visible to other transactions.
1533          */
1534
1535         /* AFTER ROW DELETE Triggers */
1536         ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1537
1538         /* Process RETURNING if present */
1539         if (resultRelInfo->ri_projectReturning)
1540         {
1541                 /*
1542                  * We have to put the target tuple into a slot, which means first we
1543                  * gotta fetch it.      We can use the trigger tuple slot.
1544                  */
1545                 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1546                 HeapTupleData deltuple;
1547                 Buffer          delbuffer;
1548
1549                 deltuple.t_self = *tupleid;
1550                 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1551                                                 &deltuple, &delbuffer, false, NULL))
1552                         elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1553
1554                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1555                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1556                 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1557
1558                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1559                                                          slot, planSlot, dest);
1560
1561                 ExecClearTuple(slot);
1562                 ReleaseBuffer(delbuffer);
1563         }
1564 }
1565
1566 /* ----------------------------------------------------------------
1567  *              ExecUpdate
1568  *
1569  *              note: we can't run UPDATE queries with transactions
1570  *              off because UPDATEs are actually INSERTs and our
1571  *              scan will mistakenly loop forever, updating the tuple
1572  *              it just inserted..      This should be fixed but until it
1573  *              is, we don't want to get stuck in an infinite loop
1574  *              which corrupts your database..
1575  * ----------------------------------------------------------------
1576  */
1577 static void
1578 ExecUpdate(TupleTableSlot *slot,
1579                    ItemPointer tupleid,
1580                    TupleTableSlot *planSlot,
1581                    DestReceiver *dest,
1582                    EState *estate)
1583 {
1584         HeapTuple       tuple;
1585         ResultRelInfo *resultRelInfo;
1586         Relation        resultRelationDesc;
1587         HTSU_Result result;
1588         ItemPointerData update_ctid;
1589         TransactionId update_xmax;
1590
1591         /*
1592          * abort the operation if not running transactions
1593          */
1594         if (IsBootstrapProcessingMode())
1595                 elog(ERROR, "cannot UPDATE during bootstrap");
1596
1597         /*
1598          * get the heap tuple out of the tuple table slot, making sure we have a
1599          * writable copy
1600          */
1601         tuple = ExecMaterializeSlot(slot);
1602
1603         /*
1604          * get information on the (current) result relation
1605          */
1606         resultRelInfo = estate->es_result_relation_info;
1607         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1608
1609         /* BEFORE ROW UPDATE Triggers */
1610         if (resultRelInfo->ri_TrigDesc &&
1611                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1612         {
1613                 HeapTuple       newtuple;
1614
1615                 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1616                                                                                 tupleid, tuple,
1617                                                                                 estate->es_snapshot->curcid);
1618
1619                 if (newtuple == NULL)   /* "do nothing" */
1620                         return;
1621
1622                 if (newtuple != tuple)  /* modified by Trigger(s) */
1623                 {
1624                         /*
1625                          * Put the modified tuple into a slot for convenience of routines
1626                          * below.  We assume the tuple was allocated in per-tuple memory
1627                          * context, and therefore will go away by itself. The tuple table
1628                          * slot should not try to clear it.
1629                          */
1630                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1631
1632                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1633                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1634                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1635                         slot = newslot;
1636                         tuple = newtuple;
1637                 }
1638         }
1639
1640         /*
1641          * Check the constraints of the tuple
1642          *
1643          * If we generate a new candidate tuple after EvalPlanQual testing, we
1644          * must loop back here and recheck constraints.  (We don't need to redo
1645          * triggers, however.  If there are any BEFORE triggers then trigger.c
1646          * will have done heap_lock_tuple to lock the correct tuple, so there's no
1647          * need to do them again.)
1648          */
1649 lreplace:;
1650         if (resultRelationDesc->rd_att->constr)
1651                 ExecConstraints(resultRelInfo, slot, estate);
1652
1653         /*
1654          * replace the heap tuple
1655          *
1656          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1657          * the row to be updated is visible to that snapshot, and throw a can't-
1658          * serialize error if not.      This is a special-case behavior needed for
1659          * referential integrity updates in serializable transactions.
1660          */
1661         result = heap_update(resultRelationDesc, tupleid, tuple,
1662                                                  &update_ctid, &update_xmax,
1663                                                  estate->es_snapshot->curcid,
1664                                                  estate->es_crosscheck_snapshot,
1665                                                  true /* wait for commit */ );
1666         switch (result)
1667         {
1668                 case HeapTupleSelfUpdated:
1669                         /* already deleted by self; nothing to do */
1670                         return;
1671
1672                 case HeapTupleMayBeUpdated:
1673                         break;
1674
1675                 case HeapTupleUpdated:
1676                         if (IsXactIsoLevelSerializable)
1677                                 ereport(ERROR,
1678                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1679                                                  errmsg("could not serialize access due to concurrent update")));
1680                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1681                         {
1682                                 TupleTableSlot *epqslot;
1683
1684                                 epqslot = EvalPlanQual(estate,
1685                                                                            resultRelInfo->ri_RangeTableIndex,
1686                                                                            &update_ctid,
1687                                                                            update_xmax,
1688                                                                            estate->es_snapshot->curcid);
1689                                 if (!TupIsNull(epqslot))
1690                                 {
1691                                         *tupleid = update_ctid;
1692                                         slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1693                                         tuple = ExecMaterializeSlot(slot);
1694                                         goto lreplace;
1695                                 }
1696                         }
1697                         /* tuple already deleted; nothing to do */
1698                         return;
1699
1700                 default:
1701                         elog(ERROR, "unrecognized heap_update status: %u", result);
1702                         return;
1703         }
1704
1705         IncrReplaced();
1706         (estate->es_processed)++;
1707
1708         /*
1709          * Note: instead of having to update the old index tuples associated with
1710          * the heap tuple, all we do is form and insert new index tuples. This is
1711          * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1712          * deletion is done later by VACUUM (see notes in ExecDelete).  All we do
1713          * here is insert new index tuples.  -cim 9/27/89
1714          */
1715
1716         /*
1717          * insert index entries for tuple
1718          *
1719          * Note: heap_update returns the tid (location) of the new tuple in the
1720          * t_self field.
1721          */
1722         if (resultRelInfo->ri_NumIndices > 0)
1723                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1724
1725         /* AFTER ROW UPDATE Triggers */
1726         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1727
1728         /* Process RETURNING if present */
1729         if (resultRelInfo->ri_projectReturning)
1730                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1731                                                          slot, planSlot, dest);
1732 }
1733
1734 /*
1735  * ExecRelCheck --- check that tuple meets constraints for result relation
1736  */
1737 static const char *
1738 ExecRelCheck(ResultRelInfo *resultRelInfo,
1739                          TupleTableSlot *slot, EState *estate)
1740 {
1741         Relation        rel = resultRelInfo->ri_RelationDesc;
1742         int                     ncheck = rel->rd_att->constr->num_check;
1743         ConstrCheck *check = rel->rd_att->constr->check;
1744         ExprContext *econtext;
1745         MemoryContext oldContext;
1746         List       *qual;
1747         int                     i;
1748
1749         /*
1750          * If first time through for this result relation, build expression
1751          * nodetrees for rel's constraint expressions.  Keep them in the per-query
1752          * memory context so they'll survive throughout the query.
1753          */
1754         if (resultRelInfo->ri_ConstraintExprs == NULL)
1755         {
1756                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1757                 resultRelInfo->ri_ConstraintExprs =
1758                         (List **) palloc(ncheck * sizeof(List *));
1759                 for (i = 0; i < ncheck; i++)
1760                 {
1761                         /* ExecQual wants implicit-AND form */
1762                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
1763                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
1764                                 ExecPrepareExpr((Expr *) qual, estate);
1765                 }
1766                 MemoryContextSwitchTo(oldContext);
1767         }
1768
1769         /*
1770          * We will use the EState's per-tuple context for evaluating constraint
1771          * expressions (creating it if it's not already there).
1772          */
1773         econtext = GetPerTupleExprContext(estate);
1774
1775         /* Arrange for econtext's scan tuple to be the tuple under test */
1776         econtext->ecxt_scantuple = slot;
1777
1778         /* And evaluate the constraints */
1779         for (i = 0; i < ncheck; i++)
1780         {
1781                 qual = resultRelInfo->ri_ConstraintExprs[i];
1782
1783                 /*
1784                  * NOTE: SQL92 specifies that a NULL result from a constraint
1785                  * expression is not to be treated as a failure.  Therefore, tell
1786                  * ExecQual to return TRUE for NULL.
1787                  */
1788                 if (!ExecQual(qual, econtext, true))
1789                         return check[i].ccname;
1790         }
1791
1792         /* NULL result means no error */
1793         return NULL;
1794 }
1795
1796 void
1797 ExecConstraints(ResultRelInfo *resultRelInfo,
1798                                 TupleTableSlot *slot, EState *estate)
1799 {
1800         Relation        rel = resultRelInfo->ri_RelationDesc;
1801         TupleConstr *constr = rel->rd_att->constr;
1802
1803         Assert(constr);
1804
1805         if (constr->has_not_null)
1806         {
1807                 int                     natts = rel->rd_att->natts;
1808                 int                     attrChk;
1809
1810                 for (attrChk = 1; attrChk <= natts; attrChk++)
1811                 {
1812                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1813                                 slot_attisnull(slot, attrChk))
1814                                 ereport(ERROR,
1815                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1816                                                  errmsg("null value in column \"%s\" violates not-null constraint",
1817                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1818                 }
1819         }
1820
1821         if (constr->num_check > 0)
1822         {
1823                 const char *failed;
1824
1825                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1826                         ereport(ERROR,
1827                                         (errcode(ERRCODE_CHECK_VIOLATION),
1828                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1829                                                         RelationGetRelationName(rel), failed)));
1830         }
1831 }
1832
1833 /*
1834  * ExecProcessReturning --- evaluate a RETURNING list and send to dest
1835  *
1836  * projectReturning: RETURNING projection info for current result rel
1837  * tupleSlot: slot holding tuple actually inserted/updated/deleted
1838  * planSlot: slot holding tuple returned by top plan node
1839  * dest: where to send the output
1840  */
1841 static void
1842 ExecProcessReturning(ProjectionInfo *projectReturning,
1843                                          TupleTableSlot *tupleSlot,
1844                                          TupleTableSlot *planSlot,
1845                                          DestReceiver *dest)
1846 {
1847         ExprContext *econtext = projectReturning->pi_exprContext;
1848         TupleTableSlot *retSlot;
1849
1850         /*
1851          * Reset per-tuple memory context to free any expression evaluation
1852          * storage allocated in the previous cycle.
1853          */
1854         ResetExprContext(econtext);
1855
1856         /* Make tuple and any needed join variables available to ExecProject */
1857         econtext->ecxt_scantuple = tupleSlot;
1858         econtext->ecxt_outertuple = planSlot;
1859
1860         /* Compute the RETURNING expressions */
1861         retSlot = ExecProject(projectReturning, NULL);
1862
1863         /* Send to dest */
1864         (*dest->receiveSlot) (retSlot, dest);
1865
1866         ExecClearTuple(retSlot);
1867 }
1868
1869 /*
1870  * Check a modified tuple to see if we want to process its updated version
1871  * under READ COMMITTED rules.
1872  *
1873  * See backend/executor/README for some info about how this works.
1874  *
1875  *      estate - executor state data
1876  *      rti - rangetable index of table containing tuple
1877  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1878  *      priorXmax - t_xmax from the outdated tuple
1879  *      curCid - command ID of current command of my transaction
1880  *
1881  * *tid is also an output parameter: it's modified to hold the TID of the
1882  * latest version of the tuple (note this may be changed even on failure)
1883  *
1884  * Returns a slot containing the new candidate update/delete tuple, or
1885  * NULL if we determine we shouldn't process the row.
1886  */
1887 TupleTableSlot *
1888 EvalPlanQual(EState *estate, Index rti,
1889                          ItemPointer tid, TransactionId priorXmax, CommandId curCid)
1890 {
1891         evalPlanQual *epq;
1892         EState     *epqstate;
1893         Relation        relation;
1894         HeapTupleData tuple;
1895         HeapTuple       copyTuple = NULL;
1896         SnapshotData SnapshotDirty;
1897         bool            endNode;
1898
1899         Assert(rti != 0);
1900
1901         /*
1902          * find relation containing target tuple
1903          */
1904         if (estate->es_result_relation_info != NULL &&
1905                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1906                 relation = estate->es_result_relation_info->ri_RelationDesc;
1907         else
1908         {
1909                 ListCell   *l;
1910
1911                 relation = NULL;
1912                 foreach(l, estate->es_rowMarks)
1913                 {
1914                         if (((ExecRowMark *) lfirst(l))->rti == rti)
1915                         {
1916                                 relation = ((ExecRowMark *) lfirst(l))->relation;
1917                                 break;
1918                         }
1919                 }
1920                 if (relation == NULL)
1921                         elog(ERROR, "could not find RowMark for RT index %u", rti);
1922         }
1923
1924         /*
1925          * fetch tid tuple
1926          *
1927          * Loop here to deal with updated or busy tuples
1928          */
1929         InitDirtySnapshot(SnapshotDirty);
1930         tuple.t_self = *tid;
1931         for (;;)
1932         {
1933                 Buffer          buffer;
1934
1935                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1936                 {
1937                         /*
1938                          * If xmin isn't what we're expecting, the slot must have been
1939                          * recycled and reused for an unrelated tuple.  This implies that
1940                          * the latest version of the row was deleted, so we need do
1941                          * nothing.  (Should be safe to examine xmin without getting
1942                          * buffer's content lock, since xmin never changes in an existing
1943                          * tuple.)
1944                          */
1945                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1946                                                                          priorXmax))
1947                         {
1948                                 ReleaseBuffer(buffer);
1949                                 return NULL;
1950                         }
1951
1952                         /* otherwise xmin should not be dirty... */
1953                         if (TransactionIdIsValid(SnapshotDirty.xmin))
1954                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1955
1956                         /*
1957                          * If tuple is being updated by other transaction then we have to
1958                          * wait for its commit/abort.
1959                          */
1960                         if (TransactionIdIsValid(SnapshotDirty.xmax))
1961                         {
1962                                 ReleaseBuffer(buffer);
1963                                 XactLockTableWait(SnapshotDirty.xmax);
1964                                 continue;               /* loop back to repeat heap_fetch */
1965                         }
1966
1967                         /*
1968                          * If tuple was inserted by our own transaction, we have to check
1969                          * cmin against curCid: cmin >= curCid means our command cannot
1970                          * see the tuple, so we should ignore it.  Without this we are
1971                          * open to the "Halloween problem" of indefinitely re-updating the
1972                          * same tuple.  (We need not check cmax because
1973                          * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1974                          * transaction dead, regardless of cmax.)  We just checked that
1975                          * priorXmax == xmin, so we can test that variable instead of
1976                          * doing HeapTupleHeaderGetXmin again.
1977                          */
1978                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1979                                 HeapTupleHeaderGetCmin(tuple.t_data) >= curCid)
1980                         {
1981                                 ReleaseBuffer(buffer);
1982                                 return NULL;
1983                         }
1984
1985                         /*
1986                          * We got tuple - now copy it for use by recheck query.
1987                          */
1988                         copyTuple = heap_copytuple(&tuple);
1989                         ReleaseBuffer(buffer);
1990                         break;
1991                 }
1992
1993                 /*
1994                  * If the referenced slot was actually empty, the latest version of
1995                  * the row must have been deleted, so we need do nothing.
1996                  */
1997                 if (tuple.t_data == NULL)
1998                 {
1999                         ReleaseBuffer(buffer);
2000                         return NULL;
2001                 }
2002
2003                 /*
2004                  * As above, if xmin isn't what we're expecting, do nothing.
2005                  */
2006                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2007                                                                  priorXmax))
2008                 {
2009                         ReleaseBuffer(buffer);
2010                         return NULL;
2011                 }
2012
2013                 /*
2014                  * If we get here, the tuple was found but failed SnapshotDirty.
2015                  * Assuming the xmin is either a committed xact or our own xact (as it
2016                  * certainly should be if we're trying to modify the tuple), this must
2017                  * mean that the row was updated or deleted by either a committed xact
2018                  * or our own xact.  If it was deleted, we can ignore it; if it was
2019                  * updated then chain up to the next version and repeat the whole
2020                  * test.
2021                  *
2022                  * As above, it should be safe to examine xmax and t_ctid without the
2023                  * buffer content lock, because they can't be changing.
2024                  */
2025                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2026                 {
2027                         /* deleted, so forget about it */
2028                         ReleaseBuffer(buffer);
2029                         return NULL;
2030                 }
2031
2032                 /* updated, so look at the updated row */
2033                 tuple.t_self = tuple.t_data->t_ctid;
2034                 /* updated row should have xmin matching this xmax */
2035                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2036                 ReleaseBuffer(buffer);
2037                 /* loop back to fetch next in chain */
2038         }
2039
2040         /*
2041          * For UPDATE/DELETE we have to return tid of actual row we're executing
2042          * PQ for.
2043          */
2044         *tid = tuple.t_self;
2045
2046         /*
2047          * Need to run a recheck subquery.      Find or create a PQ stack entry.
2048          */
2049         epq = estate->es_evalPlanQual;
2050         endNode = true;
2051
2052         if (epq != NULL && epq->rti == 0)
2053         {
2054                 /* Top PQ stack entry is idle, so re-use it */
2055                 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2056                 epq->rti = rti;
2057                 endNode = false;
2058         }
2059
2060         /*
2061          * If this is request for another RTE - Ra, - then we have to check wasn't
2062          * PlanQual requested for Ra already and if so then Ra' row was updated
2063          * again and we have to re-start old execution for Ra and forget all what
2064          * we done after Ra was suspended. Cool? -:))
2065          */
2066         if (epq != NULL && epq->rti != rti &&
2067                 epq->estate->es_evTuple[rti - 1] != NULL)
2068         {
2069                 do
2070                 {
2071                         evalPlanQual *oldepq;
2072
2073                         /* stop execution */
2074                         EvalPlanQualStop(epq);
2075                         /* pop previous PlanQual from the stack */
2076                         oldepq = epq->next;
2077                         Assert(oldepq && oldepq->rti != 0);
2078                         /* push current PQ to freePQ stack */
2079                         oldepq->free = epq;
2080                         epq = oldepq;
2081                         estate->es_evalPlanQual = epq;
2082                 } while (epq->rti != rti);
2083         }
2084
2085         /*
2086          * If we are requested for another RTE then we have to suspend execution
2087          * of current PlanQual and start execution for new one.
2088          */
2089         if (epq == NULL || epq->rti != rti)
2090         {
2091                 /* try to reuse plan used previously */
2092                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2093
2094                 if (newepq == NULL)             /* first call or freePQ stack is empty */
2095                 {
2096                         newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2097                         newepq->free = NULL;
2098                         newepq->estate = NULL;
2099                         newepq->planstate = NULL;
2100                 }
2101                 else
2102                 {
2103                         /* recycle previously used PlanQual */
2104                         Assert(newepq->estate == NULL);
2105                         epq->free = NULL;
2106                 }
2107                 /* push current PQ to the stack */
2108                 newepq->next = epq;
2109                 epq = newepq;
2110                 estate->es_evalPlanQual = epq;
2111                 epq->rti = rti;
2112                 endNode = false;
2113         }
2114
2115         Assert(epq->rti == rti);
2116
2117         /*
2118          * Ok - we're requested for the same RTE.  Unfortunately we still have to
2119          * end and restart execution of the plan, because ExecReScan wouldn't
2120          * ensure that upper plan nodes would reset themselves.  We could make
2121          * that work if insertion of the target tuple were integrated with the
2122          * Param mechanism somehow, so that the upper plan nodes know that their
2123          * children's outputs have changed.
2124          *
2125          * Note that the stack of free evalPlanQual nodes is quite useless at the
2126          * moment, since it only saves us from pallocing/releasing the
2127          * evalPlanQual nodes themselves.  But it will be useful once we implement
2128          * ReScan instead of end/restart for re-using PlanQual nodes.
2129          */
2130         if (endNode)
2131         {
2132                 /* stop execution */
2133                 EvalPlanQualStop(epq);
2134         }
2135
2136         /*
2137          * Initialize new recheck query.
2138          *
2139          * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2140          * instead copy down changeable state from the top plan (including
2141          * es_result_relation_info, es_junkFilter) and reset locally changeable
2142          * state in the epq (including es_param_exec_vals, es_evTupleNull).
2143          */
2144         EvalPlanQualStart(epq, estate, epq->next);
2145
2146         /*
2147          * free old RTE' tuple, if any, and store target tuple where relation's
2148          * scan node will see it
2149          */
2150         epqstate = epq->estate;
2151         if (epqstate->es_evTuple[rti - 1] != NULL)
2152                 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2153         epqstate->es_evTuple[rti - 1] = copyTuple;
2154
2155         return EvalPlanQualNext(estate);
2156 }
2157
2158 static TupleTableSlot *
2159 EvalPlanQualNext(EState *estate)
2160 {
2161         evalPlanQual *epq = estate->es_evalPlanQual;
2162         MemoryContext oldcontext;
2163         TupleTableSlot *slot;
2164
2165         Assert(epq->rti != 0);
2166
2167 lpqnext:;
2168         oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2169         slot = ExecProcNode(epq->planstate);
2170         MemoryContextSwitchTo(oldcontext);
2171
2172         /*
2173          * No more tuples for this PQ. Continue previous one.
2174          */
2175         if (TupIsNull(slot))
2176         {
2177                 evalPlanQual *oldepq;
2178
2179                 /* stop execution */
2180                 EvalPlanQualStop(epq);
2181                 /* pop old PQ from the stack */
2182                 oldepq = epq->next;
2183                 if (oldepq == NULL)
2184                 {
2185                         /* this is the first (oldest) PQ - mark as free */
2186                         epq->rti = 0;
2187                         estate->es_useEvalPlan = false;
2188                         /* and continue Query execution */
2189                         return NULL;
2190                 }
2191                 Assert(oldepq->rti != 0);
2192                 /* push current PQ to freePQ stack */
2193                 oldepq->free = epq;
2194                 epq = oldepq;
2195                 estate->es_evalPlanQual = epq;
2196                 goto lpqnext;
2197         }
2198
2199         return slot;
2200 }
2201
2202 static void
2203 EndEvalPlanQual(EState *estate)
2204 {
2205         evalPlanQual *epq = estate->es_evalPlanQual;
2206
2207         if (epq->rti == 0)                      /* plans already shutdowned */
2208         {
2209                 Assert(epq->next == NULL);
2210                 return;
2211         }
2212
2213         for (;;)
2214         {
2215                 evalPlanQual *oldepq;
2216
2217                 /* stop execution */
2218                 EvalPlanQualStop(epq);
2219                 /* pop old PQ from the stack */
2220                 oldepq = epq->next;
2221                 if (oldepq == NULL)
2222                 {
2223                         /* this is the first (oldest) PQ - mark as free */
2224                         epq->rti = 0;
2225                         estate->es_useEvalPlan = false;
2226                         break;
2227                 }
2228                 Assert(oldepq->rti != 0);
2229                 /* push current PQ to freePQ stack */
2230                 oldepq->free = epq;
2231                 epq = oldepq;
2232                 estate->es_evalPlanQual = epq;
2233         }
2234 }
2235
2236 /*
2237  * Start execution of one level of PlanQual.
2238  *
2239  * This is a cut-down version of ExecutorStart(): we copy some state from
2240  * the top-level estate rather than initializing it fresh.
2241  */
2242 static void
2243 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2244 {
2245         EState     *epqstate;
2246         int                     rtsize;
2247         MemoryContext oldcontext;
2248         ListCell   *l;
2249
2250         rtsize = list_length(estate->es_range_table);
2251
2252         epq->estate = epqstate = CreateExecutorState();
2253
2254         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2255
2256         /*
2257          * The epqstates share the top query's copy of unchanging state such as
2258          * the snapshot, rangetable, result-rel info, and external Param info.
2259          * They need their own copies of local state, including a tuple table,
2260          * es_param_exec_vals, etc.
2261          */
2262         epqstate->es_direction = ForwardScanDirection;
2263         epqstate->es_snapshot = estate->es_snapshot;
2264         epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2265         epqstate->es_range_table = estate->es_range_table;
2266         epqstate->es_result_relations = estate->es_result_relations;
2267         epqstate->es_num_result_relations = estate->es_num_result_relations;
2268         epqstate->es_result_relation_info = estate->es_result_relation_info;
2269         epqstate->es_junkFilter = estate->es_junkFilter;
2270         epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2271         epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2272         epqstate->es_param_list_info = estate->es_param_list_info;
2273         if (estate->es_plannedstmt->nParamExec > 0)
2274                 epqstate->es_param_exec_vals = (ParamExecData *)
2275                         palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2276         epqstate->es_rowMarks = estate->es_rowMarks;
2277         epqstate->es_instrument = estate->es_instrument;
2278         epqstate->es_select_into = estate->es_select_into;
2279         epqstate->es_into_oids = estate->es_into_oids;
2280         epqstate->es_plannedstmt = estate->es_plannedstmt;
2281
2282         /*
2283          * Each epqstate must have its own es_evTupleNull state, but all the stack
2284          * entries share es_evTuple state.      This allows sub-rechecks to inherit
2285          * the value being examined by an outer recheck.
2286          */
2287         epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2288         if (priorepq == NULL)
2289                 /* first PQ stack entry */
2290                 epqstate->es_evTuple = (HeapTuple *)
2291                         palloc0(rtsize * sizeof(HeapTuple));
2292         else
2293                 /* later stack entries share the same storage */
2294                 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2295
2296         /*
2297          * Create sub-tuple-table; we needn't redo the CountSlots work though.
2298          */
2299         epqstate->es_tupleTable =
2300                 ExecCreateTupleTable(estate->es_tupleTable->size);
2301
2302         /*
2303          * Initialize private state information for each SubPlan.  We must do
2304          * this before running ExecInitNode on the main query tree, since
2305          * ExecInitSubPlan expects to be able to find these entries.
2306          */
2307         Assert(epqstate->es_subplanstates == NIL);
2308         foreach(l, estate->es_plannedstmt->subplans)
2309         {
2310                 Plan   *subplan = (Plan *) lfirst(l);
2311                 PlanState *subplanstate;
2312
2313                 subplanstate = ExecInitNode(subplan, epqstate, 0);
2314
2315                 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2316                                                                                          subplanstate);
2317         }
2318
2319         /*
2320          * Initialize the private state information for all the nodes in the query
2321          * tree.  This opens files, allocates storage and leaves us ready to start
2322          * processing tuples.
2323          */
2324         epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2325
2326         MemoryContextSwitchTo(oldcontext);
2327 }
2328
2329 /*
2330  * End execution of one level of PlanQual.
2331  *
2332  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2333  * of the normal cleanup, but *not* close result relations (which we are
2334  * just sharing from the outer query).
2335  */
2336 static void
2337 EvalPlanQualStop(evalPlanQual *epq)
2338 {
2339         EState     *epqstate = epq->estate;
2340         MemoryContext oldcontext;
2341         ListCell   *l;
2342
2343         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2344
2345         ExecEndNode(epq->planstate);
2346
2347         foreach(l, epqstate->es_subplanstates)
2348         {
2349                 PlanState *subplanstate = (PlanState *) lfirst(l);
2350
2351                 ExecEndNode(subplanstate);
2352         }
2353
2354         ExecDropTupleTable(epqstate->es_tupleTable, true);
2355         epqstate->es_tupleTable = NULL;
2356
2357         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2358         {
2359                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2360                 epqstate->es_evTuple[epq->rti - 1] = NULL;
2361         }
2362
2363         MemoryContextSwitchTo(oldcontext);
2364
2365         FreeExecutorState(epqstate);
2366
2367         epq->estate = NULL;
2368         epq->planstate = NULL;
2369 }
2370
2371
2372 /*
2373  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2374  *
2375  * We implement SELECT INTO by diverting SELECT's normal output with
2376  * a specialized DestReceiver type.
2377  *
2378  * TODO: remove some of the INTO-specific cruft from EState, and keep
2379  * it in the DestReceiver instead.
2380  */
2381
2382 typedef struct
2383 {
2384         DestReceiver pub;                       /* publicly-known function pointers */
2385         EState     *estate;                     /* EState we are working with */
2386 } DR_intorel;
2387
2388 /*
2389  * OpenIntoRel --- actually create the SELECT INTO target relation
2390  *
2391  * This also replaces QueryDesc->dest with the special DestReceiver for
2392  * SELECT INTO.  We assume that the correct result tuple type has already
2393  * been placed in queryDesc->tupDesc.
2394  */
2395 static void
2396 OpenIntoRel(QueryDesc *queryDesc)
2397 {
2398         IntoClause *into = queryDesc->plannedstmt->intoClause;
2399         EState     *estate = queryDesc->estate;
2400         Relation        intoRelationDesc;
2401         char       *intoName;
2402         Oid                     namespaceId;
2403         Oid                     tablespaceId;
2404         Datum           reloptions;
2405         AclResult       aclresult;
2406         Oid                     intoRelationId;
2407         TupleDesc       tupdesc;
2408         DR_intorel *myState;
2409
2410         Assert(into);
2411
2412         /*
2413          * Check consistency of arguments
2414          */
2415         if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2416                 ereport(ERROR,
2417                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2418                                  errmsg("ON COMMIT can only be used on temporary tables")));
2419
2420         /*
2421          * Find namespace to create in, check its permissions
2422          */
2423         intoName = into->rel->relname;
2424         namespaceId = RangeVarGetCreationNamespace(into->rel);
2425
2426         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2427                                                                           ACL_CREATE);
2428         if (aclresult != ACLCHECK_OK)
2429                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2430                                            get_namespace_name(namespaceId));
2431
2432         /*
2433          * Select tablespace to use.  If not specified, use default_tablespace
2434          * (which may in turn default to database's default).
2435          */
2436         if (into->tableSpaceName)
2437         {
2438                 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2439                 if (!OidIsValid(tablespaceId))
2440                         ereport(ERROR,
2441                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
2442                                          errmsg("tablespace \"%s\" does not exist",
2443                                                         into->tableSpaceName)));
2444         }
2445         else
2446         {
2447                 tablespaceId = GetDefaultTablespace();
2448                 /* note InvalidOid is OK in this case */
2449         }
2450
2451         /* Check permissions except when using the database's default space */
2452         if (OidIsValid(tablespaceId))
2453         {
2454                 AclResult       aclresult;
2455
2456                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2457                                                                                    ACL_CREATE);
2458
2459                 if (aclresult != ACLCHECK_OK)
2460                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2461                                                    get_tablespace_name(tablespaceId));
2462         }
2463
2464         /* Parse and validate any reloptions */
2465         reloptions = transformRelOptions((Datum) 0,
2466                                                                          into->options,
2467                                                                          true,
2468                                                                          false);
2469         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2470
2471         /* have to copy the actual tupdesc to get rid of any constraints */
2472         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2473
2474         /* Now we can actually create the new relation */
2475         intoRelationId = heap_create_with_catalog(intoName,
2476                                                                                           namespaceId,
2477                                                                                           tablespaceId,
2478                                                                                           InvalidOid,
2479                                                                                           GetUserId(),
2480                                                                                           tupdesc,
2481                                                                                           RELKIND_RELATION,
2482                                                                                           false,
2483                                                                                           true,
2484                                                                                           0,
2485                                                                                           into->onCommit,
2486                                                                                           reloptions,
2487                                                                                           allowSystemTableMods);
2488
2489         FreeTupleDesc(tupdesc);
2490
2491         /*
2492          * Advance command counter so that the newly-created relation's catalog
2493          * tuples will be visible to heap_open.
2494          */
2495         CommandCounterIncrement();
2496
2497         /*
2498          * If necessary, create a TOAST table for the INTO relation. Note that
2499          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2500          * the TOAST table will be visible for insertion.
2501          */
2502         AlterTableCreateToastTable(intoRelationId);
2503
2504         /*
2505          * And open the constructed table for writing.
2506          */
2507         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2508
2509         /* use_wal off requires rd_targblock be initially invalid */
2510         Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2511
2512         /*
2513          * We can skip WAL-logging the insertions, unless PITR is in use.
2514          *
2515          * Note that for a non-temp INTO table, this is safe only because we know
2516          * that the catalog changes above will have been WAL-logged, and so
2517          * RecordTransactionCommit will think it needs to WAL-log the eventual
2518          * transaction commit.  Else the commit might be lost, even though all the
2519          * data is safely fsync'd ...
2520          */
2521         estate->es_into_relation_use_wal = XLogArchivingActive();
2522         estate->es_into_relation_descriptor = intoRelationDesc;
2523
2524         /*
2525          * Now replace the query's DestReceiver with one for SELECT INTO
2526          */
2527         queryDesc->dest = CreateDestReceiver(DestIntoRel, NULL);
2528         myState = (DR_intorel *) queryDesc->dest;
2529         Assert(myState->pub.mydest == DestIntoRel);
2530         myState->estate = estate;
2531 }
2532
2533 /*
2534  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2535  */
2536 static void
2537 CloseIntoRel(QueryDesc *queryDesc)
2538 {
2539         EState     *estate = queryDesc->estate;
2540
2541         /* OpenIntoRel might never have gotten called */
2542         if (estate->es_into_relation_descriptor)
2543         {
2544                 /* If we skipped using WAL, must heap_sync before commit */
2545                 if (!estate->es_into_relation_use_wal)
2546                         heap_sync(estate->es_into_relation_descriptor);
2547
2548                 /* close rel, but keep lock until commit */
2549                 heap_close(estate->es_into_relation_descriptor, NoLock);
2550
2551                 estate->es_into_relation_descriptor = NULL;
2552         }
2553 }
2554
2555 /*
2556  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2557  *
2558  * Since CreateDestReceiver doesn't accept the parameters we'd need,
2559  * we just leave the private fields empty here.  OpenIntoRel will
2560  * fill them in.
2561  */
2562 DestReceiver *
2563 CreateIntoRelDestReceiver(void)
2564 {
2565         DR_intorel *self = (DR_intorel *) palloc(sizeof(DR_intorel));
2566
2567         self->pub.receiveSlot = intorel_receive;
2568         self->pub.rStartup = intorel_startup;
2569         self->pub.rShutdown = intorel_shutdown;
2570         self->pub.rDestroy = intorel_destroy;
2571         self->pub.mydest = DestIntoRel;
2572
2573         self->estate = NULL;
2574
2575         return (DestReceiver *) self;
2576 }
2577
2578 /*
2579  * intorel_startup --- executor startup
2580  */
2581 static void
2582 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2583 {
2584         /* no-op */
2585 }
2586
2587 /*
2588  * intorel_receive --- receive one tuple
2589  */
2590 static void
2591 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2592 {
2593         DR_intorel *myState = (DR_intorel *) self;
2594         EState     *estate = myState->estate;
2595         HeapTuple       tuple;
2596
2597         tuple = ExecCopySlotTuple(slot);
2598
2599         heap_insert(estate->es_into_relation_descriptor,
2600                                 tuple,
2601                                 estate->es_snapshot->curcid,
2602                                 estate->es_into_relation_use_wal,
2603                                 false);                 /* never any point in using FSM */
2604
2605         /* We know this is a newly created relation, so there are no indexes */
2606
2607         heap_freetuple(tuple);
2608
2609         IncrAppended();
2610 }
2611
2612 /*
2613  * intorel_shutdown --- executor end
2614  */
2615 static void
2616 intorel_shutdown(DestReceiver *self)
2617 {
2618         /* no-op */
2619 }
2620
2621 /*
2622  * intorel_destroy --- release DestReceiver object
2623  */
2624 static void
2625 intorel_destroy(DestReceiver *self)
2626 {
2627         pfree(self);
2628 }