1 /*-------------------------------------------------------------------------
4 * top level executor interface routines
11 * The old ExecutorMain() has been replaced by ExecutorStart(),
12 * ExecutorRun() and ExecutorEnd()
14 * These three procedures are the external interfaces to the executor.
15 * In each case, the query descriptor is required as an argument.
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.
21 * ExecutorRun accepts direction and count arguments that specify whether
22 * the plan is to be executed forwards, backwards, and for how many tuples.
24 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
29 * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.196 2003/01/08 23:32:29 tgl Exp $
31 *-------------------------------------------------------------------------
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"
49 typedef struct execRowMark
56 typedef struct evalPlanQual
61 struct evalPlanQual *next; /* stack of active PlanQual plans */
62 struct evalPlanQual *free; /* list of free PlanQual plans */
65 /* decls for local routines only used within this module */
66 static void InitPlan(QueryDesc *queryDesc);
67 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
68 Index resultRelationIndex,
71 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
74 ScanDirection direction,
75 DestReceiver *destfunc);
76 static void ExecSelect(TupleTableSlot *slot,
77 DestReceiver *destfunc,
79 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
81 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
83 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
85 static TupleTableSlot *EvalPlanQualNext(EState *estate);
86 static void EndEvalPlanQual(EState *estate);
87 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
88 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
89 evalPlanQual *priorepq);
90 static void EvalPlanQualStop(evalPlanQual *epq);
92 /* end of local decls */
95 /* ----------------------------------------------------------------
98 * This routine must be called at the beginning of any execution of any
101 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
102 * clear why we bother to separate the two functions, but...). The tupDesc
103 * field of the QueryDesc is filled in to describe the tuples that will be
104 * returned, and the internal fields (estate and planstate) are set up.
106 * NB: the CurrentMemoryContext when this is called will become the parent
107 * of the per-query context used for this Executor invocation.
108 * ----------------------------------------------------------------
111 ExecutorStart(QueryDesc *queryDesc)
114 MemoryContext oldcontext;
116 /* sanity checks: queryDesc must not be started already */
117 Assert(queryDesc != NULL);
118 Assert(queryDesc->estate == NULL);
121 * Build EState, switch into per-query memory context for startup.
123 estate = CreateExecutorState();
124 queryDesc->estate = estate;
126 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
129 * Fill in parameters, if any, from queryDesc
131 estate->es_param_list_info = queryDesc->params;
133 if (queryDesc->plantree->nParamExec > 0)
134 estate->es_param_exec_vals = (ParamExecData *)
135 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
137 estate->es_instrument = queryDesc->doInstrument;
140 * Make our own private copy of the current query snapshot data.
142 * This "freezes" our idea of which tuples are good and which are not for
143 * the life of this query, even if it outlives the current command and
146 estate->es_snapshot = CopyQuerySnapshot();
149 * Initialize the plan state tree
153 MemoryContextSwitchTo(oldcontext);
156 /* ----------------------------------------------------------------
159 * This is the main routine of the executor module. It accepts
160 * the query descriptor from the traffic cop and executes the
163 * ExecutorStart must have been called already.
165 * If direction is NoMovementScanDirection then nothing is done
166 * except to start up/shut down the destination. Otherwise,
167 * we retrieve up to 'count' tuples in the specified direction.
169 * Note: count = 0 is interpreted as no portal limit, i.e., run to
172 * ----------------------------------------------------------------
175 ExecutorRun(QueryDesc *queryDesc,
176 ScanDirection direction, long count)
181 DestReceiver *destfunc;
182 TupleTableSlot *result;
183 MemoryContext oldcontext;
186 Assert(queryDesc != NULL);
188 estate = queryDesc->estate;
190 Assert(estate != NULL);
193 * Switch into per-query memory context
195 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
198 * extract information from the query descriptor and the query
201 operation = queryDesc->operation;
202 dest = queryDesc->dest;
205 * startup tuple receiver
207 estate->es_processed = 0;
208 estate->es_lastoid = InvalidOid;
210 destfunc = DestToFunction(dest);
211 (*destfunc->setup) (destfunc, (int) operation,
212 queryDesc->portalName, queryDesc->tupDesc);
217 if (direction == NoMovementScanDirection)
220 result = ExecutePlan(estate,
221 queryDesc->planstate,
230 (*destfunc->cleanup) (destfunc);
232 MemoryContextSwitchTo(oldcontext);
237 /* ----------------------------------------------------------------
240 * This routine must be called at the end of execution of any
242 * ----------------------------------------------------------------
245 ExecutorEnd(QueryDesc *queryDesc)
248 MemoryContext oldcontext;
251 Assert(queryDesc != NULL);
253 estate = queryDesc->estate;
255 Assert(estate != NULL);
258 * Switch into per-query memory context to run ExecEndPlan
260 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
262 ExecEndPlan(queryDesc->planstate, estate);
265 * Must switch out of context before destroying it
267 MemoryContextSwitchTo(oldcontext);
270 * Release EState and per-query memory context. This should release
271 * everything the executor has allocated.
273 FreeExecutorState(estate);
275 /* Reset queryDesc fields that no longer point to anything */
276 queryDesc->tupDesc = NULL;
277 queryDesc->estate = NULL;
278 queryDesc->planstate = NULL;
284 * Check access permissions for all relations listed in a range table.
287 ExecCheckRTPerms(List *rangeTable, CmdType operation)
291 foreach(lp, rangeTable)
293 RangeTblEntry *rte = lfirst(lp);
295 ExecCheckRTEPerms(rte, operation);
301 * Check access permissions for a single RTE.
304 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
308 AclResult aclcheck_result;
311 * If it's a subquery, recursively examine its rangetable.
313 if (rte->rtekind == RTE_SUBQUERY)
315 ExecCheckRTPerms(rte->subquery->rtable, operation);
320 * Otherwise, only plain-relation RTEs need to be checked here.
321 * Function RTEs are checked by init_fcache when the function is prepared
322 * for execution. Join and special RTEs need no checks.
324 if (rte->rtekind != RTE_RELATION)
330 * userid to check as: current user unless we have a setuid
333 * Note: GetUserId() is presently fast enough that there's no harm in
334 * calling it separately for each RTE. If that stops being true, we
335 * could call it once in ExecCheckRTPerms and pass the userid down
336 * from there. But for now, no need for the extra clutter.
338 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
340 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
342 if (rte->checkForRead)
344 aclcheck_result = CHECK(ACL_SELECT);
345 if (aclcheck_result != ACLCHECK_OK)
346 aclcheck_error(aclcheck_result, get_rel_name(relOid));
349 if (rte->checkForWrite)
352 * Note: write access in a SELECT context means SELECT FOR UPDATE.
353 * Right now we don't distinguish that from true update as far as
354 * permissions checks are concerned.
359 aclcheck_result = CHECK(ACL_INSERT);
363 aclcheck_result = CHECK(ACL_UPDATE);
366 aclcheck_result = CHECK(ACL_DELETE);
369 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
371 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
374 if (aclcheck_result != ACLCHECK_OK)
375 aclcheck_error(aclcheck_result, get_rel_name(relOid));
380 /* ===============================================================
381 * ===============================================================
382 static routines follow
383 * ===============================================================
384 * ===============================================================
388 /* ----------------------------------------------------------------
391 * Initializes the query plan: open files, allocate storage
392 * and start up the rule manager
393 * ----------------------------------------------------------------
396 InitPlan(QueryDesc *queryDesc)
398 CmdType operation = queryDesc->operation;
399 Query *parseTree = queryDesc->parsetree;
400 Plan *plan = queryDesc->plantree;
401 EState *estate = queryDesc->estate;
402 PlanState *planstate;
404 Relation intoRelationDesc;
408 * Do permissions checks. It's sufficient to examine the query's
409 * top rangetable here --- subplan RTEs will be checked during
412 ExecCheckRTPerms(parseTree->rtable, operation);
415 * get information from query descriptor
417 rangeTable = parseTree->rtable;
420 * initialize the node's execution state
422 estate->es_range_table = rangeTable;
425 * if there is a result relation, initialize result relation stuff
427 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
429 List *resultRelations = parseTree->resultRelations;
430 int numResultRelations;
431 ResultRelInfo *resultRelInfos;
433 if (resultRelations != NIL)
436 * Multiple result relations (due to inheritance)
437 * parseTree->resultRelations identifies them all
439 ResultRelInfo *resultRelInfo;
441 numResultRelations = length(resultRelations);
442 resultRelInfos = (ResultRelInfo *)
443 palloc(numResultRelations * sizeof(ResultRelInfo));
444 resultRelInfo = resultRelInfos;
445 while (resultRelations != NIL)
447 initResultRelInfo(resultRelInfo,
448 lfirsti(resultRelations),
452 resultRelations = lnext(resultRelations);
458 * Single result relation identified by
459 * parseTree->resultRelation
461 numResultRelations = 1;
462 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
463 initResultRelInfo(resultRelInfos,
464 parseTree->resultRelation,
469 estate->es_result_relations = resultRelInfos;
470 estate->es_num_result_relations = numResultRelations;
471 /* Initialize to first or only result rel */
472 estate->es_result_relation_info = resultRelInfos;
477 * if no result relation, then set state appropriately
479 estate->es_result_relations = NULL;
480 estate->es_num_result_relations = 0;
481 estate->es_result_relation_info = NULL;
485 * Have to lock relations selected for update
487 estate->es_rowMark = NIL;
488 if (parseTree->rowMarks != NIL)
492 foreach(l, parseTree->rowMarks)
494 Index rti = lfirsti(l);
495 Oid relid = getrelid(rti, rangeTable);
499 relation = heap_open(relid, RowShareLock);
500 erm = (execRowMark *) palloc(sizeof(execRowMark));
501 erm->relation = relation;
503 snprintf(erm->resname, 32, "ctid%u", rti);
504 estate->es_rowMark = lappend(estate->es_rowMark, erm);
509 * initialize the executor "tuple" table. We need slots for all the
510 * plan nodes, plus possibly output slots for the junkfilter(s). At
511 * this point we aren't sure if we need junkfilters, so just add slots
512 * for them unconditionally.
515 int nSlots = ExecCountSlotsNode(plan);
517 if (parseTree->resultRelations != NIL)
518 nSlots += length(parseTree->resultRelations);
521 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
524 /* mark EvalPlanQual not active */
525 estate->es_topPlan = plan;
526 estate->es_evalPlanQual = NULL;
527 estate->es_evTupleNull = NULL;
528 estate->es_evTuple = NULL;
529 estate->es_useEvalPlan = false;
532 * initialize the private state information for all the nodes in the
533 * query tree. This opens files, allocates storage and leaves us
534 * ready to start processing tuples.
536 planstate = ExecInitNode(plan, estate);
539 * Get the tuple descriptor describing the type of tuples to return.
540 * (this is especially important if we are creating a relation with
543 tupType = ExecGetTupType(planstate);
546 * Initialize the junk filter if needed. SELECT and INSERT queries
547 * need a filter if there are any junk attrs in the tlist. UPDATE and
548 * DELETE always need one, since there's always a junk 'ctid'
549 * attribute present --- no need to look first.
552 bool junk_filter_needed = false;
559 foreach(tlist, plan->targetlist)
561 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
563 if (tle->resdom->resjunk)
565 junk_filter_needed = true;
572 junk_filter_needed = true;
578 if (junk_filter_needed)
581 * If there are multiple result relations, each one needs its
582 * own junk filter. Note this is only possible for
583 * UPDATE/DELETE, so we can't be fooled by some needing a
584 * filter and some not.
586 if (parseTree->resultRelations != NIL)
588 PlanState **appendplans;
590 ResultRelInfo *resultRelInfo;
593 /* Top plan had better be an Append here. */
594 Assert(IsA(plan, Append));
595 Assert(((Append *) plan)->isTarget);
596 Assert(IsA(planstate, AppendState));
597 appendplans = ((AppendState *) planstate)->appendplans;
598 as_nplans = ((AppendState *) planstate)->as_nplans;
599 Assert(as_nplans == estate->es_num_result_relations);
600 resultRelInfo = estate->es_result_relations;
601 for (i = 0; i < as_nplans; i++)
603 PlanState *subplan = appendplans[i];
606 j = ExecInitJunkFilter(subplan->plan->targetlist,
607 ExecGetTupType(subplan),
608 ExecAllocTableSlot(estate->es_tupleTable));
609 resultRelInfo->ri_junkFilter = j;
614 * Set active junkfilter too; at this point ExecInitAppend
615 * has already selected an active result relation...
617 estate->es_junkFilter =
618 estate->es_result_relation_info->ri_junkFilter;
622 /* Normal case with just one JunkFilter */
625 j = ExecInitJunkFilter(planstate->plan->targetlist,
627 ExecAllocTableSlot(estate->es_tupleTable));
628 estate->es_junkFilter = j;
629 if (estate->es_result_relation_info)
630 estate->es_result_relation_info->ri_junkFilter = j;
632 /* For SELECT, want to return the cleaned tuple type */
633 if (operation == CMD_SELECT)
634 tupType = j->jf_cleanTupType;
638 estate->es_junkFilter = NULL;
642 * initialize the "into" relation
644 intoRelationDesc = (Relation) NULL;
646 if (operation == CMD_SELECT)
648 if (!parseTree->isPortal)
651 * a select into table --- need to create the "into" table
653 if (parseTree->into != NULL)
662 * find namespace to create in, check permissions
664 intoName = parseTree->into->relname;
665 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
667 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
669 if (aclresult != ACLCHECK_OK)
670 aclcheck_error(aclresult,
671 get_namespace_name(namespaceId));
674 * have to copy tupType to get rid of constraints
676 tupdesc = CreateTupleDescCopy(tupType);
679 * Formerly we forced the output table to have OIDs, but
680 * as of 7.3 it will not have OIDs, because it's too late
681 * here to change the tupdescs of the already-initialized
682 * plan tree. (Perhaps we could recurse and change them
683 * all, but it's not really worth the trouble IMHO...)
687 heap_create_with_catalog(intoName,
693 allowSystemTableMods);
695 FreeTupleDesc(tupdesc);
698 * Advance command counter so that the newly-created
699 * relation's catalog tuples will be visible to heap_open.
701 CommandCounterIncrement();
704 * If necessary, create a TOAST table for the into
705 * relation. Note that AlterTableCreateToastTable ends
706 * with CommandCounterIncrement(), so that the TOAST table
707 * will be visible for insertion.
709 AlterTableCreateToastTable(intoRelationId, true);
711 intoRelationDesc = heap_open(intoRelationId,
712 AccessExclusiveLock);
717 estate->es_into_relation_descriptor = intoRelationDesc;
719 queryDesc->tupDesc = tupType;
720 queryDesc->planstate = planstate;
724 * Initialize ResultRelInfo data for one result relation
727 initResultRelInfo(ResultRelInfo *resultRelInfo,
728 Index resultRelationIndex,
732 Oid resultRelationOid;
733 Relation resultRelationDesc;
735 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
736 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
738 switch (resultRelationDesc->rd_rel->relkind)
740 case RELKIND_SEQUENCE:
741 elog(ERROR, "You can't change sequence relation %s",
742 RelationGetRelationName(resultRelationDesc));
744 case RELKIND_TOASTVALUE:
745 elog(ERROR, "You can't change toast relation %s",
746 RelationGetRelationName(resultRelationDesc));
749 elog(ERROR, "You can't change view relation %s",
750 RelationGetRelationName(resultRelationDesc));
754 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
755 resultRelInfo->type = T_ResultRelInfo;
756 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
757 resultRelInfo->ri_RelationDesc = resultRelationDesc;
758 resultRelInfo->ri_NumIndices = 0;
759 resultRelInfo->ri_IndexRelationDescs = NULL;
760 resultRelInfo->ri_IndexRelationInfo = NULL;
761 /* make a copy so as not to depend on relcache info not changing... */
762 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
763 resultRelInfo->ri_TrigFunctions = NULL;
764 resultRelInfo->ri_ConstraintExprs = NULL;
765 resultRelInfo->ri_junkFilter = NULL;
768 * If there are indices on the result relation, open them and save
769 * descriptors in the result relation info, so that we can add new
770 * index entries for the tuples we add/update. We need not do this
771 * for a DELETE, however, since deletion doesn't affect indexes.
773 if (resultRelationDesc->rd_rel->relhasindex &&
774 operation != CMD_DELETE)
775 ExecOpenIndices(resultRelInfo);
778 /* ----------------------------------------------------------------
781 * Cleans up the query plan -- closes files and frees up storage
783 * NOTE: we are no longer very worried about freeing storage per se
784 * in this code; FreeExecutorState should be guaranteed to release all
785 * memory that needs to be released. What we are worried about doing
786 * is closing relations and dropping buffer pins. Thus, for example,
787 * tuple tables must be cleared or dropped to ensure pins are released.
788 * ----------------------------------------------------------------
791 ExecEndPlan(PlanState *planstate, EState *estate)
793 ResultRelInfo *resultRelInfo;
798 * shut down any PlanQual processing we were doing
800 if (estate->es_evalPlanQual != NULL)
801 EndEvalPlanQual(estate);
804 * shut down the node-type-specific query processing
806 ExecEndNode(planstate);
809 * destroy the executor "tuple" table.
811 ExecDropTupleTable(estate->es_tupleTable, true);
812 estate->es_tupleTable = NULL;
815 * close the result relation(s) if any, but hold locks until xact
818 resultRelInfo = estate->es_result_relations;
819 for (i = estate->es_num_result_relations; i > 0; i--)
821 /* Close indices and then the relation itself */
822 ExecCloseIndices(resultRelInfo);
823 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
828 * close the "into" relation if necessary, again keeping lock
830 if (estate->es_into_relation_descriptor != NULL)
831 heap_close(estate->es_into_relation_descriptor, NoLock);
834 * close any relations selected FOR UPDATE, again keeping locks
836 foreach(l, estate->es_rowMark)
838 execRowMark *erm = lfirst(l);
840 heap_close(erm->relation, NoLock);
844 /* ----------------------------------------------------------------
847 * processes the query plan to retrieve 'numberTuples' tuples in the
848 * direction specified.
850 * Retrieves all tuples if numberTuples is 0
852 * result is either a slot containing the last tuple in the case
853 * of a SELECT or NULL otherwise.
855 * Note: the ctid attribute is a 'junk' attribute that is removed before the
857 * ----------------------------------------------------------------
859 static TupleTableSlot *
860 ExecutePlan(EState *estate,
861 PlanState *planstate,
864 ScanDirection direction,
865 DestReceiver *destfunc)
867 JunkFilter *junkfilter;
868 TupleTableSlot *slot;
869 ItemPointer tupleid = NULL;
870 ItemPointerData tuple_ctid;
871 long current_tuple_count;
872 TupleTableSlot *result;
875 * initialize local variables
878 current_tuple_count = 0;
884 estate->es_direction = direction;
887 * Process BEFORE EACH STATEMENT triggers
892 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
895 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
898 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
906 * Loop until we've processed the proper number of tuples from the
912 /* Reset the per-output-tuple exprcontext */
913 ResetPerTupleExprContext(estate);
916 * Execute the plan and obtain a tuple
919 if (estate->es_useEvalPlan)
921 slot = EvalPlanQualNext(estate);
923 slot = ExecProcNode(planstate);
926 slot = ExecProcNode(planstate);
929 * if the tuple is null, then we assume there is nothing more to
930 * process so we just return null...
939 * if we have a junk filter, then project a new tuple with the
942 * Store this new "clean" tuple in the junkfilter's resultSlot.
943 * (Formerly, we stored it back over the "dirty" tuple, which is
944 * WRONG because that tuple slot has the wrong descriptor.)
946 * Also, extract all the junk information we need.
948 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
955 * extract the 'ctid' junk attribute.
957 if (operation == CMD_UPDATE || operation == CMD_DELETE)
959 if (!ExecGetJunkAttribute(junkfilter,
964 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
966 /* shouldn't ever get a null result... */
968 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
970 tupleid = (ItemPointer) DatumGetPointer(datum);
971 tuple_ctid = *tupleid; /* make sure we don't free the
973 tupleid = &tuple_ctid;
975 else if (estate->es_rowMark != NIL)
980 foreach(l, estate->es_rowMark)
982 execRowMark *erm = lfirst(l);
985 TupleTableSlot *newSlot;
988 if (!ExecGetJunkAttribute(junkfilter,
993 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
996 /* shouldn't ever get a null result... */
998 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1001 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1002 test = heap_mark4update(erm->relation, &tuple, &buffer,
1003 estate->es_snapshot->curcid);
1004 ReleaseBuffer(buffer);
1007 case HeapTupleSelfUpdated:
1008 /* treat it as deleted; do not process */
1011 case HeapTupleMayBeUpdated:
1014 case HeapTupleUpdated:
1015 if (XactIsoLevel == XACT_SERIALIZABLE)
1016 elog(ERROR, "Can't serialize access due to concurrent update");
1017 if (!(ItemPointerEquals(&(tuple.t_self),
1018 (ItemPointer) DatumGetPointer(datum))))
1020 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1021 if (!(TupIsNull(newSlot)))
1024 estate->es_useEvalPlan = true;
1030 * if tuple was deleted or PlanQual failed for
1031 * updated tuple - we must not return this
1037 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1044 * Finally create a new "clean" tuple with all junk attributes
1047 newTuple = ExecRemoveJunk(junkfilter, slot);
1049 slot = ExecStoreTuple(newTuple, /* tuple to store */
1050 junkfilter->jf_resultSlot, /* dest slot */
1051 InvalidBuffer, /* this tuple has no
1053 true); /* tuple should be pfreed */
1057 * now that we have a tuple, do the appropriate thing with it..
1058 * either return it to the user, add it to a relation someplace,
1059 * delete it from a relation, or modify some of its attributes.
1064 ExecSelect(slot, /* slot containing tuple */
1065 destfunc, /* destination's tuple-receiver
1072 ExecInsert(slot, tupleid, estate);
1077 ExecDelete(slot, tupleid, estate);
1082 ExecUpdate(slot, tupleid, estate);
1087 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1093 * check our tuple count.. if we've processed the proper number
1094 * then quit, else loop again and process more tuples. Zero
1095 * numberTuples means no limit.
1097 current_tuple_count++;
1098 if (numberTuples && numberTuples == current_tuple_count)
1103 * Process AFTER EACH STATEMENT triggers
1108 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1111 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1114 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1122 * here, result is either a slot containing a tuple in the case of a
1123 * SELECT or NULL otherwise.
1128 /* ----------------------------------------------------------------
1131 * SELECTs are easy.. we just pass the tuple to the appropriate
1132 * print function. The only complexity is when we do a
1133 * "SELECT INTO", in which case we insert the tuple into
1134 * the appropriate relation (note: this is a newly created relation
1135 * so we don't need to worry about indices or locks.)
1136 * ----------------------------------------------------------------
1139 ExecSelect(TupleTableSlot *slot,
1140 DestReceiver *destfunc,
1147 * get the heap tuple out of the tuple table slot
1150 attrtype = slot->ttc_tupleDescriptor;
1153 * insert the tuple into the "into relation"
1155 if (estate->es_into_relation_descriptor != NULL)
1157 heap_insert(estate->es_into_relation_descriptor, tuple,
1158 estate->es_snapshot->curcid);
1163 * send the tuple to the front end (or the screen)
1165 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1167 (estate->es_processed)++;
1170 /* ----------------------------------------------------------------
1173 * INSERTs are trickier.. we have to insert the tuple into
1174 * the base relation and insert appropriate tuples into the
1176 * ----------------------------------------------------------------
1179 ExecInsert(TupleTableSlot *slot,
1180 ItemPointer tupleid,
1184 ResultRelInfo *resultRelInfo;
1185 Relation resultRelationDesc;
1190 * get the heap tuple out of the tuple table slot
1195 * get information on the (current) result relation
1197 resultRelInfo = estate->es_result_relation_info;
1198 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1200 /* BEFORE ROW INSERT Triggers */
1201 if (resultRelInfo->ri_TrigDesc &&
1202 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1206 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1208 if (newtuple == NULL) /* "do nothing" */
1211 if (newtuple != tuple) /* modified by Trigger(s) */
1214 * Insert modified tuple into tuple table slot, replacing the
1215 * original. We assume that it was allocated in per-tuple
1216 * memory context, and therefore will go away by itself. The
1217 * tuple table slot should not try to clear it.
1219 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1225 * Check the constraints of the tuple
1227 if (resultRelationDesc->rd_att->constr)
1228 ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1233 newId = heap_insert(resultRelationDesc, tuple,
1234 estate->es_snapshot->curcid);
1237 (estate->es_processed)++;
1238 estate->es_lastoid = newId;
1239 setLastTid(&(tuple->t_self));
1244 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1245 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1248 numIndices = resultRelInfo->ri_NumIndices;
1250 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1252 /* AFTER ROW INSERT Triggers */
1253 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1256 /* ----------------------------------------------------------------
1259 * DELETE is like UPDATE, we delete the tuple and its
1261 * ----------------------------------------------------------------
1264 ExecDelete(TupleTableSlot *slot,
1265 ItemPointer tupleid,
1268 ResultRelInfo *resultRelInfo;
1269 Relation resultRelationDesc;
1270 ItemPointerData ctid;
1274 * get information on the (current) result relation
1276 resultRelInfo = estate->es_result_relation_info;
1277 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1279 /* BEFORE ROW DELETE Triggers */
1280 if (resultRelInfo->ri_TrigDesc &&
1281 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1285 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1287 if (!dodelete) /* "do nothing" */
1295 result = heap_delete(resultRelationDesc, tupleid,
1297 estate->es_snapshot->curcid);
1300 case HeapTupleSelfUpdated:
1301 /* already deleted by self; nothing to do */
1304 case HeapTupleMayBeUpdated:
1307 case HeapTupleUpdated:
1308 if (XactIsoLevel == XACT_SERIALIZABLE)
1309 elog(ERROR, "Can't serialize access due to concurrent update");
1310 else if (!(ItemPointerEquals(tupleid, &ctid)))
1312 TupleTableSlot *epqslot = EvalPlanQual(estate,
1313 resultRelInfo->ri_RangeTableIndex, &ctid);
1315 if (!TupIsNull(epqslot))
1321 /* tuple already deleted; nothing to do */
1325 elog(ERROR, "Unknown status %u from heap_delete", result);
1330 (estate->es_processed)++;
1333 * Note: Normally one would think that we have to delete index tuples
1334 * associated with the heap tuple now..
1336 * ... but in POSTGRES, we have no need to do this because the vacuum
1337 * daemon automatically opens an index scan and deletes index tuples
1338 * when it finds deleted heap tuples. -cim 9/27/89
1341 /* AFTER ROW DELETE Triggers */
1342 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1345 /* ----------------------------------------------------------------
1348 * note: we can't run UPDATE queries with transactions
1349 * off because UPDATEs are actually INSERTs and our
1350 * scan will mistakenly loop forever, updating the tuple
1351 * it just inserted.. This should be fixed but until it
1352 * is, we don't want to get stuck in an infinite loop
1353 * which corrupts your database..
1354 * ----------------------------------------------------------------
1357 ExecUpdate(TupleTableSlot *slot,
1358 ItemPointer tupleid,
1362 ResultRelInfo *resultRelInfo;
1363 Relation resultRelationDesc;
1364 ItemPointerData ctid;
1369 * abort the operation if not running transactions
1371 if (IsBootstrapProcessingMode())
1373 elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1378 * get the heap tuple out of the tuple table slot
1383 * get information on the (current) result relation
1385 resultRelInfo = estate->es_result_relation_info;
1386 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1388 /* BEFORE ROW UPDATE Triggers */
1389 if (resultRelInfo->ri_TrigDesc &&
1390 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1394 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1397 if (newtuple == NULL) /* "do nothing" */
1400 if (newtuple != tuple) /* modified by Trigger(s) */
1403 * Insert modified tuple into tuple table slot, replacing the
1404 * original. We assume that it was allocated in per-tuple
1405 * memory context, and therefore will go away by itself. The
1406 * tuple table slot should not try to clear it.
1408 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1414 * Check the constraints of the tuple
1416 * If we generate a new candidate tuple after EvalPlanQual testing, we
1417 * must loop back here and recheck constraints. (We don't need to
1418 * redo triggers, however. If there are any BEFORE triggers then
1419 * trigger.c will have done mark4update to lock the correct tuple, so
1420 * there's no need to do them again.)
1423 if (resultRelationDesc->rd_att->constr)
1424 ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1427 * replace the heap tuple
1429 result = heap_update(resultRelationDesc, tupleid, tuple,
1431 estate->es_snapshot->curcid);
1434 case HeapTupleSelfUpdated:
1435 /* already deleted by self; nothing to do */
1438 case HeapTupleMayBeUpdated:
1441 case HeapTupleUpdated:
1442 if (XactIsoLevel == XACT_SERIALIZABLE)
1443 elog(ERROR, "Can't serialize access due to concurrent update");
1444 else if (!(ItemPointerEquals(tupleid, &ctid)))
1446 TupleTableSlot *epqslot = EvalPlanQual(estate,
1447 resultRelInfo->ri_RangeTableIndex, &ctid);
1449 if (!TupIsNull(epqslot))
1452 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1453 slot = ExecStoreTuple(tuple,
1454 estate->es_junkFilter->jf_resultSlot,
1455 InvalidBuffer, true);
1459 /* tuple already deleted; nothing to do */
1463 elog(ERROR, "Unknown status %u from heap_update", result);
1468 (estate->es_processed)++;
1471 * Note: instead of having to update the old index tuples associated
1472 * with the heap tuple, all we do is form and insert new index tuples.
1473 * This is because UPDATEs are actually DELETEs and INSERTs and index
1474 * tuple deletion is done automagically by the vacuum daemon. All we
1475 * do is insert new index tuples. -cim 9/27/89
1481 * heap_update updates a tuple in the base relation by invalidating it
1482 * and then inserting a new tuple to the relation. As a side effect,
1483 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1484 * field. So we now insert index tuples using the new tupleid stored
1488 numIndices = resultRelInfo->ri_NumIndices;
1490 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1492 /* AFTER ROW UPDATE Triggers */
1493 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1497 ExecRelCheck(ResultRelInfo *resultRelInfo,
1498 TupleTableSlot *slot, EState *estate)
1500 Relation rel = resultRelInfo->ri_RelationDesc;
1501 int ncheck = rel->rd_att->constr->num_check;
1502 ConstrCheck *check = rel->rd_att->constr->check;
1503 ExprContext *econtext;
1504 MemoryContext oldContext;
1509 * If first time through for this result relation, build expression
1510 * nodetrees for rel's constraint expressions. Keep them in the
1511 * per-query memory context so they'll survive throughout the query.
1513 if (resultRelInfo->ri_ConstraintExprs == NULL)
1515 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1516 resultRelInfo->ri_ConstraintExprs =
1517 (List **) palloc(ncheck * sizeof(List *));
1518 for (i = 0; i < ncheck; i++)
1520 qual = (List *) stringToNode(check[i].ccbin);
1521 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1522 ExecPrepareExpr((Expr *) qual, estate);
1524 MemoryContextSwitchTo(oldContext);
1528 * We will use the EState's per-tuple context for evaluating
1529 * constraint expressions (creating it if it's not already there).
1531 econtext = GetPerTupleExprContext(estate);
1533 /* Arrange for econtext's scan tuple to be the tuple under test */
1534 econtext->ecxt_scantuple = slot;
1536 /* And evaluate the constraints */
1537 for (i = 0; i < ncheck; i++)
1539 qual = resultRelInfo->ri_ConstraintExprs[i];
1542 * NOTE: SQL92 specifies that a NULL result from a constraint
1543 * expression is not to be treated as a failure. Therefore, tell
1544 * ExecQual to return TRUE for NULL.
1546 if (!ExecQual(qual, econtext, true))
1547 return check[i].ccname;
1550 /* NULL result means no error */
1551 return (char *) NULL;
1555 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1556 TupleTableSlot *slot, EState *estate)
1558 Relation rel = resultRelInfo->ri_RelationDesc;
1559 HeapTuple tuple = slot->val;
1560 TupleConstr *constr = rel->rd_att->constr;
1564 if (constr->has_not_null)
1566 int natts = rel->rd_att->natts;
1569 for (attrChk = 1; attrChk <= natts; attrChk++)
1571 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1572 heap_attisnull(tuple, attrChk))
1573 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1574 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1578 if (constr->num_check > 0)
1582 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1583 elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1584 caller, failed, RelationGetRelationName(rel));
1589 * Check a modified tuple to see if we want to process its updated version
1590 * under READ COMMITTED rules.
1592 * See backend/executor/README for some info about how this works.
1595 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1600 HeapTupleData tuple;
1601 HeapTuple copyTuple = NULL;
1607 * find relation containing target tuple
1609 if (estate->es_result_relation_info != NULL &&
1610 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1611 relation = estate->es_result_relation_info->ri_RelationDesc;
1617 foreach(l, estate->es_rowMark)
1619 if (((execRowMark *) lfirst(l))->rti == rti)
1621 relation = ((execRowMark *) lfirst(l))->relation;
1625 if (relation == NULL)
1626 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1632 * Loop here to deal with updated or busy tuples
1634 tuple.t_self = *tid;
1639 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1641 TransactionId xwait = SnapshotDirty->xmax;
1643 if (TransactionIdIsValid(SnapshotDirty->xmin))
1644 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1647 * If tuple is being updated by other transaction then we have
1648 * to wait for its commit/abort.
1650 if (TransactionIdIsValid(xwait))
1652 ReleaseBuffer(buffer);
1653 XactLockTableWait(xwait);
1658 * We got tuple - now copy it for use by recheck query.
1660 copyTuple = heap_copytuple(&tuple);
1661 ReleaseBuffer(buffer);
1666 * Oops! Invalid tuple. Have to check is it updated or deleted.
1667 * Note that it's possible to get invalid SnapshotDirty->tid if
1668 * tuple updated by this transaction. Have we to check this ?
1670 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1671 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1673 /* updated, so look at the updated copy */
1674 tuple.t_self = SnapshotDirty->tid;
1679 * Deleted or updated by this transaction; forget it.
1685 * For UPDATE/DELETE we have to return tid of actual row we're
1688 *tid = tuple.t_self;
1691 * Need to run a recheck subquery. Find or create a PQ stack entry.
1693 epq = estate->es_evalPlanQual;
1696 if (epq != NULL && epq->rti == 0)
1698 /* Top PQ stack entry is idle, so re-use it */
1699 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
1705 * If this is request for another RTE - Ra, - then we have to check
1706 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1707 * updated again and we have to re-start old execution for Ra and
1708 * forget all what we done after Ra was suspended. Cool? -:))
1710 if (epq != NULL && epq->rti != rti &&
1711 epq->estate->es_evTuple[rti - 1] != NULL)
1715 evalPlanQual *oldepq;
1717 /* stop execution */
1718 EvalPlanQualStop(epq);
1719 /* pop previous PlanQual from the stack */
1721 Assert(oldepq && oldepq->rti != 0);
1722 /* push current PQ to freePQ stack */
1725 estate->es_evalPlanQual = epq;
1726 } while (epq->rti != rti);
1730 * If we are requested for another RTE then we have to suspend
1731 * execution of current PlanQual and start execution for new one.
1733 if (epq == NULL || epq->rti != rti)
1735 /* try to reuse plan used previously */
1736 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1738 if (newepq == NULL) /* first call or freePQ stack is empty */
1740 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
1741 newepq->free = NULL;
1742 newepq->estate = NULL;
1743 newepq->planstate = NULL;
1747 /* recycle previously used PlanQual */
1748 Assert(newepq->estate == NULL);
1751 /* push current PQ to the stack */
1754 estate->es_evalPlanQual = epq;
1759 Assert(epq->rti == rti);
1762 * Ok - we're requested for the same RTE. Unfortunately we still have
1763 * to end and restart execution of the plan, because ExecReScan
1764 * wouldn't ensure that upper plan nodes would reset themselves. We
1765 * could make that work if insertion of the target tuple were
1766 * integrated with the Param mechanism somehow, so that the upper plan
1767 * nodes know that their children's outputs have changed.
1769 * Note that the stack of free evalPlanQual nodes is quite useless at
1770 * the moment, since it only saves us from pallocing/releasing the
1771 * evalPlanQual nodes themselves. But it will be useful once we
1772 * implement ReScan instead of end/restart for re-using PlanQual nodes.
1776 /* stop execution */
1777 EvalPlanQualStop(epq);
1781 * Initialize new recheck query.
1783 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need
1784 * to instead copy down changeable state from the top plan (including
1785 * es_result_relation_info, es_junkFilter) and reset locally changeable
1786 * state in the epq (including es_param_exec_vals, es_evTupleNull).
1788 EvalPlanQualStart(epq, estate, epq->next);
1791 * free old RTE' tuple, if any, and store target tuple where
1792 * relation's scan node will see it
1794 epqstate = epq->estate;
1795 if (epqstate->es_evTuple[rti - 1] != NULL)
1796 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1797 epqstate->es_evTuple[rti - 1] = copyTuple;
1799 return EvalPlanQualNext(estate);
1802 static TupleTableSlot *
1803 EvalPlanQualNext(EState *estate)
1805 evalPlanQual *epq = estate->es_evalPlanQual;
1806 MemoryContext oldcontext;
1807 TupleTableSlot *slot;
1809 Assert(epq->rti != 0);
1812 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
1813 slot = ExecProcNode(epq->planstate);
1814 MemoryContextSwitchTo(oldcontext);
1817 * No more tuples for this PQ. Continue previous one.
1819 if (TupIsNull(slot))
1821 evalPlanQual *oldepq;
1823 /* stop execution */
1824 EvalPlanQualStop(epq);
1825 /* pop old PQ from the stack */
1829 /* this is the first (oldest) PQ - mark as free */
1831 estate->es_useEvalPlan = false;
1832 /* and continue Query execution */
1835 Assert(oldepq->rti != 0);
1836 /* push current PQ to freePQ stack */
1839 estate->es_evalPlanQual = epq;
1847 EndEvalPlanQual(EState *estate)
1849 evalPlanQual *epq = estate->es_evalPlanQual;
1851 if (epq->rti == 0) /* plans already shutdowned */
1853 Assert(epq->next == NULL);
1859 evalPlanQual *oldepq;
1861 /* stop execution */
1862 EvalPlanQualStop(epq);
1863 /* pop old PQ from the stack */
1867 /* this is the first (oldest) PQ - mark as free */
1869 estate->es_useEvalPlan = false;
1872 Assert(oldepq->rti != 0);
1873 /* push current PQ to freePQ stack */
1876 estate->es_evalPlanQual = epq;
1881 * Start execution of one level of PlanQual.
1883 * This is a cut-down version of ExecutorStart(): we copy some state from
1884 * the top-level estate rather than initializing it fresh.
1887 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
1891 MemoryContext oldcontext;
1893 rtsize = length(estate->es_range_table);
1895 epq->estate = epqstate = CreateExecutorState();
1897 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
1900 * The epqstates share the top query's copy of unchanging state such
1901 * as the snapshot, rangetable, result-rel info, and external Param info.
1902 * They need their own copies of local state, including a tuple table,
1903 * es_param_exec_vals, etc.
1905 epqstate->es_direction = ForwardScanDirection;
1906 epqstate->es_snapshot = estate->es_snapshot;
1907 epqstate->es_range_table = estate->es_range_table;
1908 epqstate->es_result_relations = estate->es_result_relations;
1909 epqstate->es_num_result_relations = estate->es_num_result_relations;
1910 epqstate->es_result_relation_info = estate->es_result_relation_info;
1911 epqstate->es_junkFilter = estate->es_junkFilter;
1912 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
1913 epqstate->es_param_list_info = estate->es_param_list_info;
1914 if (estate->es_topPlan->nParamExec > 0)
1915 epqstate->es_param_exec_vals = (ParamExecData *)
1916 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
1917 epqstate->es_rowMark = estate->es_rowMark;
1918 epqstate->es_instrument = estate->es_instrument;
1919 epqstate->es_topPlan = estate->es_topPlan;
1921 * Each epqstate must have its own es_evTupleNull state, but
1922 * all the stack entries share es_evTuple state. This allows
1923 * sub-rechecks to inherit the value being examined by an
1926 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
1927 if (priorepq == NULL)
1928 /* first PQ stack entry */
1929 epqstate->es_evTuple = (HeapTuple *)
1930 palloc0(rtsize * sizeof(HeapTuple));
1932 /* later stack entries share the same storage */
1933 epqstate->es_evTuple = priorepq->estate->es_evTuple;
1935 epqstate->es_tupleTable =
1936 ExecCreateTupleTable(estate->es_tupleTable->size);
1938 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
1940 MemoryContextSwitchTo(oldcontext);
1944 * End execution of one level of PlanQual.
1946 * This is a cut-down version of ExecutorEnd(); basically we want to do most
1947 * of the normal cleanup, but *not* close result relations (which we are
1948 * just sharing from the outer query).
1951 EvalPlanQualStop(evalPlanQual *epq)
1953 EState *epqstate = epq->estate;
1954 MemoryContext oldcontext;
1956 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
1958 ExecEndNode(epq->planstate);
1960 ExecDropTupleTable(epqstate->es_tupleTable, true);
1961 epqstate->es_tupleTable = NULL;
1963 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1965 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1966 epqstate->es_evTuple[epq->rti - 1] = NULL;
1969 MemoryContextSwitchTo(oldcontext);
1971 FreeExecutorState(epqstate);
1974 epq->planstate = NULL;