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