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