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