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