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