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