OSDN Git Service

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