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