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