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