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