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