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