OSDN Git Service

Tweak SPI_cursor_open to allow INSERT/UPDATE/DELETE RETURNING; this was
[pg-rex/syncrep.git] / 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.279 2006/08/12 20:05:55 tgl Exp $
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/transam.h"
38 #include "access/xact.h"
39 #include "catalog/heap.h"
40 #include "catalog/namespace.h"
41 #include "catalog/toasting.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "executor/nodeSubplan.h"
47 #include "miscadmin.h"
48 #include "optimizer/clauses.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parsetree.h"
51 #include "storage/smgr.h"
52 #include "utils/acl.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55
56
57 typedef struct evalPlanQual
58 {
59         Index           rti;
60         EState     *estate;
61         PlanState  *planstate;
62         struct evalPlanQual *next;      /* stack of active PlanQual plans */
63         struct evalPlanQual *free;      /* list of free PlanQual plans */
64 } evalPlanQual;
65
66 /* decls for local routines only used within this module */
67 static void InitPlan(QueryDesc *queryDesc, int eflags);
68 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
69                                   Index resultRelationIndex,
70                                   List *rangeTable,
71                                   CmdType operation,
72                                   bool doInstrument);
73 static 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
762                  * in 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                  * Because we already ran ExecInitNode() for the top plan node,
778                  * any subplans we just attached to it won't have been initialized;
779                  * so we have to do it here.  (Ugly, but the alternatives seem worse.)
780                  */
781                 foreach(l, planstate->subPlan)
782                 {
783                         SubPlanState *sstate = (SubPlanState *) lfirst(l);
784
785                         Assert(IsA(sstate, SubPlanState));
786                         if (sstate->planstate == NULL)                  /* already inited? */
787                                 ExecInitSubPlan(sstate, estate, eflags);
788                 }
789         }
790
791         queryDesc->tupDesc = tupType;
792         queryDesc->planstate = planstate;
793
794         /*
795          * If doing SELECT INTO, initialize the "into" relation.  We must wait
796          * till now so we have the "clean" result tuple type to create the new
797          * table from.
798          *
799          * If EXPLAIN, skip creating the "into" relation.
800          */
801         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
802                 OpenIntoRel(queryDesc);
803 }
804
805 /*
806  * Initialize ResultRelInfo data for one result relation
807  */
808 static void
809 initResultRelInfo(ResultRelInfo *resultRelInfo,
810                                   Index resultRelationIndex,
811                                   List *rangeTable,
812                                   CmdType operation,
813                                   bool doInstrument)
814 {
815         Oid                     resultRelationOid;
816         Relation        resultRelationDesc;
817
818         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
819         resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
820
821         switch (resultRelationDesc->rd_rel->relkind)
822         {
823                 case RELKIND_SEQUENCE:
824                         ereport(ERROR,
825                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
826                                          errmsg("cannot change sequence \"%s\"",
827                                                         RelationGetRelationName(resultRelationDesc))));
828                         break;
829                 case RELKIND_TOASTVALUE:
830                         ereport(ERROR,
831                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
832                                          errmsg("cannot change TOAST relation \"%s\"",
833                                                         RelationGetRelationName(resultRelationDesc))));
834                         break;
835                 case RELKIND_VIEW:
836                         ereport(ERROR,
837                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
838                                          errmsg("cannot change view \"%s\"",
839                                                         RelationGetRelationName(resultRelationDesc))));
840                         break;
841         }
842
843         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
844         resultRelInfo->type = T_ResultRelInfo;
845         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
846         resultRelInfo->ri_RelationDesc = resultRelationDesc;
847         resultRelInfo->ri_NumIndices = 0;
848         resultRelInfo->ri_IndexRelationDescs = NULL;
849         resultRelInfo->ri_IndexRelationInfo = NULL;
850         /* make a copy so as not to depend on relcache info not changing... */
851         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
852         if (resultRelInfo->ri_TrigDesc)
853         {
854                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
855
856                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
857                         palloc0(n * sizeof(FmgrInfo));
858                 if (doInstrument)
859                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
860                 else
861                         resultRelInfo->ri_TrigInstrument = NULL;
862         }
863         else
864         {
865                 resultRelInfo->ri_TrigFunctions = NULL;
866                 resultRelInfo->ri_TrigInstrument = NULL;
867         }
868         resultRelInfo->ri_ConstraintExprs = NULL;
869         resultRelInfo->ri_junkFilter = NULL;
870         resultRelInfo->ri_projectReturning = NULL;
871
872         /*
873          * If there are indices on the result relation, open them and save
874          * descriptors in the result relation info, so that we can add new index
875          * entries for the tuples we add/update.  We need not do this for a
876          * DELETE, however, since deletion doesn't affect indexes.
877          */
878         if (resultRelationDesc->rd_rel->relhasindex &&
879                 operation != CMD_DELETE)
880                 ExecOpenIndices(resultRelInfo);
881 }
882
883 /*
884  *              ExecContextForcesOids
885  *
886  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
887  * we need to ensure that result tuples have space for an OID iff they are
888  * going to be stored into a relation that has OIDs.  In other contexts
889  * we are free to choose whether to leave space for OIDs in result tuples
890  * (we generally don't want to, but we do if a physical-tlist optimization
891  * is possible).  This routine checks the plan context and returns TRUE if the
892  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
893  * *hasoids is set to the required value.
894  *
895  * One reason this is ugly is that all plan nodes in the plan tree will emit
896  * tuples with space for an OID, though we really only need the topmost node
897  * to do so.  However, node types like Sort don't project new tuples but just
898  * return their inputs, and in those cases the requirement propagates down
899  * to the input node.  Eventually we might make this code smart enough to
900  * recognize how far down the requirement really goes, but for now we just
901  * make all plan nodes do the same thing if the top level forces the choice.
902  *
903  * We assume that estate->es_result_relation_info is already set up to
904  * describe the target relation.  Note that in an UPDATE that spans an
905  * inheritance tree, some of the target relations may have OIDs and some not.
906  * We have to make the decisions on a per-relation basis as we initialize
907  * each of the child plans of the topmost Append plan.
908  *
909  * SELECT INTO is even uglier, because we don't have the INTO relation's
910  * descriptor available when this code runs; we have to look aside at a
911  * flag set by InitPlan().
912  */
913 bool
914 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
915 {
916         if (planstate->state->es_select_into)
917         {
918                 *hasoids = planstate->state->es_into_oids;
919                 return true;
920         }
921         else
922         {
923                 ResultRelInfo *ri = planstate->state->es_result_relation_info;
924
925                 if (ri != NULL)
926                 {
927                         Relation        rel = ri->ri_RelationDesc;
928
929                         if (rel != NULL)
930                         {
931                                 *hasoids = rel->rd_rel->relhasoids;
932                                 return true;
933                         }
934                 }
935         }
936
937         return false;
938 }
939
940 /* ----------------------------------------------------------------
941  *              ExecEndPlan
942  *
943  *              Cleans up the query plan -- closes files and frees up storage
944  *
945  * NOTE: we are no longer very worried about freeing storage per se
946  * in this code; FreeExecutorState should be guaranteed to release all
947  * memory that needs to be released.  What we are worried about doing
948  * is closing relations and dropping buffer pins.  Thus, for example,
949  * tuple tables must be cleared or dropped to ensure pins are released.
950  * ----------------------------------------------------------------
951  */
952 void
953 ExecEndPlan(PlanState *planstate, EState *estate)
954 {
955         ResultRelInfo *resultRelInfo;
956         int                     i;
957         ListCell   *l;
958
959         /*
960          * shut down any PlanQual processing we were doing
961          */
962         if (estate->es_evalPlanQual != NULL)
963                 EndEvalPlanQual(estate);
964
965         /*
966          * shut down the node-type-specific query processing
967          */
968         ExecEndNode(planstate);
969
970         /*
971          * destroy the executor "tuple" table.
972          */
973         ExecDropTupleTable(estate->es_tupleTable, true);
974         estate->es_tupleTable = NULL;
975
976         /*
977          * close the result relation(s) if any, but hold locks until xact commit.
978          */
979         resultRelInfo = estate->es_result_relations;
980         for (i = estate->es_num_result_relations; i > 0; i--)
981         {
982                 /* Close indices and then the relation itself */
983                 ExecCloseIndices(resultRelInfo);
984                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
985                 resultRelInfo++;
986         }
987
988         /*
989          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
990          */
991         foreach(l, estate->es_rowMarks)
992         {
993                 ExecRowMark *erm = lfirst(l);
994
995                 heap_close(erm->relation, NoLock);
996         }
997 }
998
999 /* ----------------------------------------------------------------
1000  *              ExecutePlan
1001  *
1002  *              processes the query plan to retrieve 'numberTuples' tuples in the
1003  *              direction specified.
1004  *
1005  *              Retrieves all tuples if numberTuples is 0
1006  *
1007  *              result is either a slot containing the last tuple in the case
1008  *              of a SELECT or NULL otherwise.
1009  *
1010  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1011  * user can see it
1012  * ----------------------------------------------------------------
1013  */
1014 static TupleTableSlot *
1015 ExecutePlan(EState *estate,
1016                         PlanState *planstate,
1017                         CmdType operation,
1018                         long numberTuples,
1019                         ScanDirection direction,
1020                         DestReceiver *dest)
1021 {
1022         JunkFilter *junkfilter;
1023         TupleTableSlot *planSlot;
1024         TupleTableSlot *slot;
1025         ItemPointer tupleid = NULL;
1026         ItemPointerData tuple_ctid;
1027         long            current_tuple_count;
1028         TupleTableSlot *result;
1029
1030         /*
1031          * initialize local variables
1032          */
1033         current_tuple_count = 0;
1034         result = NULL;
1035
1036         /*
1037          * Set the direction.
1038          */
1039         estate->es_direction = direction;
1040
1041         /*
1042          * Process BEFORE EACH STATEMENT triggers
1043          */
1044         switch (operation)
1045         {
1046                 case CMD_UPDATE:
1047                         ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1048                         break;
1049                 case CMD_DELETE:
1050                         ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1051                         break;
1052                 case CMD_INSERT:
1053                         ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1054                         break;
1055                 default:
1056                         /* do nothing */
1057                         break;
1058         }
1059
1060         /*
1061          * Loop until we've processed the proper number of tuples from the plan.
1062          */
1063
1064         for (;;)
1065         {
1066                 /* Reset the per-output-tuple exprcontext */
1067                 ResetPerTupleExprContext(estate);
1068
1069                 /*
1070                  * Execute the plan and obtain a tuple
1071                  */
1072 lnext:  ;
1073                 if (estate->es_useEvalPlan)
1074                 {
1075                         planSlot = EvalPlanQualNext(estate);
1076                         if (TupIsNull(planSlot))
1077                                 planSlot = ExecProcNode(planstate);
1078                 }
1079                 else
1080                         planSlot = ExecProcNode(planstate);
1081
1082                 /*
1083                  * if the tuple is null, then we assume there is nothing more to
1084                  * process so we just return null...
1085                  */
1086                 if (TupIsNull(planSlot))
1087                 {
1088                         result = NULL;
1089                         break;
1090                 }
1091                 slot = planSlot;
1092
1093                 /*
1094                  * if we have a junk filter, then project a new tuple with the junk
1095                  * removed.
1096                  *
1097                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1098                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1099                  * because that tuple slot has the wrong descriptor.)
1100                  *
1101                  * Also, extract all the junk information we need.
1102                  */
1103                 if ((junkfilter = estate->es_junkFilter) != NULL)
1104                 {
1105                         Datum           datum;
1106                         bool            isNull;
1107
1108                         /*
1109                          * extract the 'ctid' junk attribute.
1110                          */
1111                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
1112                         {
1113                                 if (!ExecGetJunkAttribute(junkfilter,
1114                                                                                   slot,
1115                                                                                   "ctid",
1116                                                                                   &datum,
1117                                                                                   &isNull))
1118                                         elog(ERROR, "could not find junk ctid column");
1119
1120                                 /* shouldn't ever get a null result... */
1121                                 if (isNull)
1122                                         elog(ERROR, "ctid is NULL");
1123
1124                                 tupleid = (ItemPointer) DatumGetPointer(datum);
1125                                 tuple_ctid = *tupleid;  /* make sure we don't free the ctid!! */
1126                                 tupleid = &tuple_ctid;
1127                         }
1128
1129                         /*
1130                          * Process any FOR UPDATE or FOR SHARE locking requested.
1131                          */
1132                         else if (estate->es_rowMarks != NIL)
1133                         {
1134                                 ListCell   *l;
1135
1136                 lmark:  ;
1137                                 foreach(l, estate->es_rowMarks)
1138                                 {
1139                                         ExecRowMark *erm = lfirst(l);
1140                                         HeapTupleData tuple;
1141                                         Buffer          buffer;
1142                                         ItemPointerData update_ctid;
1143                                         TransactionId update_xmax;
1144                                         TupleTableSlot *newSlot;
1145                                         LockTupleMode lockmode;
1146                                         HTSU_Result test;
1147
1148                                         if (!ExecGetJunkAttribute(junkfilter,
1149                                                                                           slot,
1150                                                                                           erm->resname,
1151                                                                                           &datum,
1152                                                                                           &isNull))
1153                                                 elog(ERROR, "could not find junk \"%s\" column",
1154                                                          erm->resname);
1155
1156                                         /* shouldn't ever get a null result... */
1157                                         if (isNull)
1158                                                 elog(ERROR, "\"%s\" is NULL", erm->resname);
1159
1160                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1161
1162                                         if (erm->forUpdate)
1163                                                 lockmode = LockTupleExclusive;
1164                                         else
1165                                                 lockmode = LockTupleShared;
1166
1167                                         test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1168                                                                                    &update_ctid, &update_xmax,
1169                                                                                    estate->es_snapshot->curcid,
1170                                                                                    lockmode, erm->noWait);
1171                                         ReleaseBuffer(buffer);
1172                                         switch (test)
1173                                         {
1174                                                 case HeapTupleSelfUpdated:
1175                                                         /* treat it as deleted; do not process */
1176                                                         goto lnext;
1177
1178                                                 case HeapTupleMayBeUpdated:
1179                                                         break;
1180
1181                                                 case HeapTupleUpdated:
1182                                                         if (IsXactIsoLevelSerializable)
1183                                                                 ereport(ERROR,
1184                                                                  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1185                                                                   errmsg("could not serialize access due to concurrent update")));
1186                                                         if (!ItemPointerEquals(&update_ctid,
1187                                                                                                    &tuple.t_self))
1188                                                         {
1189                                                                 /* updated, so look at updated version */
1190                                                                 newSlot = EvalPlanQual(estate,
1191                                                                                                            erm->rti,
1192                                                                                                            &update_ctid,
1193                                                                                                            update_xmax,
1194                                                                                                            estate->es_snapshot->curcid);
1195                                                                 if (!TupIsNull(newSlot))
1196                                                                 {
1197                                                                         slot = planSlot = newSlot;
1198                                                                         estate->es_useEvalPlan = true;
1199                                                                         goto lmark;
1200                                                                 }
1201                                                         }
1202
1203                                                         /*
1204                                                          * if tuple was deleted or PlanQual failed for
1205                                                          * updated tuple - we must not return this tuple!
1206                                                          */
1207                                                         goto lnext;
1208
1209                                                 default:
1210                                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1211                                                                  test);
1212                                                         return NULL;
1213                                         }
1214                                 }
1215                         }
1216
1217                         /*
1218                          * Create a new "clean" tuple with all junk attributes removed.
1219                          * We don't need to do this for DELETE, however (there will
1220                          * in fact be no non-junk attributes in a DELETE!)
1221                          */
1222                         if (operation != CMD_DELETE)
1223                                 slot = ExecFilterJunk(junkfilter, slot);
1224                 }
1225
1226                 /*
1227                  * now that we have a tuple, do the appropriate thing with it.. either
1228                  * return it to the user, add it to a relation someplace, delete it
1229                  * from a relation, or modify some of its attributes.
1230                  */
1231                 switch (operation)
1232                 {
1233                         case CMD_SELECT:
1234                                 ExecSelect(slot, dest, estate);
1235                                 result = slot;
1236                                 break;
1237
1238                         case CMD_INSERT:
1239                                 ExecInsert(slot, tupleid, planSlot, dest, estate);
1240                                 result = NULL;
1241                                 break;
1242
1243                         case CMD_DELETE:
1244                                 ExecDelete(tupleid, planSlot, dest, estate);
1245                                 result = NULL;
1246                                 break;
1247
1248                         case CMD_UPDATE:
1249                                 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1250                                 result = NULL;
1251                                 break;
1252
1253                         default:
1254                                 elog(ERROR, "unrecognized operation code: %d",
1255                                          (int) operation);
1256                                 result = NULL;
1257                                 break;
1258                 }
1259
1260                 /*
1261                  * check our tuple count.. if we've processed the proper number then
1262                  * quit, else loop again and process more tuples.  Zero numberTuples
1263                  * means no limit.
1264                  */
1265                 current_tuple_count++;
1266                 if (numberTuples && numberTuples == current_tuple_count)
1267                         break;
1268         }
1269
1270         /*
1271          * Process AFTER EACH STATEMENT triggers
1272          */
1273         switch (operation)
1274         {
1275                 case CMD_UPDATE:
1276                         ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1277                         break;
1278                 case CMD_DELETE:
1279                         ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1280                         break;
1281                 case CMD_INSERT:
1282                         ExecASInsertTriggers(estate, estate->es_result_relation_info);
1283                         break;
1284                 default:
1285                         /* do nothing */
1286                         break;
1287         }
1288
1289         /*
1290          * here, result is either a slot containing a tuple in the case of a
1291          * SELECT or NULL otherwise.
1292          */
1293         return result;
1294 }
1295
1296 /* ----------------------------------------------------------------
1297  *              ExecSelect
1298  *
1299  *              SELECTs are easy.. we just pass the tuple to the appropriate
1300  *              output function.
1301  * ----------------------------------------------------------------
1302  */
1303 static void
1304 ExecSelect(TupleTableSlot *slot,
1305                    DestReceiver *dest,
1306                    EState *estate)
1307 {
1308         (*dest->receiveSlot) (slot, dest);
1309         IncrRetrieved();
1310         (estate->es_processed)++;
1311 }
1312
1313 /* ----------------------------------------------------------------
1314  *              ExecInsert
1315  *
1316  *              INSERTs are trickier.. we have to insert the tuple into
1317  *              the base relation and insert appropriate tuples into the
1318  *              index relations.
1319  * ----------------------------------------------------------------
1320  */
1321 static void
1322 ExecInsert(TupleTableSlot *slot,
1323                    ItemPointer tupleid,
1324                    TupleTableSlot *planSlot,
1325                    DestReceiver *dest,
1326                    EState *estate)
1327 {
1328         HeapTuple       tuple;
1329         ResultRelInfo *resultRelInfo;
1330         Relation        resultRelationDesc;
1331         Oid                     newId;
1332
1333         /*
1334          * get the heap tuple out of the tuple table slot, making sure we have a
1335          * writable copy
1336          */
1337         tuple = ExecMaterializeSlot(slot);
1338
1339         /*
1340          * get information on the (current) result relation
1341          */
1342         resultRelInfo = estate->es_result_relation_info;
1343         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1344
1345         /* BEFORE ROW INSERT Triggers */
1346         if (resultRelInfo->ri_TrigDesc &&
1347                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1348         {
1349                 HeapTuple       newtuple;
1350
1351                 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1352
1353                 if (newtuple == NULL)   /* "do nothing" */
1354                         return;
1355
1356                 if (newtuple != tuple)  /* modified by Trigger(s) */
1357                 {
1358                         /*
1359                          * Put the modified tuple into a slot for convenience of routines
1360                          * below.  We assume the tuple was allocated in per-tuple memory
1361                          * context, and therefore will go away by itself. The tuple table
1362                          * slot should not try to clear it.
1363                          */
1364                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1365
1366                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1367                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1368                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1369                         slot = newslot;
1370                         tuple = newtuple;
1371                 }
1372         }
1373
1374         /*
1375          * Check the constraints of the tuple
1376          */
1377         if (resultRelationDesc->rd_att->constr)
1378                 ExecConstraints(resultRelInfo, slot, estate);
1379
1380         /*
1381          * insert the tuple
1382          *
1383          * Note: heap_insert returns the tid (location) of the new tuple in the
1384          * t_self field.
1385          */
1386         newId = heap_insert(resultRelationDesc, tuple,
1387                                                 estate->es_snapshot->curcid,
1388                                                 true, true);
1389
1390         IncrAppended();
1391         (estate->es_processed)++;
1392         estate->es_lastoid = newId;
1393         setLastTid(&(tuple->t_self));
1394
1395         /*
1396          * insert index entries for tuple
1397          */
1398         if (resultRelInfo->ri_NumIndices > 0)
1399                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1400
1401         /* AFTER ROW INSERT Triggers */
1402         ExecARInsertTriggers(estate, resultRelInfo, tuple);
1403
1404         /* Process RETURNING if present */
1405         if (resultRelInfo->ri_projectReturning)
1406                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1407                                                          slot, planSlot, dest);
1408 }
1409
1410 /* ----------------------------------------------------------------
1411  *              ExecDelete
1412  *
1413  *              DELETE is like UPDATE, except that we delete the tuple and no
1414  *              index modifications are needed
1415  * ----------------------------------------------------------------
1416  */
1417 static void
1418 ExecDelete(ItemPointer tupleid,
1419                    TupleTableSlot *planSlot,
1420                    DestReceiver *dest,
1421                    EState *estate)
1422 {
1423         ResultRelInfo *resultRelInfo;
1424         Relation        resultRelationDesc;
1425         HTSU_Result result;
1426         ItemPointerData update_ctid;
1427         TransactionId update_xmax;
1428
1429         /*
1430          * get information on the (current) result relation
1431          */
1432         resultRelInfo = estate->es_result_relation_info;
1433         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1434
1435         /* BEFORE ROW DELETE Triggers */
1436         if (resultRelInfo->ri_TrigDesc &&
1437                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1438         {
1439                 bool            dodelete;
1440
1441                 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1442                                                                                 estate->es_snapshot->curcid);
1443
1444                 if (!dodelete)                  /* "do nothing" */
1445                         return;
1446         }
1447
1448         /*
1449          * delete the tuple
1450          *
1451          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1452          * the row to be deleted is visible to that snapshot, and throw a can't-
1453          * serialize error if not.      This is a special-case behavior needed for
1454          * referential integrity updates in serializable transactions.
1455          */
1456 ldelete:;
1457         result = heap_delete(resultRelationDesc, tupleid,
1458                                                  &update_ctid, &update_xmax,
1459                                                  estate->es_snapshot->curcid,
1460                                                  estate->es_crosscheck_snapshot,
1461                                                  true /* wait for commit */ );
1462         switch (result)
1463         {
1464                 case HeapTupleSelfUpdated:
1465                         /* already deleted by self; nothing to do */
1466                         return;
1467
1468                 case HeapTupleMayBeUpdated:
1469                         break;
1470
1471                 case HeapTupleUpdated:
1472                         if (IsXactIsoLevelSerializable)
1473                                 ereport(ERROR,
1474                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1475                                                  errmsg("could not serialize access due to concurrent update")));
1476                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1477                         {
1478                                 TupleTableSlot *epqslot;
1479
1480                                 epqslot = EvalPlanQual(estate,
1481                                                                            resultRelInfo->ri_RangeTableIndex,
1482                                                                            &update_ctid,
1483                                                                            update_xmax,
1484                                                                            estate->es_snapshot->curcid);
1485                                 if (!TupIsNull(epqslot))
1486                                 {
1487                                         *tupleid = update_ctid;
1488                                         goto ldelete;
1489                                 }
1490                         }
1491                         /* tuple already deleted; nothing to do */
1492                         return;
1493
1494                 default:
1495                         elog(ERROR, "unrecognized heap_delete status: %u", result);
1496                         return;
1497         }
1498
1499         IncrDeleted();
1500         (estate->es_processed)++;
1501
1502         /*
1503          * Note: Normally one would think that we have to delete index tuples
1504          * associated with the heap tuple now...
1505          *
1506          * ... but in POSTGRES, we have no need to do this because VACUUM will
1507          * take care of it later.  We can't delete index tuples immediately
1508          * anyway, since the tuple is still visible to other transactions.
1509          */
1510
1511         /* AFTER ROW DELETE Triggers */
1512         ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1513
1514         /* Process RETURNING if present */
1515         if (resultRelInfo->ri_projectReturning)
1516         {
1517                 /*
1518                  * We have to put the target tuple into a slot, which means
1519                  * first we gotta fetch it.  We can use the trigger tuple slot.
1520                  */
1521                 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1522                 HeapTupleData deltuple;
1523                 Buffer          delbuffer;
1524
1525                 deltuple.t_self = *tupleid;
1526                 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1527                                                 &deltuple, &delbuffer, false, NULL))
1528                         elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1529
1530                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1531                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1532                 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1533
1534                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1535                                                          slot, planSlot, dest);
1536
1537                 ExecClearTuple(slot);
1538                 ReleaseBuffer(delbuffer);
1539         }
1540 }
1541
1542 /* ----------------------------------------------------------------
1543  *              ExecUpdate
1544  *
1545  *              note: we can't run UPDATE queries with transactions
1546  *              off because UPDATEs are actually INSERTs and our
1547  *              scan will mistakenly loop forever, updating the tuple
1548  *              it just inserted..      This should be fixed but until it
1549  *              is, we don't want to get stuck in an infinite loop
1550  *              which corrupts your database..
1551  * ----------------------------------------------------------------
1552  */
1553 static void
1554 ExecUpdate(TupleTableSlot *slot,
1555                    ItemPointer tupleid,
1556                    TupleTableSlot *planSlot,
1557                    DestReceiver *dest,
1558                    EState *estate)
1559 {
1560         HeapTuple       tuple;
1561         ResultRelInfo *resultRelInfo;
1562         Relation        resultRelationDesc;
1563         HTSU_Result result;
1564         ItemPointerData update_ctid;
1565         TransactionId update_xmax;
1566
1567         /*
1568          * abort the operation if not running transactions
1569          */
1570         if (IsBootstrapProcessingMode())
1571                 elog(ERROR, "cannot UPDATE during bootstrap");
1572
1573         /*
1574          * get the heap tuple out of the tuple table slot, making sure we have a
1575          * writable copy
1576          */
1577         tuple = ExecMaterializeSlot(slot);
1578
1579         /*
1580          * get information on the (current) result relation
1581          */
1582         resultRelInfo = estate->es_result_relation_info;
1583         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1584
1585         /* BEFORE ROW UPDATE Triggers */
1586         if (resultRelInfo->ri_TrigDesc &&
1587                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1588         {
1589                 HeapTuple       newtuple;
1590
1591                 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1592                                                                                 tupleid, tuple,
1593                                                                                 estate->es_snapshot->curcid);
1594
1595                 if (newtuple == NULL)   /* "do nothing" */
1596                         return;
1597
1598                 if (newtuple != tuple)  /* modified by Trigger(s) */
1599                 {
1600                         /*
1601                          * Put the modified tuple into a slot for convenience of routines
1602                          * below.  We assume the tuple was allocated in per-tuple memory
1603                          * context, and therefore will go away by itself. The tuple table
1604                          * slot should not try to clear it.
1605                          */
1606                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1607
1608                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1609                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1610                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1611                         slot = newslot;
1612                         tuple = newtuple;
1613                 }
1614         }
1615
1616         /*
1617          * Check the constraints of the tuple
1618          *
1619          * If we generate a new candidate tuple after EvalPlanQual testing, we
1620          * must loop back here and recheck constraints.  (We don't need to redo
1621          * triggers, however.  If there are any BEFORE triggers then trigger.c
1622          * will have done heap_lock_tuple to lock the correct tuple, so there's no
1623          * need to do them again.)
1624          */
1625 lreplace:;
1626         if (resultRelationDesc->rd_att->constr)
1627                 ExecConstraints(resultRelInfo, slot, estate);
1628
1629         /*
1630          * replace the heap tuple
1631          *
1632          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1633          * the row to be updated is visible to that snapshot, and throw a can't-
1634          * serialize error if not.      This is a special-case behavior needed for
1635          * referential integrity updates in serializable transactions.
1636          */
1637         result = heap_update(resultRelationDesc, tupleid, tuple,
1638                                                  &update_ctid, &update_xmax,
1639                                                  estate->es_snapshot->curcid,
1640                                                  estate->es_crosscheck_snapshot,
1641                                                  true /* wait for commit */ );
1642         switch (result)
1643         {
1644                 case HeapTupleSelfUpdated:
1645                         /* already deleted by self; nothing to do */
1646                         return;
1647
1648                 case HeapTupleMayBeUpdated:
1649                         break;
1650
1651                 case HeapTupleUpdated:
1652                         if (IsXactIsoLevelSerializable)
1653                                 ereport(ERROR,
1654                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1655                                                  errmsg("could not serialize access due to concurrent update")));
1656                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1657                         {
1658                                 TupleTableSlot *epqslot;
1659
1660                                 epqslot = EvalPlanQual(estate,
1661                                                                            resultRelInfo->ri_RangeTableIndex,
1662                                                                            &update_ctid,
1663                                                                            update_xmax,
1664                                                                            estate->es_snapshot->curcid);
1665                                 if (!TupIsNull(epqslot))
1666                                 {
1667                                         *tupleid = update_ctid;
1668                                         slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1669                                         tuple = ExecMaterializeSlot(slot);
1670                                         goto lreplace;
1671                                 }
1672                         }
1673                         /* tuple already deleted; nothing to do */
1674                         return;
1675
1676                 default:
1677                         elog(ERROR, "unrecognized heap_update status: %u", result);
1678                         return;
1679         }
1680
1681         IncrReplaced();
1682         (estate->es_processed)++;
1683
1684         /*
1685          * Note: instead of having to update the old index tuples associated with
1686          * the heap tuple, all we do is form and insert new index tuples. This is
1687          * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1688          * deletion is done later by VACUUM (see notes in ExecDelete).  All we do
1689          * here is insert new index tuples.  -cim 9/27/89
1690          */
1691
1692         /*
1693          * insert index entries for tuple
1694          *
1695          * Note: heap_update returns the tid (location) of the new tuple in the
1696          * t_self field.
1697          */
1698         if (resultRelInfo->ri_NumIndices > 0)
1699                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1700
1701         /* AFTER ROW UPDATE Triggers */
1702         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1703
1704         /* Process RETURNING if present */
1705         if (resultRelInfo->ri_projectReturning)
1706                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1707                                                          slot, planSlot, dest);
1708 }
1709
1710 /*
1711  * ExecRelCheck --- check that tuple meets constraints for result relation
1712  */
1713 static const char *
1714 ExecRelCheck(ResultRelInfo *resultRelInfo,
1715                          TupleTableSlot *slot, EState *estate)
1716 {
1717         Relation        rel = resultRelInfo->ri_RelationDesc;
1718         int                     ncheck = rel->rd_att->constr->num_check;
1719         ConstrCheck *check = rel->rd_att->constr->check;
1720         ExprContext *econtext;
1721         MemoryContext oldContext;
1722         List       *qual;
1723         int                     i;
1724
1725         /*
1726          * If first time through for this result relation, build expression
1727          * nodetrees for rel's constraint expressions.  Keep them in the per-query
1728          * memory context so they'll survive throughout the query.
1729          */
1730         if (resultRelInfo->ri_ConstraintExprs == NULL)
1731         {
1732                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1733                 resultRelInfo->ri_ConstraintExprs =
1734                         (List **) palloc(ncheck * sizeof(List *));
1735                 for (i = 0; i < ncheck; i++)
1736                 {
1737                         /* ExecQual wants implicit-AND form */
1738                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
1739                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
1740                                 ExecPrepareExpr((Expr *) qual, estate);
1741                 }
1742                 MemoryContextSwitchTo(oldContext);
1743         }
1744
1745         /*
1746          * We will use the EState's per-tuple context for evaluating constraint
1747          * expressions (creating it if it's not already there).
1748          */
1749         econtext = GetPerTupleExprContext(estate);
1750
1751         /* Arrange for econtext's scan tuple to be the tuple under test */
1752         econtext->ecxt_scantuple = slot;
1753
1754         /* And evaluate the constraints */
1755         for (i = 0; i < ncheck; i++)
1756         {
1757                 qual = resultRelInfo->ri_ConstraintExprs[i];
1758
1759                 /*
1760                  * NOTE: SQL92 specifies that a NULL result from a constraint
1761                  * expression is not to be treated as a failure.  Therefore, tell
1762                  * ExecQual to return TRUE for NULL.
1763                  */
1764                 if (!ExecQual(qual, econtext, true))
1765                         return check[i].ccname;
1766         }
1767
1768         /* NULL result means no error */
1769         return NULL;
1770 }
1771
1772 void
1773 ExecConstraints(ResultRelInfo *resultRelInfo,
1774                                 TupleTableSlot *slot, EState *estate)
1775 {
1776         Relation        rel = resultRelInfo->ri_RelationDesc;
1777         TupleConstr *constr = rel->rd_att->constr;
1778
1779         Assert(constr);
1780
1781         if (constr->has_not_null)
1782         {
1783                 int                     natts = rel->rd_att->natts;
1784                 int                     attrChk;
1785
1786                 for (attrChk = 1; attrChk <= natts; attrChk++)
1787                 {
1788                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1789                                 slot_attisnull(slot, attrChk))
1790                                 ereport(ERROR,
1791                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1792                                                  errmsg("null value in column \"%s\" violates not-null constraint",
1793                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1794                 }
1795         }
1796
1797         if (constr->num_check > 0)
1798         {
1799                 const char *failed;
1800
1801                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1802                         ereport(ERROR,
1803                                         (errcode(ERRCODE_CHECK_VIOLATION),
1804                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1805                                                         RelationGetRelationName(rel), failed)));
1806         }
1807 }
1808
1809 /*
1810  * ExecProcessReturning --- evaluate a RETURNING list and send to dest
1811  *
1812  * projectReturning: RETURNING projection info for current result rel
1813  * tupleSlot: slot holding tuple actually inserted/updated/deleted
1814  * planSlot: slot holding tuple returned by top plan node
1815  * dest: where to send the output
1816  */
1817 static void
1818 ExecProcessReturning(ProjectionInfo     *projectReturning,
1819                                          TupleTableSlot *tupleSlot,
1820                                          TupleTableSlot *planSlot,
1821                                          DestReceiver *dest)
1822 {
1823         ExprContext             *econtext = projectReturning->pi_exprContext;
1824         TupleTableSlot  *retSlot;
1825
1826         /*
1827          * Reset per-tuple memory context to free any expression evaluation
1828          * storage allocated in the previous cycle.
1829          */
1830         ResetExprContext(econtext);
1831
1832         /* Make tuple and any needed join variables available to ExecProject */
1833         econtext->ecxt_scantuple = tupleSlot;
1834         econtext->ecxt_outertuple = planSlot;
1835
1836         /* Compute the RETURNING expressions */
1837         retSlot = ExecProject(projectReturning, NULL);
1838
1839         /* Send to dest */
1840         (*dest->receiveSlot) (retSlot, dest);
1841
1842         ExecClearTuple(retSlot);
1843 }
1844
1845 /*
1846  * Check a modified tuple to see if we want to process its updated version
1847  * under READ COMMITTED rules.
1848  *
1849  * See backend/executor/README for some info about how this works.
1850  *
1851  *      estate - executor state data
1852  *      rti - rangetable index of table containing tuple
1853  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1854  *      priorXmax - t_xmax from the outdated tuple
1855  *      curCid - command ID of current command of my transaction
1856  *
1857  * *tid is also an output parameter: it's modified to hold the TID of the
1858  * latest version of the tuple (note this may be changed even on failure)
1859  *
1860  * Returns a slot containing the new candidate update/delete tuple, or
1861  * NULL if we determine we shouldn't process the row.
1862  */
1863 TupleTableSlot *
1864 EvalPlanQual(EState *estate, Index rti,
1865                          ItemPointer tid, TransactionId priorXmax, CommandId curCid)
1866 {
1867         evalPlanQual *epq;
1868         EState     *epqstate;
1869         Relation        relation;
1870         HeapTupleData tuple;
1871         HeapTuple       copyTuple = NULL;
1872         bool            endNode;
1873
1874         Assert(rti != 0);
1875
1876         /*
1877          * find relation containing target tuple
1878          */
1879         if (estate->es_result_relation_info != NULL &&
1880                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1881                 relation = estate->es_result_relation_info->ri_RelationDesc;
1882         else
1883         {
1884                 ListCell   *l;
1885
1886                 relation = NULL;
1887                 foreach(l, estate->es_rowMarks)
1888                 {
1889                         if (((ExecRowMark *) lfirst(l))->rti == rti)
1890                         {
1891                                 relation = ((ExecRowMark *) lfirst(l))->relation;
1892                                 break;
1893                         }
1894                 }
1895                 if (relation == NULL)
1896                         elog(ERROR, "could not find RowMark for RT index %u", rti);
1897         }
1898
1899         /*
1900          * fetch tid tuple
1901          *
1902          * Loop here to deal with updated or busy tuples
1903          */
1904         tuple.t_self = *tid;
1905         for (;;)
1906         {
1907                 Buffer          buffer;
1908
1909                 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, true, NULL))
1910                 {
1911                         /*
1912                          * If xmin isn't what we're expecting, the slot must have been
1913                          * recycled and reused for an unrelated tuple.  This implies that
1914                          * the latest version of the row was deleted, so we need do
1915                          * nothing.  (Should be safe to examine xmin without getting
1916                          * buffer's content lock, since xmin never changes in an existing
1917                          * tuple.)
1918                          */
1919                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1920                                                                          priorXmax))
1921                         {
1922                                 ReleaseBuffer(buffer);
1923                                 return NULL;
1924                         }
1925
1926                         /* otherwise xmin should not be dirty... */
1927                         if (TransactionIdIsValid(SnapshotDirty->xmin))
1928                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1929
1930                         /*
1931                          * If tuple is being updated by other transaction then we have to
1932                          * wait for its commit/abort.
1933                          */
1934                         if (TransactionIdIsValid(SnapshotDirty->xmax))
1935                         {
1936                                 ReleaseBuffer(buffer);
1937                                 XactLockTableWait(SnapshotDirty->xmax);
1938                                 continue;               /* loop back to repeat heap_fetch */
1939                         }
1940
1941                         /*
1942                          * If tuple was inserted by our own transaction, we have to check
1943                          * cmin against curCid: cmin >= curCid means our command cannot
1944                          * see the tuple, so we should ignore it.  Without this we are
1945                          * open to the "Halloween problem" of indefinitely re-updating
1946                          * the same tuple.  (We need not check cmax because
1947                          * HeapTupleSatisfiesDirty will consider a tuple deleted by
1948                          * our transaction dead, regardless of cmax.)  We just checked
1949                          * that priorXmax == xmin, so we can test that variable instead
1950                          * of doing HeapTupleHeaderGetXmin again.
1951                          */
1952                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1953                                 HeapTupleHeaderGetCmin(tuple.t_data) >= curCid)
1954                         {
1955                                 ReleaseBuffer(buffer);
1956                                 return NULL;
1957                         }
1958
1959                         /*
1960                          * We got tuple - now copy it for use by recheck query.
1961                          */
1962                         copyTuple = heap_copytuple(&tuple);
1963                         ReleaseBuffer(buffer);
1964                         break;
1965                 }
1966
1967                 /*
1968                  * If the referenced slot was actually empty, the latest version of
1969                  * the row must have been deleted, so we need do nothing.
1970                  */
1971                 if (tuple.t_data == NULL)
1972                 {
1973                         ReleaseBuffer(buffer);
1974                         return NULL;
1975                 }
1976
1977                 /*
1978                  * As above, if xmin isn't what we're expecting, do nothing.
1979                  */
1980                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1981                                                                  priorXmax))
1982                 {
1983                         ReleaseBuffer(buffer);
1984                         return NULL;
1985                 }
1986
1987                 /*
1988                  * If we get here, the tuple was found but failed SnapshotDirty.
1989                  * Assuming the xmin is either a committed xact or our own xact (as it
1990                  * certainly should be if we're trying to modify the tuple), this must
1991                  * mean that the row was updated or deleted by either a committed xact
1992                  * or our own xact.  If it was deleted, we can ignore it; if it was
1993                  * updated then chain up to the next version and repeat the whole
1994                  * test.
1995                  *
1996                  * As above, it should be safe to examine xmax and t_ctid without the
1997                  * buffer content lock, because they can't be changing.
1998                  */
1999                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2000                 {
2001                         /* deleted, so forget about it */
2002                         ReleaseBuffer(buffer);
2003                         return NULL;
2004                 }
2005
2006                 /* updated, so look at the updated row */
2007                 tuple.t_self = tuple.t_data->t_ctid;
2008                 /* updated row should have xmin matching this xmax */
2009                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2010                 ReleaseBuffer(buffer);
2011                 /* loop back to fetch next in chain */
2012         }
2013
2014         /*
2015          * For UPDATE/DELETE we have to return tid of actual row we're executing
2016          * PQ for.
2017          */
2018         *tid = tuple.t_self;
2019
2020         /*
2021          * Need to run a recheck subquery.      Find or create a PQ stack entry.
2022          */
2023         epq = estate->es_evalPlanQual;
2024         endNode = true;
2025
2026         if (epq != NULL && epq->rti == 0)
2027         {
2028                 /* Top PQ stack entry is idle, so re-use it */
2029                 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2030                 epq->rti = rti;
2031                 endNode = false;
2032         }
2033
2034         /*
2035          * If this is request for another RTE - Ra, - then we have to check wasn't
2036          * PlanQual requested for Ra already and if so then Ra' row was updated
2037          * again and we have to re-start old execution for Ra and forget all what
2038          * we done after Ra was suspended. Cool? -:))
2039          */
2040         if (epq != NULL && epq->rti != rti &&
2041                 epq->estate->es_evTuple[rti - 1] != NULL)
2042         {
2043                 do
2044                 {
2045                         evalPlanQual *oldepq;
2046
2047                         /* stop execution */
2048                         EvalPlanQualStop(epq);
2049                         /* pop previous PlanQual from the stack */
2050                         oldepq = epq->next;
2051                         Assert(oldepq && oldepq->rti != 0);
2052                         /* push current PQ to freePQ stack */
2053                         oldepq->free = epq;
2054                         epq = oldepq;
2055                         estate->es_evalPlanQual = epq;
2056                 } while (epq->rti != rti);
2057         }
2058
2059         /*
2060          * If we are requested for another RTE then we have to suspend execution
2061          * of current PlanQual and start execution for new one.
2062          */
2063         if (epq == NULL || epq->rti != rti)
2064         {
2065                 /* try to reuse plan used previously */
2066                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2067
2068                 if (newepq == NULL)             /* first call or freePQ stack is empty */
2069                 {
2070                         newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2071                         newepq->free = NULL;
2072                         newepq->estate = NULL;
2073                         newepq->planstate = NULL;
2074                 }
2075                 else
2076                 {
2077                         /* recycle previously used PlanQual */
2078                         Assert(newepq->estate == NULL);
2079                         epq->free = NULL;
2080                 }
2081                 /* push current PQ to the stack */
2082                 newepq->next = epq;
2083                 epq = newepq;
2084                 estate->es_evalPlanQual = epq;
2085                 epq->rti = rti;
2086                 endNode = false;
2087         }
2088
2089         Assert(epq->rti == rti);
2090
2091         /*
2092          * Ok - we're requested for the same RTE.  Unfortunately we still have to
2093          * end and restart execution of the plan, because ExecReScan wouldn't
2094          * ensure that upper plan nodes would reset themselves.  We could make
2095          * that work if insertion of the target tuple were integrated with the
2096          * Param mechanism somehow, so that the upper plan nodes know that their
2097          * children's outputs have changed.
2098          *
2099          * Note that the stack of free evalPlanQual nodes is quite useless at the
2100          * moment, since it only saves us from pallocing/releasing the
2101          * evalPlanQual nodes themselves.  But it will be useful once we implement
2102          * ReScan instead of end/restart for re-using PlanQual nodes.
2103          */
2104         if (endNode)
2105         {
2106                 /* stop execution */
2107                 EvalPlanQualStop(epq);
2108         }
2109
2110         /*
2111          * Initialize new recheck query.
2112          *
2113          * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2114          * instead copy down changeable state from the top plan (including
2115          * es_result_relation_info, es_junkFilter) and reset locally changeable
2116          * state in the epq (including es_param_exec_vals, es_evTupleNull).
2117          */
2118         EvalPlanQualStart(epq, estate, epq->next);
2119
2120         /*
2121          * free old RTE' tuple, if any, and store target tuple where relation's
2122          * scan node will see it
2123          */
2124         epqstate = epq->estate;
2125         if (epqstate->es_evTuple[rti - 1] != NULL)
2126                 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2127         epqstate->es_evTuple[rti - 1] = copyTuple;
2128
2129         return EvalPlanQualNext(estate);
2130 }
2131
2132 static TupleTableSlot *
2133 EvalPlanQualNext(EState *estate)
2134 {
2135         evalPlanQual *epq = estate->es_evalPlanQual;
2136         MemoryContext oldcontext;
2137         TupleTableSlot *slot;
2138
2139         Assert(epq->rti != 0);
2140
2141 lpqnext:;
2142         oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2143         slot = ExecProcNode(epq->planstate);
2144         MemoryContextSwitchTo(oldcontext);
2145
2146         /*
2147          * No more tuples for this PQ. Continue previous one.
2148          */
2149         if (TupIsNull(slot))
2150         {
2151                 evalPlanQual *oldepq;
2152
2153                 /* stop execution */
2154                 EvalPlanQualStop(epq);
2155                 /* pop old PQ from the stack */
2156                 oldepq = epq->next;
2157                 if (oldepq == NULL)
2158                 {
2159                         /* this is the first (oldest) PQ - mark as free */
2160                         epq->rti = 0;
2161                         estate->es_useEvalPlan = false;
2162                         /* and continue Query execution */
2163                         return NULL;
2164                 }
2165                 Assert(oldepq->rti != 0);
2166                 /* push current PQ to freePQ stack */
2167                 oldepq->free = epq;
2168                 epq = oldepq;
2169                 estate->es_evalPlanQual = epq;
2170                 goto lpqnext;
2171         }
2172
2173         return slot;
2174 }
2175
2176 static void
2177 EndEvalPlanQual(EState *estate)
2178 {
2179         evalPlanQual *epq = estate->es_evalPlanQual;
2180
2181         if (epq->rti == 0)                      /* plans already shutdowned */
2182         {
2183                 Assert(epq->next == NULL);
2184                 return;
2185         }
2186
2187         for (;;)
2188         {
2189                 evalPlanQual *oldepq;
2190
2191                 /* stop execution */
2192                 EvalPlanQualStop(epq);
2193                 /* pop old PQ from the stack */
2194                 oldepq = epq->next;
2195                 if (oldepq == NULL)
2196                 {
2197                         /* this is the first (oldest) PQ - mark as free */
2198                         epq->rti = 0;
2199                         estate->es_useEvalPlan = false;
2200                         break;
2201                 }
2202                 Assert(oldepq->rti != 0);
2203                 /* push current PQ to freePQ stack */
2204                 oldepq->free = epq;
2205                 epq = oldepq;
2206                 estate->es_evalPlanQual = epq;
2207         }
2208 }
2209
2210 /*
2211  * Start execution of one level of PlanQual.
2212  *
2213  * This is a cut-down version of ExecutorStart(): we copy some state from
2214  * the top-level estate rather than initializing it fresh.
2215  */
2216 static void
2217 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2218 {
2219         EState     *epqstate;
2220         int                     rtsize;
2221         MemoryContext oldcontext;
2222
2223         rtsize = list_length(estate->es_range_table);
2224
2225         epq->estate = epqstate = CreateExecutorState();
2226
2227         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2228
2229         /*
2230          * The epqstates share the top query's copy of unchanging state such as
2231          * the snapshot, rangetable, result-rel info, and external Param info.
2232          * They need their own copies of local state, including a tuple table,
2233          * es_param_exec_vals, etc.
2234          */
2235         epqstate->es_direction = ForwardScanDirection;
2236         epqstate->es_snapshot = estate->es_snapshot;
2237         epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2238         epqstate->es_range_table = estate->es_range_table;
2239         epqstate->es_result_relations = estate->es_result_relations;
2240         epqstate->es_num_result_relations = estate->es_num_result_relations;
2241         epqstate->es_result_relation_info = estate->es_result_relation_info;
2242         epqstate->es_junkFilter = estate->es_junkFilter;
2243         epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2244         epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2245         epqstate->es_param_list_info = estate->es_param_list_info;
2246         if (estate->es_topPlan->nParamExec > 0)
2247                 epqstate->es_param_exec_vals = (ParamExecData *)
2248                         palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2249         epqstate->es_rowMarks = estate->es_rowMarks;
2250         epqstate->es_instrument = estate->es_instrument;
2251         epqstate->es_select_into = estate->es_select_into;
2252         epqstate->es_into_oids = estate->es_into_oids;
2253         epqstate->es_topPlan = estate->es_topPlan;
2254
2255         /*
2256          * Each epqstate must have its own es_evTupleNull state, but all the stack
2257          * entries share es_evTuple state.      This allows sub-rechecks to inherit
2258          * the value being examined by an outer recheck.
2259          */
2260         epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2261         if (priorepq == NULL)
2262                 /* first PQ stack entry */
2263                 epqstate->es_evTuple = (HeapTuple *)
2264                         palloc0(rtsize * sizeof(HeapTuple));
2265         else
2266                 /* later stack entries share the same storage */
2267                 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2268
2269         epqstate->es_tupleTable =
2270                 ExecCreateTupleTable(estate->es_tupleTable->size);
2271
2272         epq->planstate = ExecInitNode(estate->es_topPlan, epqstate, 0);
2273
2274         MemoryContextSwitchTo(oldcontext);
2275 }
2276
2277 /*
2278  * End execution of one level of PlanQual.
2279  *
2280  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2281  * of the normal cleanup, but *not* close result relations (which we are
2282  * just sharing from the outer query).
2283  */
2284 static void
2285 EvalPlanQualStop(evalPlanQual *epq)
2286 {
2287         EState     *epqstate = epq->estate;
2288         MemoryContext oldcontext;
2289
2290         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2291
2292         ExecEndNode(epq->planstate);
2293
2294         ExecDropTupleTable(epqstate->es_tupleTable, true);
2295         epqstate->es_tupleTable = NULL;
2296
2297         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2298         {
2299                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2300                 epqstate->es_evTuple[epq->rti - 1] = NULL;
2301         }
2302
2303         MemoryContextSwitchTo(oldcontext);
2304
2305         FreeExecutorState(epqstate);
2306
2307         epq->estate = NULL;
2308         epq->planstate = NULL;
2309 }
2310
2311
2312 /*
2313  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2314  *
2315  * We implement SELECT INTO by diverting SELECT's normal output with
2316  * a specialized DestReceiver type.
2317  *
2318  * TODO: remove some of the INTO-specific cruft from EState, and keep
2319  * it in the DestReceiver instead.
2320  */
2321
2322 typedef struct
2323 {
2324         DestReceiver pub;                       /* publicly-known function pointers */
2325         EState     *estate;                     /* EState we are working with */
2326 } DR_intorel;
2327
2328 /*
2329  * OpenIntoRel --- actually create the SELECT INTO target relation
2330  *
2331  * This also replaces QueryDesc->dest with the special DestReceiver for
2332  * SELECT INTO.  We assume that the correct result tuple type has already
2333  * been placed in queryDesc->tupDesc.
2334  */
2335 static void
2336 OpenIntoRel(QueryDesc *queryDesc)
2337 {
2338         Query      *parseTree = queryDesc->parsetree;
2339         EState     *estate = queryDesc->estate;
2340         Relation        intoRelationDesc;
2341         char       *intoName;
2342         Oid                     namespaceId;
2343         Oid                     tablespaceId;
2344         Datum           reloptions;
2345         AclResult       aclresult;
2346         Oid                     intoRelationId;
2347         TupleDesc       tupdesc;
2348         DR_intorel *myState;
2349
2350         /*
2351          * Check consistency of arguments
2352          */
2353         if (parseTree->intoOnCommit != ONCOMMIT_NOOP && !parseTree->into->istemp)
2354                 ereport(ERROR,
2355                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2356                                  errmsg("ON COMMIT can only be used on temporary tables")));
2357
2358         /*
2359          * Find namespace to create in, check its permissions
2360          */
2361         intoName = parseTree->into->relname;
2362         namespaceId = RangeVarGetCreationNamespace(parseTree->into);
2363
2364         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2365                                                                           ACL_CREATE);
2366         if (aclresult != ACLCHECK_OK)
2367                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2368                                            get_namespace_name(namespaceId));
2369
2370         /*
2371          * Select tablespace to use.  If not specified, use default_tablespace
2372          * (which may in turn default to database's default).
2373          */
2374         if (parseTree->intoTableSpaceName)
2375         {
2376                 tablespaceId = get_tablespace_oid(parseTree->intoTableSpaceName);
2377                 if (!OidIsValid(tablespaceId))
2378                         ereport(ERROR,
2379                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
2380                                          errmsg("tablespace \"%s\" does not exist",
2381                                                         parseTree->intoTableSpaceName)));
2382         } else
2383         {
2384                 tablespaceId = GetDefaultTablespace();
2385                 /* note InvalidOid is OK in this case */
2386         }
2387
2388         /* Check permissions except when using the database's default space */
2389         if (OidIsValid(tablespaceId))
2390         {
2391                 AclResult       aclresult;
2392
2393                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2394                                                                                    ACL_CREATE);
2395
2396                 if (aclresult != ACLCHECK_OK)
2397                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2398                                                    get_tablespace_name(tablespaceId));
2399         }
2400
2401         /* Parse and validate any reloptions */
2402         reloptions = transformRelOptions((Datum) 0,
2403                                                                          parseTree->intoOptions,
2404                                                                          true,
2405                                                                          false);
2406         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2407
2408         /* have to copy the actual tupdesc to get rid of any constraints */
2409         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2410
2411         /* Now we can actually create the new relation */
2412         intoRelationId = heap_create_with_catalog(intoName,
2413                                                                                           namespaceId,
2414                                                                                           tablespaceId,
2415                                                                                           InvalidOid,
2416                                                                                           GetUserId(),
2417                                                                                           tupdesc,
2418                                                                                           RELKIND_RELATION,
2419                                                                                           false,
2420                                                                                           true,
2421                                                                                           0,
2422                                                                                           parseTree->intoOnCommit,
2423                                                                                           reloptions,
2424                                                                                           allowSystemTableMods);
2425
2426         FreeTupleDesc(tupdesc);
2427
2428         /*
2429          * Advance command counter so that the newly-created relation's
2430          * catalog tuples will be visible to heap_open.
2431          */
2432         CommandCounterIncrement();
2433
2434         /*
2435          * If necessary, create a TOAST table for the INTO relation. Note that
2436          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so
2437          * that the TOAST table will be visible for insertion.
2438          */
2439         AlterTableCreateToastTable(intoRelationId);
2440
2441         /*
2442          * And open the constructed table for writing.
2443          */
2444         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2445
2446         /* use_wal off requires rd_targblock be initially invalid */
2447         Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2448
2449         /*
2450          * We can skip WAL-logging the insertions, unless PITR is in use.
2451          *
2452          * Note that for a non-temp INTO table, this is safe only because we
2453          * know that the catalog changes above will have been WAL-logged, and
2454          * so RecordTransactionCommit will think it needs to WAL-log the
2455          * eventual transaction commit.  Else the commit might be lost, even
2456          * though all the data is safely fsync'd ...
2457          */
2458         estate->es_into_relation_use_wal = XLogArchivingActive();
2459         estate->es_into_relation_descriptor = intoRelationDesc;
2460
2461         /*
2462          * Now replace the query's DestReceiver with one for SELECT INTO
2463          */
2464         queryDesc->dest = CreateDestReceiver(DestIntoRel, NULL);
2465         myState = (DR_intorel *) queryDesc->dest;
2466         Assert(myState->pub.mydest == DestIntoRel);
2467         myState->estate = estate;
2468 }
2469
2470 /*
2471  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2472  */
2473 static void
2474 CloseIntoRel(QueryDesc *queryDesc)
2475 {
2476         EState     *estate = queryDesc->estate;
2477
2478         /* OpenIntoRel might never have gotten called */
2479         if (estate->es_into_relation_descriptor)
2480         {
2481                 /*
2482                  * If we skipped using WAL, and it's not a temp relation, we must
2483                  * force the relation down to disk before it's safe to commit the
2484                  * transaction.  This requires forcing out any dirty buffers and then
2485                  * doing a forced fsync.
2486                  */
2487                 if (!estate->es_into_relation_use_wal &&
2488                         !estate->es_into_relation_descriptor->rd_istemp)
2489                 {
2490                         FlushRelationBuffers(estate->es_into_relation_descriptor);
2491                         /* FlushRelationBuffers will have opened rd_smgr */
2492                         smgrimmedsync(estate->es_into_relation_descriptor->rd_smgr);
2493                 }
2494
2495                 /* close rel, but keep lock until commit */
2496                 heap_close(estate->es_into_relation_descriptor, NoLock);
2497
2498                 estate->es_into_relation_descriptor = NULL;
2499         }
2500 }
2501
2502 /*
2503  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2504  *
2505  * Since CreateDestReceiver doesn't accept the parameters we'd need,
2506  * we just leave the private fields empty here.  OpenIntoRel will
2507  * fill them in.
2508  */
2509 DestReceiver *
2510 CreateIntoRelDestReceiver(void)
2511 {
2512         DR_intorel *self = (DR_intorel *) palloc(sizeof(DR_intorel));
2513
2514         self->pub.receiveSlot = intorel_receive;
2515         self->pub.rStartup = intorel_startup;
2516         self->pub.rShutdown = intorel_shutdown;
2517         self->pub.rDestroy = intorel_destroy;
2518         self->pub.mydest = DestIntoRel;
2519
2520         self->estate = NULL;
2521
2522         return (DestReceiver *) self;
2523 }
2524
2525 /*
2526  * intorel_startup --- executor startup
2527  */
2528 static void
2529 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2530 {
2531         /* no-op */
2532 }
2533
2534 /*
2535  * intorel_receive --- receive one tuple
2536  */
2537 static void
2538 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2539 {
2540         DR_intorel *myState = (DR_intorel *) self;
2541         EState     *estate = myState->estate;
2542         HeapTuple       tuple;
2543
2544         tuple = ExecCopySlotTuple(slot);
2545
2546         heap_insert(estate->es_into_relation_descriptor,
2547                                 tuple,
2548                                 estate->es_snapshot->curcid,
2549                                 estate->es_into_relation_use_wal,
2550                                 false);                 /* never any point in using FSM */
2551
2552         /* We know this is a newly created relation, so there are no indexes */
2553
2554         heap_freetuple(tuple);
2555
2556         IncrAppended();
2557 }
2558
2559 /*
2560  * intorel_shutdown --- executor end
2561  */
2562 static void
2563 intorel_shutdown(DestReceiver *self)
2564 {
2565         /* no-op */
2566 }
2567
2568 /*
2569  * intorel_destroy --- release DestReceiver object
2570  */
2571 static void
2572 intorel_destroy(DestReceiver *self)
2573 {
2574         pfree(self);
2575 }