]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
Merge palloc()/MemSet(0) calls into a single palloc0() call.
[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.182 2002/11/10 07:25:13 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         Oid                     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                                                                                          ATEOXACTNOOP,
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          * Loop until we've processed the proper number of tuples from the
932          * plan.
933          */
934
935         for (;;)
936         {
937                 /* Reset the per-output-tuple exprcontext */
938                 ResetPerTupleExprContext(estate);
939
940                 /*
941                  * Execute the plan and obtain a tuple
942                  */
943 lnext:  ;
944                 if (estate->es_useEvalPlan)
945                 {
946                         slot = EvalPlanQualNext(estate);
947                         if (TupIsNull(slot))
948                                 slot = ExecProcNode(plan, NULL);
949                 }
950                 else
951                         slot = ExecProcNode(plan, NULL);
952
953                 /*
954                  * if the tuple is null, then we assume there is nothing more to
955                  * process so we just return null...
956                  */
957                 if (TupIsNull(slot))
958                 {
959                         result = NULL;
960                         break;
961                 }
962
963                 /*
964                  * if we have a junk filter, then project a new tuple with the
965                  * junk removed.
966                  *
967                  * Store this new "clean" tuple in the junkfilter's resultSlot.
968                  * (Formerly, we stored it back over the "dirty" tuple, which is
969                  * WRONG because that tuple slot has the wrong descriptor.)
970                  *
971                  * Also, extract all the junk information we need.
972                  */
973                 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
974                 {
975                         Datum           datum;
976                         HeapTuple       newTuple;
977                         bool            isNull;
978
979                         /*
980                          * extract the 'ctid' junk attribute.
981                          */
982                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
983                         {
984                                 if (!ExecGetJunkAttribute(junkfilter,
985                                                                                   slot,
986                                                                                   "ctid",
987                                                                                   &datum,
988                                                                                   &isNull))
989                                         elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
990
991                                 /* shouldn't ever get a null result... */
992                                 if (isNull)
993                                         elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
994
995                                 tupleid = (ItemPointer) DatumGetPointer(datum);
996                                 tuple_ctid = *tupleid;  /* make sure we don't free the
997                                                                                  * ctid!! */
998                                 tupleid = &tuple_ctid;
999                         }
1000                         else if (estate->es_rowMark != NIL)
1001                         {
1002                                 List       *l;
1003
1004                 lmark:  ;
1005                                 foreach(l, estate->es_rowMark)
1006                                 {
1007                                         execRowMark *erm = lfirst(l);
1008                                         Buffer          buffer;
1009                                         HeapTupleData tuple;
1010                                         TupleTableSlot *newSlot;
1011                                         int                     test;
1012
1013                                         if (!ExecGetJunkAttribute(junkfilter,
1014                                                                                           slot,
1015                                                                                           erm->resname,
1016                                                                                           &datum,
1017                                                                                           &isNull))
1018                                                 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1019                                                          erm->resname);
1020
1021                                         /* shouldn't ever get a null result... */
1022                                         if (isNull)
1023                                                 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1024                                                          erm->resname);
1025
1026                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1027                                         test = heap_mark4update(erm->relation, &tuple, &buffer,
1028                                                                                         estate->es_snapshot->curcid);
1029                                         ReleaseBuffer(buffer);
1030                                         switch (test)
1031                                         {
1032                                                 case HeapTupleSelfUpdated:
1033                                                         /* treat it as deleted; do not process */
1034                                                         goto lnext;
1035
1036                                                 case HeapTupleMayBeUpdated:
1037                                                         break;
1038
1039                                                 case HeapTupleUpdated:
1040                                                         if (XactIsoLevel == XACT_SERIALIZABLE)
1041                                                                 elog(ERROR, "Can't serialize access due to concurrent update");
1042                                                         if (!(ItemPointerEquals(&(tuple.t_self),
1043                                                                   (ItemPointer) DatumGetPointer(datum))))
1044                                                         {
1045                                                                 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1046                                                                 if (!(TupIsNull(newSlot)))
1047                                                                 {
1048                                                                         slot = newSlot;
1049                                                                         estate->es_useEvalPlan = true;
1050                                                                         goto lmark;
1051                                                                 }
1052                                                         }
1053
1054                                                         /*
1055                                                          * if tuple was deleted or PlanQual failed for
1056                                                          * updated tuple - we must not return this
1057                                                          * tuple!
1058                                                          */
1059                                                         goto lnext;
1060
1061                                                 default:
1062                                                         elog(ERROR, "Unknown status %u from heap_mark4update", test);
1063                                                         return (NULL);
1064                                         }
1065                                 }
1066                         }
1067
1068                         /*
1069                          * Finally create a new "clean" tuple with all junk attributes
1070                          * removed
1071                          */
1072                         newTuple = ExecRemoveJunk(junkfilter, slot);
1073
1074                         slot = ExecStoreTuple(newTuple,         /* tuple to store */
1075                                                                   junkfilter->jf_resultSlot,    /* dest slot */
1076                                                                   InvalidBuffer,                /* this tuple has no
1077                                                                                                                  * buffer */
1078                                                                   true);                /* tuple should be pfreed */
1079                 }
1080
1081                 /*
1082                  * now that we have a tuple, do the appropriate thing with it..
1083                  * either return it to the user, add it to a relation someplace,
1084                  * delete it from a relation, or modify some of its attributes.
1085                  */
1086                 switch (operation)
1087                 {
1088                         case CMD_SELECT:
1089                                 ExecSelect(slot,        /* slot containing tuple */
1090                                                    destfunc,    /* destination's tuple-receiver
1091                                                                                  * obj */
1092                                                    estate);
1093                                 result = slot;
1094                                 break;
1095
1096                         case CMD_INSERT:
1097                                 ExecInsert(slot, tupleid, estate);
1098                                 result = NULL;
1099                                 break;
1100
1101                         case CMD_DELETE:
1102                                 ExecDelete(slot, tupleid, estate);
1103                                 result = NULL;
1104                                 break;
1105
1106                         case CMD_UPDATE:
1107                                 ExecUpdate(slot, tupleid, estate);
1108                                 result = NULL;
1109                                 break;
1110
1111                         default:
1112                                 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1113                                 result = NULL;
1114                                 break;
1115                 }
1116
1117                 /*
1118                  * check our tuple count.. if we've processed the proper number
1119                  * then quit, else loop again and process more tuples..
1120                  */
1121                 current_tuple_count++;
1122                 if (numberTuples == current_tuple_count)
1123                         break;
1124         }
1125
1126         /*
1127          * here, result is either a slot containing a tuple in the case of a
1128          * SELECT or NULL otherwise.
1129          */
1130         return result;
1131 }
1132
1133 /* ----------------------------------------------------------------
1134  *              ExecSelect
1135  *
1136  *              SELECTs are easy.. we just pass the tuple to the appropriate
1137  *              print function.  The only complexity is when we do a
1138  *              "SELECT INTO", in which case we insert the tuple into
1139  *              the appropriate relation (note: this is a newly created relation
1140  *              so we don't need to worry about indices or locks.)
1141  * ----------------------------------------------------------------
1142  */
1143 static void
1144 ExecSelect(TupleTableSlot *slot,
1145                    DestReceiver *destfunc,
1146                    EState *estate)
1147 {
1148         HeapTuple       tuple;
1149         TupleDesc       attrtype;
1150
1151         /*
1152          * get the heap tuple out of the tuple table slot
1153          */
1154         tuple = slot->val;
1155         attrtype = slot->ttc_tupleDescriptor;
1156
1157         /*
1158          * insert the tuple into the "into relation"
1159          */
1160         if (estate->es_into_relation_descriptor != NULL)
1161         {
1162                 heap_insert(estate->es_into_relation_descriptor, tuple,
1163                                         estate->es_snapshot->curcid);
1164                 IncrAppended();
1165         }
1166
1167         /*
1168          * send the tuple to the front end (or the screen)
1169          */
1170         (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1171         IncrRetrieved();
1172         (estate->es_processed)++;
1173 }
1174
1175 /* ----------------------------------------------------------------
1176  *              ExecInsert
1177  *
1178  *              INSERTs are trickier.. we have to insert the tuple into
1179  *              the base relation and insert appropriate tuples into the
1180  *              index relations.
1181  * ----------------------------------------------------------------
1182  */
1183 static void
1184 ExecInsert(TupleTableSlot *slot,
1185                    ItemPointer tupleid,
1186                    EState *estate)
1187 {
1188         HeapTuple       tuple;
1189         ResultRelInfo *resultRelInfo;
1190         Relation        resultRelationDesc;
1191         int                     numIndices;
1192         Oid                     newId;
1193
1194         /*
1195          * get the heap tuple out of the tuple table slot
1196          */
1197         tuple = slot->val;
1198
1199         /*
1200          * get information on the (current) result relation
1201          */
1202         resultRelInfo = estate->es_result_relation_info;
1203         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1204
1205         /* BEFORE ROW INSERT Triggers */
1206         if (resultRelInfo->ri_TrigDesc &&
1207           resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1208         {
1209                 HeapTuple       newtuple;
1210
1211                 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1212
1213                 if (newtuple == NULL)   /* "do nothing" */
1214                         return;
1215
1216                 if (newtuple != tuple)  /* modified by Trigger(s) */
1217                 {
1218                         /*
1219                          * Insert modified tuple into tuple table slot, replacing the
1220                          * original.  We assume that it was allocated in per-tuple
1221                          * memory context, and therefore will go away by itself. The
1222                          * tuple table slot should not try to clear it.
1223                          */
1224                         ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1225                         tuple = newtuple;
1226                 }
1227         }
1228
1229         /*
1230          * Check the constraints of the tuple
1231          */
1232         if (resultRelationDesc->rd_att->constr)
1233                 ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1234
1235         /*
1236          * insert the tuple
1237          */
1238         newId = heap_insert(resultRelationDesc, tuple,
1239                                                 estate->es_snapshot->curcid);
1240
1241         IncrAppended();
1242         (estate->es_processed)++;
1243         estate->es_lastoid = newId;
1244         setLastTid(&(tuple->t_self));
1245
1246         /*
1247          * process indices
1248          *
1249          * Note: heap_insert adds a new tuple to a relation.  As a side effect,
1250          * the tupleid of the new tuple is placed in the new tuple's t_ctid
1251          * field.
1252          */
1253         numIndices = resultRelInfo->ri_NumIndices;
1254         if (numIndices > 0)
1255                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1256
1257         /* AFTER ROW INSERT Triggers */
1258         if (resultRelInfo->ri_TrigDesc)
1259                 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1260 }
1261
1262 /* ----------------------------------------------------------------
1263  *              ExecDelete
1264  *
1265  *              DELETE is like UPDATE, we delete the tuple and its
1266  *              index tuples.
1267  * ----------------------------------------------------------------
1268  */
1269 static void
1270 ExecDelete(TupleTableSlot *slot,
1271                    ItemPointer tupleid,
1272                    EState *estate)
1273 {
1274         ResultRelInfo *resultRelInfo;
1275         Relation        resultRelationDesc;
1276         ItemPointerData ctid;
1277         int                     result;
1278
1279         /*
1280          * get information on the (current) result relation
1281          */
1282         resultRelInfo = estate->es_result_relation_info;
1283         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1284
1285         /* BEFORE ROW DELETE Triggers */
1286         if (resultRelInfo->ri_TrigDesc &&
1287           resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1288         {
1289                 bool            dodelete;
1290
1291                 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1292
1293                 if (!dodelete)                  /* "do nothing" */
1294                         return;
1295         }
1296
1297         /*
1298          * delete the tuple
1299          */
1300 ldelete:;
1301         result = heap_delete(resultRelationDesc, tupleid,
1302                                                  &ctid,
1303                                                  estate->es_snapshot->curcid);
1304         switch (result)
1305         {
1306                 case HeapTupleSelfUpdated:
1307                         /* already deleted by self; nothing to do */
1308                         return;
1309
1310                 case HeapTupleMayBeUpdated:
1311                         break;
1312
1313                 case HeapTupleUpdated:
1314                         if (XactIsoLevel == XACT_SERIALIZABLE)
1315                                 elog(ERROR, "Can't serialize access due to concurrent update");
1316                         else if (!(ItemPointerEquals(tupleid, &ctid)))
1317                         {
1318                                 TupleTableSlot *epqslot = EvalPlanQual(estate,
1319                                                            resultRelInfo->ri_RangeTableIndex, &ctid);
1320
1321                                 if (!TupIsNull(epqslot))
1322                                 {
1323                                         *tupleid = ctid;
1324                                         goto ldelete;
1325                                 }
1326                         }
1327                         /* tuple already deleted; nothing to do */
1328                         return;
1329
1330                 default:
1331                         elog(ERROR, "Unknown status %u from heap_delete", result);
1332                         return;
1333         }
1334
1335         IncrDeleted();
1336         (estate->es_processed)++;
1337
1338         /*
1339          * Note: Normally one would think that we have to delete index tuples
1340          * associated with the heap tuple now..
1341          *
1342          * ... but in POSTGRES, we have no need to do this because the vacuum
1343          * daemon automatically opens an index scan and deletes index tuples
1344          * when it finds deleted heap tuples. -cim 9/27/89
1345          */
1346
1347         /* AFTER ROW DELETE Triggers */
1348         if (resultRelInfo->ri_TrigDesc)
1349                 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1350 }
1351
1352 /* ----------------------------------------------------------------
1353  *              ExecUpdate
1354  *
1355  *              note: we can't run UPDATE queries with transactions
1356  *              off because UPDATEs are actually INSERTs and our
1357  *              scan will mistakenly loop forever, updating the tuple
1358  *              it just inserted..      This should be fixed but until it
1359  *              is, we don't want to get stuck in an infinite loop
1360  *              which corrupts your database..
1361  * ----------------------------------------------------------------
1362  */
1363 static void
1364 ExecUpdate(TupleTableSlot *slot,
1365                    ItemPointer tupleid,
1366                    EState *estate)
1367 {
1368         HeapTuple       tuple;
1369         ResultRelInfo *resultRelInfo;
1370         Relation        resultRelationDesc;
1371         ItemPointerData ctid;
1372         int                     result;
1373         int                     numIndices;
1374
1375         /*
1376          * abort the operation if not running transactions
1377          */
1378         if (IsBootstrapProcessingMode())
1379         {
1380                 elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1381                 return;
1382         }
1383
1384         /*
1385          * get the heap tuple out of the tuple table slot
1386          */
1387         tuple = slot->val;
1388
1389         /*
1390          * get information on the (current) result relation
1391          */
1392         resultRelInfo = estate->es_result_relation_info;
1393         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1394
1395         /* BEFORE ROW UPDATE Triggers */
1396         if (resultRelInfo->ri_TrigDesc &&
1397           resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1398         {
1399                 HeapTuple       newtuple;
1400
1401                 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1402                                                                                 tupleid, tuple);
1403
1404                 if (newtuple == NULL)   /* "do nothing" */
1405                         return;
1406
1407                 if (newtuple != tuple)  /* modified by Trigger(s) */
1408                 {
1409                         /*
1410                          * Insert modified tuple into tuple table slot, replacing the
1411                          * original.  We assume that it was allocated in per-tuple
1412                          * memory context, and therefore will go away by itself. The
1413                          * tuple table slot should not try to clear it.
1414                          */
1415                         ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1416                         tuple = newtuple;
1417                 }
1418         }
1419
1420         /*
1421          * Check the constraints of the tuple
1422          *
1423          * If we generate a new candidate tuple after EvalPlanQual testing, we
1424          * must loop back here and recheck constraints.  (We don't need to
1425          * redo triggers, however.      If there are any BEFORE triggers then
1426          * trigger.c will have done mark4update to lock the correct tuple, so
1427          * there's no need to do them again.)
1428          */
1429 lreplace:;
1430         if (resultRelationDesc->rd_att->constr)
1431                 ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1432
1433         /*
1434          * replace the heap tuple
1435          */
1436         result = heap_update(resultRelationDesc, tupleid, tuple,
1437                                                  &ctid,
1438                                                  estate->es_snapshot->curcid);
1439         switch (result)
1440         {
1441                 case HeapTupleSelfUpdated:
1442                         /* already deleted by self; nothing to do */
1443                         return;
1444
1445                 case HeapTupleMayBeUpdated:
1446                         break;
1447
1448                 case HeapTupleUpdated:
1449                         if (XactIsoLevel == XACT_SERIALIZABLE)
1450                                 elog(ERROR, "Can't serialize access due to concurrent update");
1451                         else if (!(ItemPointerEquals(tupleid, &ctid)))
1452                         {
1453                                 TupleTableSlot *epqslot = EvalPlanQual(estate,
1454                                                            resultRelInfo->ri_RangeTableIndex, &ctid);
1455
1456                                 if (!TupIsNull(epqslot))
1457                                 {
1458                                         *tupleid = ctid;
1459                                         tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1460                                         slot = ExecStoreTuple(tuple,
1461                                                                         estate->es_junkFilter->jf_resultSlot,
1462                                                                                   InvalidBuffer, true);
1463                                         goto lreplace;
1464                                 }
1465                         }
1466                         /* tuple already deleted; nothing to do */
1467                         return;
1468
1469                 default:
1470                         elog(ERROR, "Unknown status %u from heap_update", result);
1471                         return;
1472         }
1473
1474         IncrReplaced();
1475         (estate->es_processed)++;
1476
1477         /*
1478          * Note: instead of having to update the old index tuples associated
1479          * with the heap tuple, all we do is form and insert new index tuples.
1480          * This is because UPDATEs are actually DELETEs and INSERTs and index
1481          * tuple deletion is done automagically by the vacuum daemon. All we
1482          * do is insert new index tuples.  -cim 9/27/89
1483          */
1484
1485         /*
1486          * process indices
1487          *
1488          * heap_update updates a tuple in the base relation by invalidating it
1489          * and then inserting a new tuple to the relation.      As a side effect,
1490          * the tupleid of the new tuple is placed in the new tuple's t_ctid
1491          * field.  So we now insert index tuples using the new tupleid stored
1492          * there.
1493          */
1494
1495         numIndices = resultRelInfo->ri_NumIndices;
1496         if (numIndices > 0)
1497                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1498
1499         /* AFTER ROW UPDATE Triggers */
1500         if (resultRelInfo->ri_TrigDesc)
1501                 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1502 }
1503
1504 static char *
1505 ExecRelCheck(ResultRelInfo *resultRelInfo,
1506                          TupleTableSlot *slot, EState *estate)
1507 {
1508         Relation        rel = resultRelInfo->ri_RelationDesc;
1509         int                     ncheck = rel->rd_att->constr->num_check;
1510         ConstrCheck *check = rel->rd_att->constr->check;
1511         ExprContext *econtext;
1512         MemoryContext oldContext;
1513         List       *qual;
1514         int                     i;
1515
1516         /*
1517          * If first time through for this result relation, build expression
1518          * nodetrees for rel's constraint expressions.  Keep them in the
1519          * per-query memory context so they'll survive throughout the query.
1520          */
1521         if (resultRelInfo->ri_ConstraintExprs == NULL)
1522         {
1523                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1524                 resultRelInfo->ri_ConstraintExprs =
1525                         (List **) palloc(ncheck * sizeof(List *));
1526                 for (i = 0; i < ncheck; i++)
1527                 {
1528                         qual = (List *) stringToNode(check[i].ccbin);
1529                         resultRelInfo->ri_ConstraintExprs[i] = qual;
1530                 }
1531                 MemoryContextSwitchTo(oldContext);
1532         }
1533
1534         /*
1535          * We will use the EState's per-tuple context for evaluating
1536          * constraint expressions (creating it if it's not already there).
1537          */
1538         econtext = GetPerTupleExprContext(estate);
1539
1540         /* Arrange for econtext's scan tuple to be the tuple under test */
1541         econtext->ecxt_scantuple = slot;
1542
1543         /* And evaluate the constraints */
1544         for (i = 0; i < ncheck; i++)
1545         {
1546                 qual = resultRelInfo->ri_ConstraintExprs[i];
1547
1548                 /*
1549                  * NOTE: SQL92 specifies that a NULL result from a constraint
1550                  * expression is not to be treated as a failure.  Therefore, tell
1551                  * ExecQual to return TRUE for NULL.
1552                  */
1553                 if (!ExecQual(qual, econtext, true))
1554                         return check[i].ccname;
1555         }
1556
1557         /* NULL result means no error */
1558         return (char *) NULL;
1559 }
1560
1561 void
1562 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1563                                 TupleTableSlot *slot, EState *estate)
1564 {
1565         Relation        rel = resultRelInfo->ri_RelationDesc;
1566         HeapTuple       tuple = slot->val;
1567         TupleConstr *constr = rel->rd_att->constr;
1568
1569         Assert(constr);
1570
1571         if (constr->has_not_null)
1572         {
1573                 int                     natts = rel->rd_att->natts;
1574                 int                     attrChk;
1575
1576                 for (attrChk = 1; attrChk <= natts; attrChk++)
1577                 {
1578                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1579                                 heap_attisnull(tuple, attrChk))
1580                                 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1581                                          caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1582                 }
1583         }
1584
1585         if (constr->num_check > 0)
1586         {
1587                 char       *failed;
1588
1589                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1590                         elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1591                                  caller, failed, RelationGetRelationName(rel));
1592         }
1593 }
1594
1595 /*
1596  * Check a modified tuple to see if we want to process its updated version
1597  * under READ COMMITTED rules.
1598  *
1599  * See backend/executor/README for some info about how this works.
1600  */
1601 TupleTableSlot *
1602 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1603 {
1604         evalPlanQual *epq;
1605         EState     *epqstate;
1606         Relation        relation;
1607         HeapTupleData tuple;
1608         HeapTuple       copyTuple = NULL;
1609         int                     rtsize;
1610         bool            endNode;
1611
1612         Assert(rti != 0);
1613
1614         /*
1615          * find relation containing target tuple
1616          */
1617         if (estate->es_result_relation_info != NULL &&
1618                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1619                 relation = estate->es_result_relation_info->ri_RelationDesc;
1620         else
1621         {
1622                 List       *l;
1623
1624                 relation = NULL;
1625                 foreach(l, estate->es_rowMark)
1626                 {
1627                         if (((execRowMark *) lfirst(l))->rti == rti)
1628                         {
1629                                 relation = ((execRowMark *) lfirst(l))->relation;
1630                                 break;
1631                         }
1632                 }
1633                 if (relation == NULL)
1634                         elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1635         }
1636
1637         /*
1638          * fetch tid tuple
1639          *
1640          * Loop here to deal with updated or busy tuples
1641          */
1642         tuple.t_self = *tid;
1643         for (;;)
1644         {
1645                 Buffer          buffer;
1646
1647                 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1648                 {
1649                         TransactionId xwait = SnapshotDirty->xmax;
1650
1651                         if (TransactionIdIsValid(SnapshotDirty->xmin))
1652                                 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1653
1654                         /*
1655                          * If tuple is being updated by other transaction then we have
1656                          * to wait for its commit/abort.
1657                          */
1658                         if (TransactionIdIsValid(xwait))
1659                         {
1660                                 ReleaseBuffer(buffer);
1661                                 XactLockTableWait(xwait);
1662                                 continue;
1663                         }
1664
1665                         /*
1666                          * We got tuple - now copy it for use by recheck query.
1667                          */
1668                         copyTuple = heap_copytuple(&tuple);
1669                         ReleaseBuffer(buffer);
1670                         break;
1671                 }
1672
1673                 /*
1674                  * Oops! Invalid tuple. Have to check is it updated or deleted.
1675                  * Note that it's possible to get invalid SnapshotDirty->tid if
1676                  * tuple updated by this transaction. Have we to check this ?
1677                  */
1678                 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1679                         !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1680                 {
1681                         /* updated, so look at the updated copy */
1682                         tuple.t_self = SnapshotDirty->tid;
1683                         continue;
1684                 }
1685
1686                 /*
1687                  * Deleted or updated by this transaction; forget it.
1688                  */
1689                 return NULL;
1690         }
1691
1692         /*
1693          * For UPDATE/DELETE we have to return tid of actual row we're
1694          * executing PQ for.
1695          */
1696         *tid = tuple.t_self;
1697
1698         /*
1699          * Need to run a recheck subquery.      Find or create a PQ stack entry.
1700          */
1701         epq = (evalPlanQual *) estate->es_evalPlanQual;
1702         rtsize = length(estate->es_range_table);
1703         endNode = true;
1704
1705         if (epq != NULL && epq->rti == 0)
1706         {
1707                 /* Top PQ stack entry is idle, so re-use it */
1708                 Assert(!(estate->es_useEvalPlan) &&
1709                            epq->estate.es_evalPlanQual == NULL);
1710                 epq->rti = rti;
1711                 endNode = false;
1712         }
1713
1714         /*
1715          * If this is request for another RTE - Ra, - then we have to check
1716          * wasn't PlanQual requested for Ra already and if so then Ra' row was
1717          * updated again and we have to re-start old execution for Ra and
1718          * forget all what we done after Ra was suspended. Cool? -:))
1719          */
1720         if (epq != NULL && epq->rti != rti &&
1721                 epq->estate.es_evTuple[rti - 1] != NULL)
1722         {
1723                 do
1724                 {
1725                         evalPlanQual *oldepq;
1726
1727                         /* pop previous PlanQual from the stack */
1728                         epqstate = &(epq->estate);
1729                         oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1730                         Assert(oldepq->rti != 0);
1731                         /* stop execution */
1732                         ExecEndNode(epq->plan, NULL);
1733                         ExecDropTupleTable(epqstate->es_tupleTable, true);
1734                         epqstate->es_tupleTable = NULL;
1735                         heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1736                         epqstate->es_evTuple[epq->rti - 1] = NULL;
1737                         /* push current PQ to freePQ stack */
1738                         oldepq->free = epq;
1739                         epq = oldepq;
1740                         estate->es_evalPlanQual = (Pointer) epq;
1741                 } while (epq->rti != rti);
1742         }
1743
1744         /*
1745          * If we are requested for another RTE then we have to suspend
1746          * execution of current PlanQual and start execution for new one.
1747          */
1748         if (epq == NULL || epq->rti != rti)
1749         {
1750                 /* try to reuse plan used previously */
1751                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1752
1753                 if (newepq == NULL)             /* first call or freePQ stack is empty */
1754                 {
1755                         newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1756                         newepq->free = NULL;
1757
1758                         /*
1759                          * Each stack level has its own copy of the plan tree.  This
1760                          * is wasteful, but necessary as long as plan nodes point to
1761                          * exec state nodes rather than vice versa.  Note that
1762                          * copyfuncs.c doesn't attempt to copy the exec state nodes,
1763                          * which is a good thing in this situation.
1764                          */
1765                         newepq->plan = copyObject(estate->es_origPlan);
1766
1767                         /*
1768                          * Init stack level's EState.  We share top level's copy of
1769                          * es_result_relations array and other non-changing status. We
1770                          * need our own tupletable, es_param_exec_vals, and other
1771                          * changeable state.
1772                          */
1773                         epqstate = &(newepq->estate);
1774                         memcpy(epqstate, estate, sizeof(EState));
1775                         epqstate->es_direction = ForwardScanDirection;
1776                         if (estate->es_origPlan->nParamExec > 0)
1777                                 epqstate->es_param_exec_vals = (ParamExecData *)
1778                                         palloc(estate->es_origPlan->nParamExec *
1779                                                    sizeof(ParamExecData));
1780                         epqstate->es_tupleTable = NULL;
1781                         epqstate->es_per_tuple_exprcontext = NULL;
1782
1783                         /*
1784                          * Each epqstate must have its own es_evTupleNull state, but
1785                          * all the stack entries share es_evTuple state.  This allows
1786                          * sub-rechecks to inherit the value being examined by an
1787                          * outer recheck.
1788                          */
1789                         epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1790                         if (epq == NULL)
1791                                 /* first PQ stack entry */
1792                                 epqstate->es_evTuple = (HeapTuple *)
1793                                         palloc0(rtsize * sizeof(HeapTuple));
1794                         else
1795                                 /* later stack entries share the same storage */
1796                                 epqstate->es_evTuple = epq->estate.es_evTuple;
1797                 }
1798                 else
1799                 {
1800                         /* recycle previously used EState */
1801                         epqstate = &(newepq->estate);
1802                 }
1803                 /* push current PQ to the stack */
1804                 epqstate->es_evalPlanQual = (Pointer) epq;
1805                 epq = newepq;
1806                 estate->es_evalPlanQual = (Pointer) epq;
1807                 epq->rti = rti;
1808                 endNode = false;
1809         }
1810
1811         Assert(epq->rti == rti);
1812         epqstate = &(epq->estate);
1813
1814         /*
1815          * Ok - we're requested for the same RTE.  Unfortunately we still have
1816          * to end and restart execution of the plan, because ExecReScan
1817          * wouldn't ensure that upper plan nodes would reset themselves.  We
1818          * could make that work if insertion of the target tuple were
1819          * integrated with the Param mechanism somehow, so that the upper plan
1820          * nodes know that their children's outputs have changed.
1821          */
1822         if (endNode)
1823         {
1824                 /* stop execution */
1825                 ExecEndNode(epq->plan, NULL);
1826                 ExecDropTupleTable(epqstate->es_tupleTable, true);
1827                 epqstate->es_tupleTable = NULL;
1828         }
1829
1830         /*
1831          * free old RTE' tuple, if any, and store target tuple where
1832          * relation's scan node will see it
1833          */
1834         if (epqstate->es_evTuple[rti - 1] != NULL)
1835                 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1836         epqstate->es_evTuple[rti - 1] = copyTuple;
1837
1838         /*
1839          * Initialize for new recheck query; be careful to copy down state
1840          * that might have changed in top EState.
1841          */
1842         epqstate->es_result_relation_info = estate->es_result_relation_info;
1843         epqstate->es_junkFilter = estate->es_junkFilter;
1844         if (estate->es_origPlan->nParamExec > 0)
1845                 memset(epqstate->es_param_exec_vals, 0,
1846                            estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1847         memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1848         epqstate->es_useEvalPlan = false;
1849         Assert(epqstate->es_tupleTable == NULL);
1850         epqstate->es_tupleTable =
1851                 ExecCreateTupleTable(estate->es_tupleTable->size);
1852
1853         ExecInitNode(epq->plan, epqstate, NULL);
1854
1855         return EvalPlanQualNext(estate);
1856 }
1857
1858 static TupleTableSlot *
1859 EvalPlanQualNext(EState *estate)
1860 {
1861         evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1862         EState     *epqstate = &(epq->estate);
1863         evalPlanQual *oldepq;
1864         TupleTableSlot *slot;
1865
1866         Assert(epq->rti != 0);
1867
1868 lpqnext:;
1869         slot = ExecProcNode(epq->plan, NULL);
1870
1871         /*
1872          * No more tuples for this PQ. Continue previous one.
1873          */
1874         if (TupIsNull(slot))
1875         {
1876                 /* stop execution */
1877                 ExecEndNode(epq->plan, NULL);
1878                 ExecDropTupleTable(epqstate->es_tupleTable, true);
1879                 epqstate->es_tupleTable = NULL;
1880                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1881                 epqstate->es_evTuple[epq->rti - 1] = NULL;
1882                 /* pop old PQ from the stack */
1883                 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1884                 if (oldepq == (evalPlanQual *) NULL)
1885                 {
1886                         epq->rti = 0;           /* this is the first (oldest) */
1887                         estate->es_useEvalPlan = false;         /* PQ - mark as free and          */
1888                         return (NULL);          /* continue Query execution   */
1889                 }
1890                 Assert(oldepq->rti != 0);
1891                 /* push current PQ to freePQ stack */
1892                 oldepq->free = epq;
1893                 epq = oldepq;
1894                 epqstate = &(epq->estate);
1895                 estate->es_evalPlanQual = (Pointer) epq;
1896                 goto lpqnext;
1897         }
1898
1899         return (slot);
1900 }
1901
1902 static void
1903 EndEvalPlanQual(EState *estate)
1904 {
1905         evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1906         EState     *epqstate = &(epq->estate);
1907         evalPlanQual *oldepq;
1908
1909         if (epq->rti == 0)                      /* plans already shutdowned */
1910         {
1911                 Assert(epq->estate.es_evalPlanQual == NULL);
1912                 return;
1913         }
1914
1915         for (;;)
1916         {
1917                 /* stop execution */
1918                 ExecEndNode(epq->plan, NULL);
1919                 ExecDropTupleTable(epqstate->es_tupleTable, true);
1920                 epqstate->es_tupleTable = NULL;
1921                 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1922                 {
1923                         heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1924                         epqstate->es_evTuple[epq->rti - 1] = NULL;
1925                 }
1926                 /* pop old PQ from the stack */
1927                 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1928                 if (oldepq == (evalPlanQual *) NULL)
1929                 {
1930                         epq->rti = 0;           /* this is the first (oldest) */
1931                         estate->es_useEvalPlan = false;         /* PQ - mark as free */
1932                         break;
1933                 }
1934                 Assert(oldepq->rti != 0);
1935                 /* push current PQ to freePQ stack */
1936                 oldepq->free = epq;
1937                 epq = oldepq;
1938                 epqstate = &(epq->estate);
1939                 estate->es_evalPlanQual = (Pointer) epq;
1940         }
1941 }