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