]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
Clean up per-tuple memory leaks in trigger firing and plpgsql
[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 and the execution state is required
16  *       as arguments
17  *
18  *      ExecutorStart() must be called at the beginning of any execution of any
19  *      query plan and ExecutorEnd() should always be called at the end of
20  *      execution of a plan.
21  *
22  *      ExecutorRun accepts 'feature' and 'count' arguments that specify whether
23  *      the plan is to be executed forwards, backwards, and for how many tuples.
24  *
25  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
26  * Portions Copyright (c) 1994, Regents of the University of California
27  *
28  *
29  * IDENTIFICATION
30  *        $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.135 2001/01/22 00:50:07 tgl Exp $
31  *
32  *-------------------------------------------------------------------------
33  */
34 #include "postgres.h"
35
36 #include "access/heapam.h"
37 #include "catalog/heap.h"
38 #include "commands/command.h"
39 #include "commands/trigger.h"
40 #include "executor/execdebug.h"
41 #include "executor/execdefs.h"
42 #include "miscadmin.h"
43 #include "optimizer/var.h"
44 #include "parser/parsetree.h"
45 #include "utils/acl.h"
46
47
48 /* decls for local routines only used within this module */
49 static TupleDesc InitPlan(CmdType operation,
50                  Query *parseTree,
51                  Plan *plan,
52                  EState *estate);
53 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
54                                                           Index resultRelationIndex,
55                                                           List *rangeTable,
56                                                           CmdType operation);
57 static void EndPlan(Plan *plan, EState *estate);
58 static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
59                                                                    CmdType operation,
60                                                                    long numberTuples,
61                                                                    ScanDirection direction,
62                                                                    DestReceiver *destfunc);
63 static void ExecRetrieve(TupleTableSlot *slot,
64                          DestReceiver *destfunc,
65                          EState *estate);
66 static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
67                    EState *estate);
68 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
69                    EState *estate);
70 static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
71                         EState *estate);
72 static TupleTableSlot *EvalPlanQualNext(EState *estate);
73 static void EndEvalPlanQual(EState *estate);
74 static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
75                                                                 Plan *plan);
76 static void ExecCheckPlanPerms(Plan *plan, List *rangeTable,
77                                                            CmdType operation);
78 static void ExecCheckRTPerms(List *rangeTable, CmdType operation);
79 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
80
81 /* end of local decls */
82
83
84 /* ----------------------------------------------------------------
85  *              ExecutorStart
86  *
87  *              This routine must be called at the beginning of any execution of any
88  *              query plan
89  *
90  *              returns a TupleDesc which describes the attributes of the tuples to
91  *              be returned by the query.
92  *
93  * NB: the CurrentMemoryContext when this is called must be the context
94  * to be used as the per-query context for the query plan.  ExecutorRun()
95  * and ExecutorEnd() must be called in this same memory context.
96  * ----------------------------------------------------------------
97  */
98 TupleDesc
99 ExecutorStart(QueryDesc *queryDesc, EState *estate)
100 {
101         TupleDesc       result;
102
103         /* sanity checks */
104         Assert(queryDesc != NULL);
105
106         if (queryDesc->plantree->nParamExec > 0)
107         {
108                 estate->es_param_exec_vals = (ParamExecData *)
109                         palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
110                 MemSet(estate->es_param_exec_vals, 0,
111                            queryDesc->plantree->nParamExec * sizeof(ParamExecData));
112         }
113
114         /*
115          * Make our own private copy of the current queries snapshot data
116          */
117         if (QuerySnapshot == NULL)
118                 estate->es_snapshot = NULL;
119         else
120         {
121                 estate->es_snapshot = (Snapshot) palloc(sizeof(SnapshotData));
122                 memcpy(estate->es_snapshot, QuerySnapshot, sizeof(SnapshotData));
123                 if (estate->es_snapshot->xcnt > 0)
124                 {
125                         estate->es_snapshot->xip = (TransactionId *)
126                                 palloc(estate->es_snapshot->xcnt * sizeof(TransactionId));
127                         memcpy(estate->es_snapshot->xip, QuerySnapshot->xip,
128                                    estate->es_snapshot->xcnt * sizeof(TransactionId));
129                 }
130         }
131
132         /*
133          * Initialize the plan
134          */
135         result = InitPlan(queryDesc->operation,
136                                           queryDesc->parsetree,
137                                           queryDesc->plantree,
138                                           estate);
139
140         return result;
141 }
142
143 /* ----------------------------------------------------------------
144  *              ExecutorRun
145  *
146  *              This is the main routine of the executor module. It accepts
147  *              the query descriptor from the traffic cop and executes the
148  *              query plan.
149  *
150  *              ExecutorStart must have been called already.
151  *
152  *              the different features supported are:
153  *                       EXEC_RUN:      retrieve all tuples in the forward direction
154  *                       EXEC_FOR:      retrieve 'count' number of tuples in the forward dir
155  *                       EXEC_BACK: retrieve 'count' number of tuples in the backward dir
156  *                       EXEC_RETONE: return one tuple but don't 'retrieve' it
157  *                                                 used in postquel function processing
158  *
159  *              Note: count = 0 is interpreted as "no limit".
160  *
161  * ----------------------------------------------------------------
162  */
163 TupleTableSlot *
164 ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature, long count)
165 {
166         CmdType         operation;
167         Plan       *plan;
168         TupleTableSlot *result;
169         CommandDest dest;
170         DestReceiver *destfunc;
171
172         /*
173          * sanity checks
174          */
175         Assert(queryDesc != NULL);
176
177         /*
178          * extract information from the query descriptor and the query
179          * feature.
180          */
181         operation = queryDesc->operation;
182         plan = queryDesc->plantree;
183         dest = queryDesc->dest;
184         destfunc = DestToFunction(dest);
185         estate->es_processed = 0;
186         estate->es_lastoid = InvalidOid;
187
188         /*
189          * FIXME: the dest setup function ought to be handed the tuple desc
190          * for the tuples to be output, but I'm not quite sure how to get that
191          * info at this point.  For now, passing NULL is OK because no
192          * existing dest setup function actually uses the pointer.
193          */
194         (*destfunc->setup) (destfunc, (TupleDesc) NULL);
195
196         switch (feature)
197         {
198                 case EXEC_RUN:
199                         result = ExecutePlan(estate,
200                                                                  plan,
201                                                                  operation,
202                                                                  count,
203                                                                  ForwardScanDirection,
204                                                                  destfunc);
205                         break;
206
207                 case EXEC_FOR:
208                         result = ExecutePlan(estate,
209                                                                  plan,
210                                                                  operation,
211                                                                  count,
212                                                                  ForwardScanDirection,
213                                                                  destfunc);
214                         break;
215
216                         /*
217                          * retrieve next n "backward" tuples
218                          */
219                 case EXEC_BACK:
220                         result = ExecutePlan(estate,
221                                                                  plan,
222                                                                  operation,
223                                                                  count,
224                                                                  BackwardScanDirection,
225                                                                  destfunc);
226                         break;
227
228                         /*
229                          * return one tuple but don't "retrieve" it. (this is used by
230                          * the rule manager..) -cim 9/14/89
231                          */
232                 case EXEC_RETONE:
233                         result = ExecutePlan(estate,
234                                                                  plan,
235                                                                  operation,
236                                                                  ONE_TUPLE,
237                                                                  ForwardScanDirection,
238                                                                  destfunc);
239                         break;
240
241                 default:
242                         elog(DEBUG, "ExecutorRun: Unknown feature %d", feature);
243                         result = NULL;
244                         break;
245         }
246
247         (*destfunc->cleanup) (destfunc);
248
249         return result;
250 }
251
252 /* ----------------------------------------------------------------
253  *              ExecutorEnd
254  *
255  *              This routine must be called at the end of any execution of any
256  *              query plan
257  *
258  *              returns (AttrInfo*) which describes the attributes of the tuples to
259  *              be returned by the query.
260  *
261  * ----------------------------------------------------------------
262  */
263 void
264 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
265 {
266         /* sanity checks */
267         Assert(queryDesc != NULL);
268
269         EndPlan(queryDesc->plantree, estate);
270
271         /* XXX - clean up some more from ExecutorStart() - er1p */
272         if (NULL == estate->es_snapshot)
273         {
274                 /* nothing to free */
275         }
276         else
277         {
278                 if (estate->es_snapshot->xcnt > 0)
279                         pfree(estate->es_snapshot->xip);
280                 pfree(estate->es_snapshot);
281         }
282
283         if (NULL == estate->es_param_exec_vals)
284         {
285                 /* nothing to free */
286         }
287         else
288         {
289                 pfree(estate->es_param_exec_vals);
290                 estate->es_param_exec_vals = NULL;
291         }
292 }
293
294
295 /*
296  * ExecCheckQueryPerms
297  *              Check access permissions for all relations referenced in a query.
298  */
299 static void
300 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
301 {
302         /*
303          * Check RTEs in the query's primary rangetable.
304          */
305         ExecCheckRTPerms(parseTree->rtable, operation);
306
307         /*
308          * Search for subplans and APPEND nodes to check their rangetables.
309          */
310         ExecCheckPlanPerms(plan, parseTree->rtable, operation);
311 }
312
313 /*
314  * ExecCheckPlanPerms
315  *              Recursively scan the plan tree to check access permissions in
316  *              subplans.
317  */
318 static void
319 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
320 {
321         List       *subp;
322
323         if (plan == NULL)
324                 return;
325
326         /* Check subplans, which we assume are plain SELECT queries */
327
328         foreach(subp, plan->initPlan)
329         {
330                 SubPlan    *subplan = (SubPlan *) lfirst(subp);
331
332                 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
333                 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
334         }
335         foreach(subp, plan->subPlan)
336         {
337                 SubPlan    *subplan = (SubPlan *) lfirst(subp);
338
339                 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
340                 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
341         }
342
343         /* Check lower plan nodes */
344
345         ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
346         ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
347
348         /* Do node-type-specific checks */
349
350         switch (nodeTag(plan))
351         {
352                 case T_SubqueryScan:
353                         {
354                                 SubqueryScan   *scan = (SubqueryScan *) plan;
355                                 RangeTblEntry *rte;
356
357                                 /* Recursively check the subquery */
358                                 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
359                                 Assert(rte->subquery != NULL);
360                                 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
361                                 break;
362                         }
363                 case T_Append:
364                         {
365                                 Append     *app = (Append *) plan;
366                                 List       *appendplans;
367
368                                 foreach(appendplans, app->appendplans)
369                                 {
370                                         ExecCheckPlanPerms((Plan *) lfirst(appendplans),
371                                                                            rangeTable,
372                                                                            operation);
373                                 }
374                                 break;
375                         }
376
377                 default:
378                         break;
379         }
380 }
381
382 /*
383  * ExecCheckRTPerms
384  *              Check access permissions for all relations listed in a range table.
385  */
386 static void
387 ExecCheckRTPerms(List *rangeTable, CmdType operation)
388 {
389         List       *lp;
390
391         foreach(lp, rangeTable)
392         {
393                 RangeTblEntry *rte = lfirst(lp);
394
395                 ExecCheckRTEPerms(rte, operation);
396         }
397 }
398
399 /*
400  * ExecCheckRTEPerms
401  *              Check access permissions for a single RTE.
402  */
403 static void
404 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
405 {
406         char       *relName;
407         Oid                     userid;
408         int32           aclcheck_result;
409
410         /*
411          * If it's a subquery RTE, ignore it --- it will be checked when
412          * ExecCheckPlanPerms finds the SubqueryScan node for it.
413          */
414         if (rte->subquery)
415                 return;
416
417         relName = rte->relname;
418
419         /*
420          * userid to check as: current user unless we have a setuid indication.
421          *
422          * Note: GetUserId() is presently fast enough that there's no harm
423          * in calling it separately for each RTE.  If that stops being true,
424          * we could call it once in ExecCheckQueryPerms and pass the userid
425          * down from there.  But for now, no need for the extra clutter.
426          */
427         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
428
429 #define CHECK(MODE)             pg_aclcheck(relName, userid, MODE)
430
431         if (rte->checkForRead)
432         {
433                 aclcheck_result = CHECK(ACL_RD);
434                 if (aclcheck_result != ACLCHECK_OK)
435                         elog(ERROR, "%s: %s",
436                                  relName, aclcheck_error_strings[aclcheck_result]);
437         }
438
439         if (rte->checkForWrite)
440         {
441                 /*
442                  * Note: write access in a SELECT context means SELECT FOR UPDATE.
443                  * Right now we don't distinguish that from true update as far as
444                  * permissions checks are concerned.
445                  */
446                 switch (operation)
447                 {
448                         case CMD_INSERT:
449                                 /* Accept either APPEND or WRITE access for this */
450                                 aclcheck_result = CHECK(ACL_AP);
451                                 if (aclcheck_result != ACLCHECK_OK)
452                                         aclcheck_result = CHECK(ACL_WR);
453                                 break;
454                         case CMD_SELECT:
455                         case CMD_DELETE:
456                         case CMD_UPDATE:
457                                 aclcheck_result = CHECK(ACL_WR);
458                                 break;
459                         default:
460                                 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
461                                          operation);
462                                 aclcheck_result = ACLCHECK_OK;  /* keep compiler quiet */
463                                 break;
464                 }
465                 if (aclcheck_result != ACLCHECK_OK)
466                         elog(ERROR, "%s: %s",
467                                  relName, aclcheck_error_strings[aclcheck_result]);
468         }
469 }
470
471
472 /* ===============================================================
473  * ===============================================================
474                                                  static routines follow
475  * ===============================================================
476  * ===============================================================
477  */
478
479 typedef struct execRowMark
480 {
481         Relation        relation;
482         Index           rti;
483         char            resname[32];
484 } execRowMark;
485
486 typedef struct evalPlanQual
487 {
488         Plan       *plan;
489         Index           rti;
490         EState          estate;
491         struct evalPlanQual *free;
492 } evalPlanQual;
493
494 /* ----------------------------------------------------------------
495  *              InitPlan
496  *
497  *              Initializes the query plan: open files, allocate storage
498  *              and start up the rule manager
499  * ----------------------------------------------------------------
500  */
501 static TupleDesc
502 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
503 {
504         List       *rangeTable;
505         Relation        intoRelationDesc;
506         TupleDesc       tupType;
507
508         /*
509          * Do permissions checks.
510          */
511         ExecCheckQueryPerms(operation, parseTree, plan);
512
513         /*
514          * get information from query descriptor
515          */
516         rangeTable = parseTree->rtable;
517
518         /*
519          * initialize the node's execution state
520          */
521         estate->es_range_table = rangeTable;
522
523         /*
524          * if there is a result relation, initialize result relation stuff
525          */
526         if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
527         {
528                 List       *resultRelations = parseTree->resultRelations;
529                 int                     numResultRelations;
530                 ResultRelInfo *resultRelInfos;
531
532                 if (resultRelations != NIL)
533                 {
534                         /*
535                          * Multiple result relations (due to inheritance)
536                          * parseTree->resultRelations identifies them all
537                          */
538                         ResultRelInfo *resultRelInfo;
539
540                         numResultRelations = length(resultRelations);
541                         resultRelInfos = (ResultRelInfo *)
542                                 palloc(numResultRelations * sizeof(ResultRelInfo));
543                         resultRelInfo = resultRelInfos;
544                         while (resultRelations != NIL)
545                         {
546                                 initResultRelInfo(resultRelInfo,
547                                                                   lfirsti(resultRelations),
548                                                                   rangeTable,
549                                                                   operation);
550                                 resultRelInfo++;
551                                 resultRelations = lnext(resultRelations);
552                         }
553                 }
554                 else
555                 {
556                         /*
557                          * Single result relation identified by parseTree->resultRelation
558                          */
559                         numResultRelations = 1;
560                         resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
561                         initResultRelInfo(resultRelInfos,
562                                                           parseTree->resultRelation,
563                                                           rangeTable,
564                                                           operation);
565                 }
566
567                 estate->es_result_relations = resultRelInfos;
568                 estate->es_num_result_relations = numResultRelations;
569                 /* Initialize to first or only result rel */
570                 estate->es_result_relation_info = resultRelInfos;
571         }
572         else
573         {
574                 /*
575                  * if no result relation, then set state appropriately
576                  */
577                 estate->es_result_relations = NULL;
578                 estate->es_num_result_relations = 0;
579                 estate->es_result_relation_info = NULL;
580         }
581
582         /*
583          * Have to lock relations selected for update
584          */
585         estate->es_rowMark = NIL;
586         if (parseTree->rowMarks != NIL)
587         {
588                 List       *l;
589
590                 foreach(l, parseTree->rowMarks)
591                 {
592                         Index           rti = lfirsti(l);
593                         Oid                     relid = getrelid(rti, rangeTable);
594                         Relation        relation;
595                         execRowMark *erm;
596
597                         relation = heap_open(relid, RowShareLock);
598                         erm = (execRowMark *) palloc(sizeof(execRowMark));
599                         erm->relation = relation;
600                         erm->rti = rti;
601                         sprintf(erm->resname, "ctid%u", rti);
602                         estate->es_rowMark = lappend(estate->es_rowMark, erm);
603                 }
604         }
605
606         /*
607          * initialize the executor "tuple" table.
608          */
609         {
610                 int                     nSlots = ExecCountSlotsNode(plan);
611                 TupleTable      tupleTable = ExecCreateTupleTable(nSlots + 10);         /* why add ten? - jolly */
612
613                 estate->es_tupleTable = tupleTable;
614         }
615
616         /*
617          * initialize the private state information for all the nodes in the
618          * query tree.  This opens files, allocates storage and leaves us
619          * ready to start processing tuples.
620          */
621         ExecInitNode(plan, estate, NULL);
622
623         /*
624          * Get the tuple descriptor describing the type of tuples to return.
625          * (this is especially important if we are creating a relation with
626          * "retrieve into")
627          */
628         tupType = ExecGetTupType(plan);         /* tuple descriptor */
629
630         /*
631          * Initialize the junk filter if needed. SELECT and INSERT queries need
632          * a filter if there are any junk attrs in the tlist.  UPDATE and
633          * DELETE always need one, since there's always a junk 'ctid' attribute
634          * present --- no need to look first.
635          */
636         {
637                 bool            junk_filter_needed = false;
638                 List       *tlist;
639
640                 switch (operation)
641                 {
642                         case CMD_SELECT:
643                         case CMD_INSERT:
644                                 foreach(tlist, plan->targetlist)
645                                 {
646                                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
647
648                                         if (tle->resdom->resjunk)
649                                         {
650                                                 junk_filter_needed = true;
651                                                 break;
652                                         }
653                                 }
654                                 break;
655                         case CMD_UPDATE:
656                         case CMD_DELETE:
657                                 junk_filter_needed = true;
658                                 break;
659                         default:
660                                 break;
661                 }
662
663                 if (junk_filter_needed)
664                 {
665                         /*
666                          * If there are multiple result relations, each one needs
667                          * its own junk filter.  Note this is only possible for
668                          * UPDATE/DELETE, so we can't be fooled by some needing
669                          * a filter and some not.
670                          */
671                         if (parseTree->resultRelations != NIL)
672                         {
673                                 List       *subplans;
674                                 ResultRelInfo *resultRelInfo;
675
676                                 /* Top plan had better be an Append here. */
677                                 Assert(IsA(plan, Append));
678                                 Assert(((Append *) plan)->isTarget);
679                                 subplans = ((Append *) plan)->appendplans;
680                                 Assert(length(subplans) == estate->es_num_result_relations);
681                                 resultRelInfo = estate->es_result_relations;
682                                 while (subplans != NIL)
683                                 {
684                                         Plan       *subplan = (Plan *) lfirst(subplans);
685                                         JunkFilter *j;
686
687                                         j = ExecInitJunkFilter(subplan->targetlist,
688                                                                                    ExecGetTupType(subplan));
689                                         resultRelInfo->ri_junkFilter = j;
690                                         resultRelInfo++;
691                                         subplans = lnext(subplans);
692                                 }
693                                 /*
694                                  * Set active junkfilter too; at this point ExecInitAppend
695                                  * has already selected an active result relation...
696                                  */
697                                 estate->es_junkFilter =
698                                         estate->es_result_relation_info->ri_junkFilter;
699                         }
700                         else
701                         {
702                                 /* Normal case with just one JunkFilter */
703                                 JunkFilter *j = ExecInitJunkFilter(plan->targetlist,
704                                                                                                    tupType);
705
706                                 estate->es_junkFilter = j;
707                                 if (estate->es_result_relation_info)
708                                         estate->es_result_relation_info->ri_junkFilter = j;
709
710                                 /* For SELECT, want to return the cleaned tuple type */
711                                 if (operation == CMD_SELECT)
712                                         tupType = j->jf_cleanTupType;
713                         }
714                 }
715                 else
716                         estate->es_junkFilter = NULL;
717         }
718
719         /*
720          * initialize the "into" relation
721          */
722         intoRelationDesc = (Relation) NULL;
723
724         if (operation == CMD_SELECT)
725         {
726                 char       *intoName;
727                 Oid                     intoRelationId;
728                 TupleDesc       tupdesc;
729
730                 if (!parseTree->isPortal)
731                 {
732
733                         /*
734                          * a select into table
735                          */
736                         if (parseTree->into != NULL)
737                         {
738
739                                 /*
740                                  * create the "into" relation
741                                  */
742                                 intoName = parseTree->into;
743
744                                 /*
745                                  * have to copy tupType to get rid of constraints
746                                  */
747                                 tupdesc = CreateTupleDescCopy(tupType);
748
749                                 intoRelationId =
750                                         heap_create_with_catalog(intoName,
751                                                                                          tupdesc,
752                                                                                          RELKIND_RELATION,
753                                                                                          parseTree->isTemp,
754                                                                                          allowSystemTableMods);
755
756                                 FreeTupleDesc(tupdesc);
757
758                                 /*
759                                  * Advance command counter so that the newly-created
760                                  * relation's catalog tuples will be visible to heap_open.
761                                  */
762                                 CommandCounterIncrement();
763
764                                 /*
765                                  * If necessary, create a TOAST table for the into relation.
766                                  * Note that AlterTableCreateToastTable ends with
767                                  * CommandCounterIncrement(), so that the TOAST table will
768                                  * be visible for insertion.
769                                  */
770                                 AlterTableCreateToastTable(intoName, true);
771
772                                 intoRelationDesc = heap_open(intoRelationId,
773                                                                                          AccessExclusiveLock);
774                         }
775                 }
776         }
777
778         estate->es_into_relation_descriptor = intoRelationDesc;
779
780         estate->es_origPlan = plan;
781         estate->es_evalPlanQual = NULL;
782         estate->es_evTuple = NULL;
783         estate->es_useEvalPlan = false;
784
785         return tupType;
786 }
787
788 /*
789  * Initialize ResultRelInfo data for one result relation
790  */
791 static void
792 initResultRelInfo(ResultRelInfo *resultRelInfo,
793                                   Index resultRelationIndex,
794                                   List *rangeTable,
795                                   CmdType operation)
796 {
797         Oid                     resultRelationOid;
798         Relation        resultRelationDesc;
799
800         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
801         resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
802
803         switch (resultRelationDesc->rd_rel->relkind)
804         {
805                 case RELKIND_SEQUENCE:
806                         elog(ERROR, "You can't change sequence relation %s",
807                                  RelationGetRelationName(resultRelationDesc));
808                         break;
809                 case RELKIND_TOASTVALUE:
810                         elog(ERROR, "You can't change toast relation %s",
811                                  RelationGetRelationName(resultRelationDesc));
812                         break;
813                 case RELKIND_VIEW:
814                         elog(ERROR, "You can't change view relation %s",
815                                  RelationGetRelationName(resultRelationDesc));
816                         break;
817         }
818
819         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
820         resultRelInfo->type = T_ResultRelInfo;
821         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
822         resultRelInfo->ri_RelationDesc = resultRelationDesc;
823         resultRelInfo->ri_NumIndices = 0;
824         resultRelInfo->ri_IndexRelationDescs = NULL;
825         resultRelInfo->ri_IndexRelationInfo = NULL;
826         resultRelInfo->ri_ConstraintExprs = NULL;
827         resultRelInfo->ri_junkFilter = NULL;
828
829         /*
830          * If there are indices on the result relation, open them and save
831          * descriptors in the result relation info, so that we can add new
832          * index entries for the tuples we add/update.  We need not do
833          * this for a DELETE, however, since deletion doesn't affect
834          * indexes.
835          */
836         if (resultRelationDesc->rd_rel->relhasindex &&
837                 operation != CMD_DELETE)
838                 ExecOpenIndices(resultRelInfo);
839 }
840
841 /* ----------------------------------------------------------------
842  *              EndPlan
843  *
844  *              Cleans up the query plan -- closes files and free up storages
845  * ----------------------------------------------------------------
846  */
847 static void
848 EndPlan(Plan *plan, EState *estate)
849 {
850         ResultRelInfo *resultRelInfo;
851         int                     i;
852         List       *l;
853
854         /*
855          * shut down any PlanQual processing we were doing
856          */
857         if (estate->es_evalPlanQual != NULL)
858                 EndEvalPlanQual(estate);
859
860         /*
861          * shut down the node-type-specific query processing
862          */
863         ExecEndNode(plan, plan);
864
865         /*
866          * destroy the executor "tuple" table.
867          */
868         ExecDropTupleTable(estate->es_tupleTable, true);
869         estate->es_tupleTable = NULL;
870
871         /*
872          * close the result relation(s) if any, but hold locks
873          * until xact commit.
874          */
875         resultRelInfo = estate->es_result_relations;
876         for (i = estate->es_num_result_relations; i > 0; i--)
877         {
878                 /* Close indices and then the relation itself */
879                 ExecCloseIndices(resultRelInfo);
880                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
881                 resultRelInfo++;
882         }
883
884         /*
885          * close the "into" relation if necessary, again keeping lock
886          */
887         if (estate->es_into_relation_descriptor != NULL)
888                 heap_close(estate->es_into_relation_descriptor, NoLock);
889
890         /*
891          * close any relations selected FOR UPDATE, again keeping locks
892          */
893         foreach(l, estate->es_rowMark)
894         {
895                 execRowMark *erm = lfirst(l);
896
897                 heap_close(erm->relation, NoLock);
898         }
899 }
900
901 /* ----------------------------------------------------------------
902  *              ExecutePlan
903  *
904  *              processes the query plan to retrieve 'numberTuples' tuples in the
905  *              direction specified.
906  *              Retrieves all tuples if tupleCount is 0
907  *
908  *              result is either a slot containing the last tuple in the case
909  *              of a RETRIEVE or NULL otherwise.
910  *
911  * Note: the ctid attribute is a 'junk' attribute that is removed before the
912  * user can see it
913  * ----------------------------------------------------------------
914  */
915 static TupleTableSlot *
916 ExecutePlan(EState *estate,
917                         Plan *plan,
918                         CmdType operation,
919                         long numberTuples,
920                         ScanDirection direction,
921                         DestReceiver *destfunc)
922 {
923         JunkFilter *junkfilter;
924         TupleTableSlot *slot;
925         ItemPointer tupleid = NULL;
926         ItemPointerData tuple_ctid;
927         long            current_tuple_count;
928         TupleTableSlot *result;
929
930         /*
931          * initialize local variables
932          */
933         slot = NULL;
934         current_tuple_count = 0;
935         result = NULL;
936
937         /*
938          * Set the direction.
939          */
940         estate->es_direction = direction;
941
942         /*
943          * Loop until we've processed the proper number of tuples from the
944          * plan.
945          */
946
947         for (;;)
948         {
949                 /* Reset the per-output-tuple exprcontext */
950                 ResetPerTupleExprContext(estate);
951
952                 /*
953                  * Execute the plan and obtain a tuple
954                  */
955                 /* at the top level, the parent of a plan (2nd arg) is itself */
956 lnext:  ;
957                 if (estate->es_useEvalPlan)
958                 {
959                         slot = EvalPlanQualNext(estate);
960                         if (TupIsNull(slot))
961                                 slot = ExecProcNode(plan, plan);
962                 }
963                 else
964                         slot = ExecProcNode(plan, plan);
965
966                 /*
967                  * if the tuple is null, then we assume there is nothing more to
968                  * process so we just return null...
969                  */
970                 if (TupIsNull(slot))
971                 {
972                         result = NULL;
973                         break;
974                 }
975
976                 /*
977                  * if we have a junk filter, then project a new tuple with the
978                  * junk removed.
979                  *
980                  * Store this new "clean" tuple in the place of the original tuple.
981                  *
982                  * Also, extract all the junk information we need.
983                  */
984                 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
985                 {
986                         Datum           datum;
987                         HeapTuple       newTuple;
988                         bool            isNull;
989
990                         /*
991                          * extract the 'ctid' junk attribute.
992                          */
993                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
994                         {
995                                 if (!ExecGetJunkAttribute(junkfilter,
996                                                                                   slot,
997                                                                                   "ctid",
998                                                                                   &datum,
999                                                                                   &isNull))
1000                                         elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1001
1002                                 /* shouldn't ever get a null result... */
1003                                 if (isNull)
1004                                         elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1005
1006                                 tupleid = (ItemPointer) DatumGetPointer(datum);
1007                                 tuple_ctid = *tupleid;  /* make sure we don't free the
1008                                                                                  * ctid!! */
1009                                 tupleid = &tuple_ctid;
1010                         }
1011                         else if (estate->es_rowMark != NIL)
1012                         {
1013                                 List       *l;
1014
1015                 lmark:  ;
1016                                 foreach(l, estate->es_rowMark)
1017                                 {
1018                                         execRowMark *erm = lfirst(l);
1019                                         Buffer          buffer;
1020                                         HeapTupleData tuple;
1021                                         TupleTableSlot *newSlot;
1022                                         int                     test;
1023
1024                                         if (!ExecGetJunkAttribute(junkfilter,
1025                                                                                           slot,
1026                                                                                           erm->resname,
1027                                                                                           &datum,
1028                                                                                           &isNull))
1029                                                 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1030                                                          erm->resname);
1031
1032                                         /*
1033                                          * Unlike the UPDATE/DELETE case, a null result is
1034                                          * possible here, when the referenced table is on the
1035                                          * nullable side of an outer join.  Ignore nulls.
1036                                          */
1037                                         if (isNull)
1038                                                 continue;
1039
1040                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1041                                         test = heap_mark4update(erm->relation, &tuple, &buffer);
1042                                         ReleaseBuffer(buffer);
1043                                         switch (test)
1044                                         {
1045                                                 case HeapTupleSelfUpdated:
1046                                                 case HeapTupleMayBeUpdated:
1047                                                         break;
1048
1049                                                 case HeapTupleUpdated:
1050                                                         if (XactIsoLevel == XACT_SERIALIZABLE)
1051                                                                 elog(ERROR, "Can't serialize access due to concurrent update");
1052                                                         if (!(ItemPointerEquals(&(tuple.t_self),
1053                                                                   (ItemPointer) DatumGetPointer(datum))))
1054                                                         {
1055                                                                 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1056                                                                 if (!(TupIsNull(newSlot)))
1057                                                                 {
1058                                                                         slot = newSlot;
1059                                                                         estate->es_useEvalPlan = true;
1060                                                                         goto lmark;
1061                                                                 }
1062                                                         }
1063
1064                                                         /*
1065                                                          * if tuple was deleted or PlanQual failed for
1066                                                          * updated tuple - we have not return this
1067                                                          * tuple!
1068                                                          */
1069                                                         goto lnext;
1070
1071                                                 default:
1072                                                         elog(ERROR, "Unknown status %u from heap_mark4update", test);
1073                                                         return (NULL);
1074                                         }
1075                                 }
1076                         }
1077
1078                         /*
1079                          * Finally create a new "clean" tuple with all junk attributes
1080                          * removed
1081                          */
1082                         newTuple = ExecRemoveJunk(junkfilter, slot);
1083
1084                         slot = ExecStoreTuple(newTuple,         /* tuple to store */
1085                                                                   slot, /* destination slot */
1086                                                                   InvalidBuffer,                /* this tuple has no
1087                                                                                                                  * buffer */
1088                                                                   true);                /* tuple should be pfreed */
1089                 }                                               /* if (junkfilter... */
1090
1091                 /*
1092                  * now that we have a tuple, do the appropriate thing with it..
1093                  * either return it to the user, add it to a relation someplace,
1094                  * delete it from a relation, or modify some of its attributes.
1095                  */
1096
1097                 switch (operation)
1098                 {
1099                         case CMD_SELECT:
1100                                 ExecRetrieve(slot,              /* slot containing tuple */
1101                                                          destfunc,      /* destination's tuple-receiver
1102                                                                                  * obj */
1103                                                          estate);       /* */
1104                                 result = slot;
1105                                 break;
1106
1107                         case CMD_INSERT:
1108                                 ExecAppend(slot, tupleid, estate);
1109                                 result = NULL;
1110                                 break;
1111
1112                         case CMD_DELETE:
1113                                 ExecDelete(slot, tupleid, estate);
1114                                 result = NULL;
1115                                 break;
1116
1117                         case CMD_UPDATE:
1118                                 ExecReplace(slot, tupleid, estate);
1119                                 result = NULL;
1120                                 break;
1121
1122                         default:
1123                                 elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1124                                 result = NULL;
1125                                 break;
1126                 }
1127
1128                 /*
1129                  * check our tuple count.. if we've processed the proper number
1130                  * then quit, else loop again and process more tuples..
1131                  */
1132                 current_tuple_count++;
1133                 if (numberTuples == current_tuple_count)
1134                         break;
1135         }
1136
1137         /*
1138          * here, result is either a slot containing a tuple in the case of a
1139          * RETRIEVE or NULL otherwise.
1140          */
1141         return result;
1142 }
1143
1144 /* ----------------------------------------------------------------
1145  *              ExecRetrieve
1146  *
1147  *              RETRIEVEs are easy.. we just pass the tuple to the appropriate
1148  *              print function.  The only complexity is when we do a
1149  *              "retrieve into", in which case we insert the tuple into
1150  *              the appropriate relation (note: this is a newly created relation
1151  *              so we don't need to worry about indices or locks.)
1152  * ----------------------------------------------------------------
1153  */
1154 static void
1155 ExecRetrieve(TupleTableSlot *slot,
1156                          DestReceiver *destfunc,
1157                          EState *estate)
1158 {
1159         HeapTuple       tuple;
1160         TupleDesc       attrtype;
1161
1162         /*
1163          * get the heap tuple out of the tuple table slot
1164          */
1165         tuple = slot->val;
1166         attrtype = slot->ttc_tupleDescriptor;
1167
1168         /*
1169          * insert the tuple into the "into relation"
1170          */
1171         if (estate->es_into_relation_descriptor != NULL)
1172         {
1173                 heap_insert(estate->es_into_relation_descriptor, tuple);
1174                 IncrAppended();
1175         }
1176
1177         /*
1178          * send the tuple to the front end (or the screen)
1179          */
1180         (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1181         IncrRetrieved();
1182         (estate->es_processed)++;
1183 }
1184
1185 /* ----------------------------------------------------------------
1186  *              ExecAppend
1187  *
1188  *              APPENDs are trickier.. we have to insert the tuple into
1189  *              the base relation and insert appropriate tuples into the
1190  *              index relations.
1191  * ----------------------------------------------------------------
1192  */
1193
1194 static void
1195 ExecAppend(TupleTableSlot *slot,
1196                    ItemPointer tupleid,
1197                    EState *estate)
1198 {
1199         HeapTuple       tuple;
1200         ResultRelInfo *resultRelInfo;
1201         Relation        resultRelationDesc;
1202         int                     numIndices;
1203         Oid                     newId;
1204
1205         /*
1206          * get the heap tuple out of the tuple table slot
1207          */
1208         tuple = slot->val;
1209
1210         /*
1211          * get information on the (current) result relation
1212          */
1213         resultRelInfo = estate->es_result_relation_info;
1214         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1215
1216         /* BEFORE ROW INSERT Triggers */
1217         if (resultRelationDesc->trigdesc &&
1218                 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1219         {
1220                 HeapTuple       newtuple;
1221
1222                 newtuple = ExecBRInsertTriggers(estate, resultRelationDesc, tuple);
1223
1224                 if (newtuple == NULL)   /* "do nothing" */
1225                         return;
1226
1227                 if (newtuple != tuple)  /* modified by Trigger(s) */
1228                 {
1229                         /*
1230                          * Insert modified tuple into tuple table slot, replacing the
1231                          * original.  We assume that it was allocated in per-tuple
1232                          * memory context, and therefore will go away by itself.
1233                          * The tuple table slot should not try to clear it.
1234                          */
1235                         ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1236                         tuple = newtuple;
1237                 }
1238         }
1239
1240         /*
1241          * Check the constraints of the tuple
1242          */
1243         if (resultRelationDesc->rd_att->constr)
1244                 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1245
1246         /*
1247          * insert the tuple
1248          */
1249         newId = heap_insert(resultRelationDesc, tuple);
1250
1251         IncrAppended();
1252         (estate->es_processed)++;
1253         estate->es_lastoid = newId;
1254
1255         /*
1256          * process indices
1257          *
1258          * Note: heap_insert adds a new tuple to a relation.  As a side effect,
1259          * the tupleid of the new tuple is placed in the new tuple's t_ctid
1260          * field.
1261          */
1262         numIndices = resultRelInfo->ri_NumIndices;
1263         if (numIndices > 0)
1264                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1265
1266         /* AFTER ROW INSERT Triggers */
1267         if (resultRelationDesc->trigdesc &&
1268                 resultRelationDesc->trigdesc->n_after_row[TRIGGER_EVENT_INSERT] > 0)
1269                 ExecARInsertTriggers(estate, resultRelationDesc, tuple);
1270 }
1271
1272 /* ----------------------------------------------------------------
1273  *              ExecDelete
1274  *
1275  *              DELETE is like append, we delete the tuple and its
1276  *              index tuples.
1277  * ----------------------------------------------------------------
1278  */
1279 static void
1280 ExecDelete(TupleTableSlot *slot,
1281                    ItemPointer tupleid,
1282                    EState *estate)
1283 {
1284         ResultRelInfo *resultRelInfo;
1285         Relation        resultRelationDesc;
1286         ItemPointerData ctid;
1287         int                     result;
1288
1289         /*
1290          * get information on the (current) result relation
1291          */
1292         resultRelInfo = estate->es_result_relation_info;
1293         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1294
1295         /* BEFORE ROW DELETE Triggers */
1296         if (resultRelationDesc->trigdesc &&
1297                 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1298         {
1299                 bool            dodelete;
1300
1301                 dodelete = ExecBRDeleteTriggers(estate, tupleid);
1302
1303                 if (!dodelete)                  /* "do nothing" */
1304                         return;
1305         }
1306
1307         /*
1308          * delete the tuple
1309          */
1310 ldelete:;
1311         result = heap_delete(resultRelationDesc, tupleid, &ctid);
1312         switch (result)
1313         {
1314                 case HeapTupleSelfUpdated:
1315                         return;
1316
1317                 case HeapTupleMayBeUpdated:
1318                         break;
1319
1320                 case HeapTupleUpdated:
1321                         if (XactIsoLevel == XACT_SERIALIZABLE)
1322                                 elog(ERROR, "Can't serialize access due to concurrent update");
1323                         else if (!(ItemPointerEquals(tupleid, &ctid)))
1324                         {
1325                                 TupleTableSlot *epqslot = EvalPlanQual(estate,
1326                                                   resultRelInfo->ri_RangeTableIndex, &ctid);
1327
1328                                 if (!TupIsNull(epqslot))
1329                                 {
1330                                         *tupleid = ctid;
1331                                         goto ldelete;
1332                                 }
1333                         }
1334                         return;
1335
1336                 default:
1337                         elog(ERROR, "Unknown status %u from heap_delete", result);
1338                         return;
1339         }
1340
1341         IncrDeleted();
1342         (estate->es_processed)++;
1343
1344         /*
1345          * Note: Normally one would think that we have to delete index tuples
1346          * associated with the heap tuple now..
1347          *
1348          * ... but in POSTGRES, we have no need to do this because the vacuum
1349          * daemon automatically opens an index scan and deletes index tuples
1350          * when it finds deleted heap tuples. -cim 9/27/89
1351          */
1352
1353         /* AFTER ROW DELETE Triggers */
1354         if (resultRelationDesc->trigdesc &&
1355                 resultRelationDesc->trigdesc->n_after_row[TRIGGER_EVENT_DELETE] > 0)
1356                 ExecARDeleteTriggers(estate, tupleid);
1357 }
1358
1359 /* ----------------------------------------------------------------
1360  *              ExecReplace
1361  *
1362  *              note: we can't run replace queries with transactions
1363  *              off because replaces are actually appends and our
1364  *              scan will mistakenly loop forever, replacing the tuple
1365  *              it just appended..      This should be fixed but until it
1366  *              is, we don't want to get stuck in an infinite loop
1367  *              which corrupts your database..
1368  * ----------------------------------------------------------------
1369  */
1370 static void
1371 ExecReplace(TupleTableSlot *slot,
1372                         ItemPointer tupleid,
1373                         EState *estate)
1374 {
1375         HeapTuple       tuple;
1376         ResultRelInfo *resultRelInfo;
1377         Relation        resultRelationDesc;
1378         ItemPointerData ctid;
1379         int                     result;
1380         int                     numIndices;
1381
1382         /*
1383          * abort the operation if not running transactions
1384          */
1385         if (IsBootstrapProcessingMode())
1386         {
1387                 elog(NOTICE, "ExecReplace: replace can't run without transactions");
1388                 return;
1389         }
1390
1391         /*
1392          * get the heap tuple out of the tuple table slot
1393          */
1394         tuple = slot->val;
1395
1396         /*
1397          * get information on the (current) result relation
1398          */
1399         resultRelInfo = estate->es_result_relation_info;
1400         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1401
1402         /* BEFORE ROW UPDATE Triggers */
1403         if (resultRelationDesc->trigdesc &&
1404                 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1405         {
1406                 HeapTuple       newtuple;
1407
1408                 newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1409
1410                 if (newtuple == NULL)   /* "do nothing" */
1411                         return;
1412
1413                 if (newtuple != tuple)  /* modified by Trigger(s) */
1414                 {
1415                         /*
1416                          * Insert modified tuple into tuple table slot, replacing the
1417                          * original.  We assume that it was allocated in per-tuple
1418                          * memory context, and therefore will go away by itself.
1419                          * The tuple table slot should not try to clear it.
1420                          */
1421                         ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1422                         tuple = newtuple;
1423                 }
1424         }
1425
1426         /*
1427          * Check the constraints of the tuple
1428          */
1429         if (resultRelationDesc->rd_att->constr)
1430                 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1431
1432         /*
1433          * replace the heap tuple
1434          */
1435 lreplace:;
1436         result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1437         switch (result)
1438         {
1439                 case HeapTupleSelfUpdated:
1440                         return;
1441
1442                 case HeapTupleMayBeUpdated:
1443                         break;
1444
1445                 case HeapTupleUpdated:
1446                         if (XactIsoLevel == XACT_SERIALIZABLE)
1447                                 elog(ERROR, "Can't serialize access due to concurrent update");
1448                         else if (!(ItemPointerEquals(tupleid, &ctid)))
1449                         {
1450                                 TupleTableSlot *epqslot = EvalPlanQual(estate,
1451                                                   resultRelInfo->ri_RangeTableIndex, &ctid);
1452
1453                                 if (!TupIsNull(epqslot))
1454                                 {
1455                                         *tupleid = ctid;
1456                                         tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1457                                         slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1458                                         goto lreplace;
1459                                 }
1460                         }
1461                         return;
1462
1463                 default:
1464                         elog(ERROR, "Unknown status %u from heap_update", result);
1465                         return;
1466         }
1467
1468         IncrReplaced();
1469         (estate->es_processed)++;
1470
1471         /*
1472          * Note: instead of having to update the old index tuples associated
1473          * with the heap tuple, all we do is form and insert new index
1474          * tuples.  This is because replaces are actually deletes and inserts
1475          * and index tuple deletion is done automagically by the vacuum
1476          * daemon. All we do is insert new index tuples.  -cim 9/27/89
1477          */
1478
1479         /*
1480          * process indices
1481          *
1482          * heap_update updates a tuple in the base relation by invalidating it
1483          * and then appending a new tuple to the relation.      As a side effect,
1484          * the tupleid of the new tuple is placed in the new tuple's t_ctid
1485          * field.  So we now insert index tuples using the new tupleid stored
1486          * there.
1487          */
1488
1489         numIndices = resultRelInfo->ri_NumIndices;
1490         if (numIndices > 0)
1491                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1492
1493         /* AFTER ROW UPDATE Triggers */
1494         if (resultRelationDesc->trigdesc &&
1495                 resultRelationDesc->trigdesc->n_after_row[TRIGGER_EVENT_UPDATE] > 0)
1496                 ExecARUpdateTriggers(estate, tupleid, tuple);
1497 }
1498
1499 static char *
1500 ExecRelCheck(ResultRelInfo *resultRelInfo,
1501                          TupleTableSlot *slot, EState *estate)
1502 {
1503         Relation        rel = resultRelInfo->ri_RelationDesc;
1504         int                     ncheck = rel->rd_att->constr->num_check;
1505         ConstrCheck *check = rel->rd_att->constr->check;
1506         ExprContext *econtext;
1507         MemoryContext oldContext;
1508         List       *qual;
1509         int                     i;
1510
1511         /*
1512          * If first time through for this result relation, build expression
1513          * nodetrees for rel's constraint expressions.  Keep them in the
1514          * per-query memory context so they'll survive throughout the query.
1515          */
1516         if (resultRelInfo->ri_ConstraintExprs == NULL)
1517         {
1518                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1519                 resultRelInfo->ri_ConstraintExprs =
1520                         (List **) palloc(ncheck * sizeof(List *));
1521                 for (i = 0; i < ncheck; i++)
1522                 {
1523                         qual = (List *) stringToNode(check[i].ccbin);
1524                         resultRelInfo->ri_ConstraintExprs[i] = qual;
1525                 }
1526                 MemoryContextSwitchTo(oldContext);
1527         }
1528
1529         /*
1530          * We will use the EState's per-tuple context for evaluating constraint
1531          * expressions (creating it if it's not already there).
1532          */
1533         econtext = GetPerTupleExprContext(estate);
1534
1535         /* Arrange for econtext's scan tuple to be the tuple under test */
1536         econtext->ecxt_scantuple = slot;
1537
1538         /* And evaluate the constraints */
1539         for (i = 0; i < ncheck; i++)
1540         {
1541                 qual = resultRelInfo->ri_ConstraintExprs[i];
1542
1543                 /*
1544                  * NOTE: SQL92 specifies that a NULL result from a constraint
1545                  * expression is not to be treated as a failure.  Therefore, tell
1546                  * ExecQual to return TRUE for NULL.
1547                  */
1548                 if (!ExecQual(qual, econtext, true))
1549                         return check[i].ccname;
1550         }
1551
1552         /* NULL result means no error */
1553         return (char *) NULL;
1554 }
1555
1556 void
1557 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1558                                 TupleTableSlot *slot, EState *estate)
1559 {
1560         Relation        rel = resultRelInfo->ri_RelationDesc;
1561         HeapTuple       tuple = slot->val;
1562         TupleConstr *constr = rel->rd_att->constr;
1563
1564         Assert(constr);
1565
1566         if (constr->has_not_null)
1567         {
1568                 int                     natts = rel->rd_att->natts;
1569                 int                     attrChk;
1570
1571                 for (attrChk = 1; attrChk <= natts; attrChk++)
1572                 {
1573                         if (rel->rd_att->attrs[attrChk-1]->attnotnull &&
1574                                 heap_attisnull(tuple, attrChk))
1575                                 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1576                                          caller, NameStr(rel->rd_att->attrs[attrChk-1]->attname));
1577                 }
1578         }
1579
1580         if (constr->num_check > 0)
1581         {
1582                 char       *failed;
1583
1584                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1585                         elog(ERROR, "%s: rejected due to CHECK constraint %s",
1586                                  caller, failed);
1587         }
1588 }
1589
1590 TupleTableSlot *
1591 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1592 {
1593         evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1594         evalPlanQual *oldepq;
1595         EState     *epqstate = NULL;
1596         Relation        relation;
1597         Buffer          buffer;
1598         HeapTupleData tuple;
1599         bool            endNode = true;
1600
1601         Assert(rti != 0);
1602
1603         if (epq != NULL && epq->rti == 0)
1604         {
1605                 Assert(!(estate->es_useEvalPlan) &&
1606                            epq->estate.es_evalPlanQual == NULL);
1607                 epq->rti = rti;
1608                 endNode = false;
1609         }
1610
1611         /*
1612          * If this is request for another RTE - Ra, - then we have to check
1613          * wasn't PlanQual requested for Ra already and if so then Ra' row was
1614          * updated again and we have to re-start old execution for Ra and
1615          * forget all what we done after Ra was suspended. Cool? -:))
1616          */
1617         if (epq != NULL && epq->rti != rti &&
1618                 epq->estate.es_evTuple[rti - 1] != NULL)
1619         {
1620                 do
1621                 {
1622                         /* pop previous PlanQual from the stack */
1623                         epqstate = &(epq->estate);
1624                         oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1625                         Assert(oldepq->rti != 0);
1626                         /* stop execution */
1627                         ExecEndNode(epq->plan, epq->plan);
1628                         epqstate->es_tupleTable->next = 0;
1629                         heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1630                         epqstate->es_evTuple[epq->rti - 1] = NULL;
1631                         /* push current PQ to freePQ stack */
1632                         oldepq->free = epq;
1633                         epq = oldepq;
1634                 } while (epq->rti != rti);
1635                 estate->es_evalPlanQual = (Pointer) epq;
1636         }
1637
1638         /*
1639          * If we are requested for another RTE then we have to suspend
1640          * execution of current PlanQual and start execution for new one.
1641          */
1642         if (epq == NULL || epq->rti != rti)
1643         {
1644                 /* try to reuse plan used previously */
1645                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1646
1647                 if (newepq == NULL)             /* first call or freePQ stack is empty */
1648                 {
1649                         newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1650                         /* Init EState */
1651                         epqstate = &(newepq->estate);
1652                         memset(epqstate, 0, sizeof(EState));
1653                         epqstate->type = T_EState;
1654                         epqstate->es_direction = ForwardScanDirection;
1655                         epqstate->es_snapshot = estate->es_snapshot;
1656                         epqstate->es_range_table = estate->es_range_table;
1657                         epqstate->es_param_list_info = estate->es_param_list_info;
1658                         if (estate->es_origPlan->nParamExec > 0)
1659                                 epqstate->es_param_exec_vals = (ParamExecData *)
1660                                         palloc(estate->es_origPlan->nParamExec *
1661                                                    sizeof(ParamExecData));
1662                         epqstate->es_tupleTable =
1663                                 ExecCreateTupleTable(estate->es_tupleTable->size);
1664                         /* ... rest */
1665                         newepq->plan = copyObject(estate->es_origPlan);
1666                         newepq->free = NULL;
1667                         epqstate->es_evTupleNull = (bool *)
1668                                 palloc(length(estate->es_range_table) * sizeof(bool));
1669                         if (epq == NULL)        /* first call */
1670                         {
1671                                 epqstate->es_evTuple = (HeapTuple *)
1672                                         palloc(length(estate->es_range_table) * sizeof(HeapTuple));
1673                                 memset(epqstate->es_evTuple, 0,
1674                                          length(estate->es_range_table) * sizeof(HeapTuple));
1675                         }
1676                         else
1677                                 epqstate->es_evTuple = epq->estate.es_evTuple;
1678                 }
1679                 else
1680                         epqstate = &(newepq->estate);
1681                 /* push current PQ to the stack */
1682                 epqstate->es_evalPlanQual = (Pointer) epq;
1683                 epq = newepq;
1684                 estate->es_evalPlanQual = (Pointer) epq;
1685                 epq->rti = rti;
1686                 endNode = false;
1687         }
1688
1689         epqstate = &(epq->estate);
1690
1691         /*
1692          * Ok - we're requested for the same RTE (-:)). I'm not sure about
1693          * ability to use ExecReScan instead of ExecInitNode, so...
1694          */
1695         if (endNode)
1696         {
1697                 ExecEndNode(epq->plan, epq->plan);
1698                 epqstate->es_tupleTable->next = 0;
1699         }
1700
1701         /* free old RTE' tuple */
1702         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1703         {
1704                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1705                 epqstate->es_evTuple[epq->rti - 1] = NULL;
1706         }
1707
1708         /* ** fetch tid tuple ** */
1709         if (estate->es_result_relation_info != NULL &&
1710                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1711                 relation = estate->es_result_relation_info->ri_RelationDesc;
1712         else
1713         {
1714                 List       *l;
1715
1716                 foreach(l, estate->es_rowMark)
1717                 {
1718                         if (((execRowMark *) lfirst(l))->rti == rti)
1719                                 break;
1720                 }
1721                 relation = ((execRowMark *) lfirst(l))->relation;
1722         }
1723         tuple.t_self = *tid;
1724         for (;;)
1725         {
1726                 heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
1727                 if (tuple.t_data != NULL)
1728                 {
1729                         TransactionId xwait = SnapshotDirty->xmax;
1730
1731                         if (TransactionIdIsValid(SnapshotDirty->xmin))
1732                         {
1733                                 elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
1734                                 Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
1735                                 elog(ERROR, "Aborting this transaction");
1736                         }
1737
1738                         /*
1739                          * If tuple is being updated by other transaction then we have
1740                          * to wait for its commit/abort.
1741                          */
1742                         if (TransactionIdIsValid(xwait))
1743                         {
1744                                 ReleaseBuffer(buffer);
1745                                 XactLockTableWait(xwait);
1746                                 continue;
1747                         }
1748
1749                         /*
1750                          * Nice! We got tuple - now copy it.
1751                          */
1752                         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1753                                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1754                         epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
1755                         ReleaseBuffer(buffer);
1756                         break;
1757                 }
1758
1759                 /*
1760                  * Ops! Invalid tuple. Have to check is it updated or deleted.
1761                  * Note that it's possible to get invalid SnapshotDirty->tid if
1762                  * tuple updated by this transaction. Have we to check this ?
1763                  */
1764                 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1765                         !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1766                 {
1767                         tuple.t_self = SnapshotDirty->tid;      /* updated ... */
1768                         continue;
1769                 }
1770
1771                 /*
1772                  * Deleted or updated by this transaction. Do not (re-)start
1773                  * execution of this PQ. Continue previous PQ.
1774                  */
1775                 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1776                 if (oldepq != NULL)
1777                 {
1778                         Assert(oldepq->rti != 0);
1779                         /* push current PQ to freePQ stack */
1780                         oldepq->free = epq;
1781                         epq = oldepq;
1782                         epqstate = &(epq->estate);
1783                         estate->es_evalPlanQual = (Pointer) epq;
1784                 }
1785                 else
1786                 {
1787                         epq->rti = 0;           /* this is the first (oldest) */
1788                         estate->es_useEvalPlan = false;         /* PQ - mark as free and          */
1789                         return (NULL);          /* continue Query execution   */
1790                 }
1791         }
1792
1793         if (estate->es_origPlan->nParamExec > 0)
1794                 memset(epqstate->es_param_exec_vals, 0,
1795                            estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1796         memset(epqstate->es_evTupleNull, false,
1797                    length(estate->es_range_table) * sizeof(bool));
1798         Assert(epqstate->es_tupleTable->next == 0);
1799         ExecInitNode(epq->plan, epqstate, NULL);
1800
1801         /*
1802          * For UPDATE/DELETE we have to return tid of actual row we're
1803          * executing PQ for.
1804          */
1805         *tid = tuple.t_self;
1806
1807         return EvalPlanQualNext(estate);
1808 }
1809
1810 static TupleTableSlot *
1811 EvalPlanQualNext(EState *estate)
1812 {
1813         evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1814         EState     *epqstate = &(epq->estate);
1815         evalPlanQual *oldepq;
1816         TupleTableSlot *slot;
1817
1818         Assert(epq->rti != 0);
1819
1820 lpqnext:;
1821         slot = ExecProcNode(epq->plan, epq->plan);
1822
1823         /*
1824          * No more tuples for this PQ. Continue previous one.
1825          */
1826         if (TupIsNull(slot))
1827         {
1828                 ExecEndNode(epq->plan, epq->plan);
1829                 epqstate->es_tupleTable->next = 0;
1830                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1831                 epqstate->es_evTuple[epq->rti - 1] = NULL;
1832                 /* pop old PQ from the stack */
1833                 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1834                 if (oldepq == (evalPlanQual *) NULL)
1835                 {
1836                         epq->rti = 0;           /* this is the first (oldest) */
1837                         estate->es_useEvalPlan = false;         /* PQ - mark as free and          */
1838                         return (NULL);          /* continue Query execution   */
1839                 }
1840                 Assert(oldepq->rti != 0);
1841                 /* push current PQ to freePQ stack */
1842                 oldepq->free = epq;
1843                 epq = oldepq;
1844                 epqstate = &(epq->estate);
1845                 estate->es_evalPlanQual = (Pointer) epq;
1846                 goto lpqnext;
1847         }
1848
1849         return (slot);
1850 }
1851
1852 static void
1853 EndEvalPlanQual(EState *estate)
1854 {
1855         evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1856         EState     *epqstate = &(epq->estate);
1857         evalPlanQual *oldepq;
1858
1859         if (epq->rti == 0)                      /* plans already shutdowned */
1860         {
1861                 Assert(epq->estate.es_evalPlanQual == NULL);
1862                 return;
1863         }
1864
1865         for (;;)
1866         {
1867                 ExecEndNode(epq->plan, epq->plan);
1868                 epqstate->es_tupleTable->next = 0;
1869                 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1870                 {
1871                         heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1872                         epqstate->es_evTuple[epq->rti - 1] = NULL;
1873                 }
1874                 /* pop old PQ from the stack */
1875                 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1876                 if (oldepq == (evalPlanQual *) NULL)
1877                 {
1878                         epq->rti = 0;           /* this is the first (oldest) */
1879                         estate->es_useEvalPlan = false;         /* PQ - mark as free */
1880                         break;
1881                 }
1882                 Assert(oldepq->rti != 0);
1883                 /* push current PQ to freePQ stack */
1884                 oldepq->free = epq;
1885                 epq = oldepq;
1886                 epqstate = &(epq->estate);
1887                 estate->es_evalPlanQual = (Pointer) epq;
1888         }
1889 }