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