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.191 2002/12/12 15:49:24 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/planmain.h"
44 #include "optimizer/var.h"
45 #include "parser/parsetree.h"
46 #include "utils/acl.h"
47 #include "utils/lsyscache.h"
50 /* decls for local routines only used within this module */
51 static void InitPlan(QueryDesc *queryDesc);
52 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
53 Index resultRelationIndex,
56 static void EndPlan(PlanState *planstate, EState *estate);
57 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
60 ScanDirection direction,
61 DestReceiver *destfunc);
62 static void ExecSelect(TupleTableSlot *slot,
63 DestReceiver *destfunc,
65 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
67 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
69 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
71 static TupleTableSlot *EvalPlanQualNext(EState *estate);
72 static void EndEvalPlanQual(EState *estate);
73 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
75 /* end of local decls */
78 /* ----------------------------------------------------------------
81 * This routine must be called at the beginning of any execution of any
84 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
85 * clear why we bother to separate the two functions, but...). The tupDesc
86 * field of the QueryDesc is filled in to describe the tuples that will be
87 * returned, and the internal fields (estate and planstate) are set up.
89 * XXX this will change soon:
90 * NB: the CurrentMemoryContext when this is called must be the context
91 * to be used as the per-query context for the query plan. ExecutorRun()
92 * and ExecutorEnd() must be called in this same memory context.
93 * ----------------------------------------------------------------
96 ExecutorStart(QueryDesc *queryDesc)
100 /* sanity checks: queryDesc must not be started already */
101 Assert(queryDesc != NULL);
102 Assert(queryDesc->estate == NULL);
105 * Build EState, fill with parameters from queryDesc
107 estate = CreateExecutorState();
108 queryDesc->estate = estate;
110 estate->es_param_list_info = queryDesc->params;
112 if (queryDesc->plantree->nParamExec > 0)
113 estate->es_param_exec_vals = (ParamExecData *)
114 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
116 estate->es_instrument = queryDesc->doInstrument;
119 * Make our own private copy of the current query snapshot data.
121 * This "freezes" our idea of which tuples are good and which are not for
122 * the life of this query, even if it outlives the current command and
125 estate->es_snapshot = CopyQuerySnapshot();
128 * Initialize the plan state tree
133 /* ----------------------------------------------------------------
136 * This is the main routine of the executor module. It accepts
137 * the query descriptor from the traffic cop and executes the
140 * ExecutorStart must have been called already.
142 * If direction is NoMovementScanDirection then nothing is done
143 * except to start up/shut down the destination. Otherwise,
144 * we retrieve up to 'count' tuples in the specified direction.
146 * Note: count = 0 is interpreted as no portal limit, e.g. run to
149 * ----------------------------------------------------------------
152 ExecutorRun(QueryDesc *queryDesc,
153 ScanDirection direction, long count)
158 DestReceiver *destfunc;
159 TupleTableSlot *result;
164 Assert(queryDesc != NULL);
167 * extract information from the query descriptor and the query
170 operation = queryDesc->operation;
171 estate = queryDesc->estate;
172 dest = queryDesc->dest;
175 * startup tuple receiver
177 estate->es_processed = 0;
178 estate->es_lastoid = InvalidOid;
180 destfunc = DestToFunction(dest);
181 (*destfunc->setup) (destfunc, (int) operation,
182 queryDesc->portalName, queryDesc->tupDesc);
187 if (direction == NoMovementScanDirection)
190 result = ExecutePlan(estate,
191 queryDesc->planstate,
200 (*destfunc->cleanup) (destfunc);
205 /* ----------------------------------------------------------------
208 * This routine must be called at the end of execution of any
210 * ----------------------------------------------------------------
213 ExecutorEnd(QueryDesc *queryDesc)
218 Assert(queryDesc != NULL);
220 estate = queryDesc->estate;
222 EndPlan(queryDesc->planstate, estate);
224 if (estate->es_snapshot != NULL)
226 if (estate->es_snapshot->xcnt > 0)
227 pfree(estate->es_snapshot->xip);
228 pfree(estate->es_snapshot);
229 estate->es_snapshot = NULL;
232 if (estate->es_param_exec_vals != NULL)
234 pfree(estate->es_param_exec_vals);
235 estate->es_param_exec_vals = NULL;
241 * CreateExecutorState
244 CreateExecutorState(void)
249 * create a new executor state
251 state = makeNode(EState);
254 * initialize the Executor State structure
256 state->es_direction = ForwardScanDirection;
257 state->es_range_table = NIL;
259 state->es_result_relations = NULL;
260 state->es_num_result_relations = 0;
261 state->es_result_relation_info = NULL;
263 state->es_junkFilter = NULL;
265 state->es_into_relation_descriptor = NULL;
267 state->es_param_list_info = NULL;
268 state->es_param_exec_vals = NULL;
270 state->es_tupleTable = NULL;
272 state->es_query_cxt = CurrentMemoryContext;
274 state->es_instrument = false;
276 state->es_per_tuple_exprcontext = NULL;
279 * return the executor state structure
287 * Check access permissions for all relations listed in a range table.
290 ExecCheckRTPerms(List *rangeTable, CmdType operation)
294 foreach(lp, rangeTable)
296 RangeTblEntry *rte = lfirst(lp);
298 ExecCheckRTEPerms(rte, operation);
304 * Check access permissions for a single RTE.
307 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
311 AclResult aclcheck_result;
314 * If it's a subquery, recursively examine its rangetable.
316 if (rte->rtekind == RTE_SUBQUERY)
318 ExecCheckRTPerms(rte->subquery->rtable, operation);
323 * Otherwise, only plain-relation RTEs need to be checked here.
324 * Function RTEs are checked by init_fcache when the function is prepared
325 * for execution. Join and special RTEs need no checks.
327 if (rte->rtekind != RTE_RELATION)
333 * userid to check as: current user unless we have a setuid
336 * Note: GetUserId() is presently fast enough that there's no harm in
337 * calling it separately for each RTE. If that stops being true, we
338 * could call it once in ExecCheckRTPerms and pass the userid down
339 * from there. But for now, no need for the extra clutter.
341 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
343 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
345 if (rte->checkForRead)
347 aclcheck_result = CHECK(ACL_SELECT);
348 if (aclcheck_result != ACLCHECK_OK)
349 aclcheck_error(aclcheck_result, get_rel_name(relOid));
352 if (rte->checkForWrite)
355 * Note: write access in a SELECT context means SELECT FOR UPDATE.
356 * Right now we don't distinguish that from true update as far as
357 * permissions checks are concerned.
362 aclcheck_result = CHECK(ACL_INSERT);
366 aclcheck_result = CHECK(ACL_UPDATE);
369 aclcheck_result = CHECK(ACL_DELETE);
372 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
374 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
377 if (aclcheck_result != ACLCHECK_OK)
378 aclcheck_error(aclcheck_result, get_rel_name(relOid));
383 /* ===============================================================
384 * ===============================================================
385 static routines follow
386 * ===============================================================
387 * ===============================================================
390 typedef struct execRowMark
397 typedef struct evalPlanQual
399 Plan *plan; /* XXX temporary */
400 PlanState *planstate;
403 struct evalPlanQual *free;
406 /* ----------------------------------------------------------------
409 * Initializes the query plan: open files, allocate storage
410 * and start up the rule manager
411 * ----------------------------------------------------------------
414 InitPlan(QueryDesc *queryDesc)
416 CmdType operation = queryDesc->operation;
417 Query *parseTree = queryDesc->parsetree;
418 Plan *plan = queryDesc->plantree;
419 EState *estate = queryDesc->estate;
420 PlanState *planstate;
422 Relation intoRelationDesc;
426 * Do permissions checks. It's sufficient to examine the query's
427 * top rangetable here --- subplan RTEs will be checked during
430 ExecCheckRTPerms(parseTree->rtable, operation);
433 * get information from query descriptor
435 rangeTable = parseTree->rtable;
438 * initialize the node's execution state
440 estate->es_range_table = rangeTable;
443 * if there is a result relation, initialize result relation stuff
445 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
447 List *resultRelations = parseTree->resultRelations;
448 int numResultRelations;
449 ResultRelInfo *resultRelInfos;
451 if (resultRelations != NIL)
454 * Multiple result relations (due to inheritance)
455 * parseTree->resultRelations identifies them all
457 ResultRelInfo *resultRelInfo;
459 numResultRelations = length(resultRelations);
460 resultRelInfos = (ResultRelInfo *)
461 palloc(numResultRelations * sizeof(ResultRelInfo));
462 resultRelInfo = resultRelInfos;
463 while (resultRelations != NIL)
465 initResultRelInfo(resultRelInfo,
466 lfirsti(resultRelations),
470 resultRelations = lnext(resultRelations);
476 * Single result relation identified by
477 * parseTree->resultRelation
479 numResultRelations = 1;
480 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
481 initResultRelInfo(resultRelInfos,
482 parseTree->resultRelation,
487 estate->es_result_relations = resultRelInfos;
488 estate->es_num_result_relations = numResultRelations;
489 /* Initialize to first or only result rel */
490 estate->es_result_relation_info = resultRelInfos;
495 * if no result relation, then set state appropriately
497 estate->es_result_relations = NULL;
498 estate->es_num_result_relations = 0;
499 estate->es_result_relation_info = NULL;
503 * Have to lock relations selected for update
505 estate->es_rowMark = NIL;
506 if (parseTree->rowMarks != NIL)
510 foreach(l, parseTree->rowMarks)
512 Index rti = lfirsti(l);
513 Oid relid = getrelid(rti, rangeTable);
517 relation = heap_open(relid, RowShareLock);
518 erm = (execRowMark *) palloc(sizeof(execRowMark));
519 erm->relation = relation;
521 snprintf(erm->resname, 32, "ctid%u", rti);
522 estate->es_rowMark = lappend(estate->es_rowMark, erm);
527 * initialize the executor "tuple" table. We need slots for all the
528 * plan nodes, plus possibly output slots for the junkfilter(s). At
529 * this point we aren't sure if we need junkfilters, so just add slots
530 * for them unconditionally.
533 int nSlots = ExecCountSlotsNode(plan);
535 if (parseTree->resultRelations != NIL)
536 nSlots += length(parseTree->resultRelations);
539 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
542 /* mark EvalPlanQual not active */
543 estate->es_origPlan = plan;
544 estate->es_evalPlanQual = NULL;
545 estate->es_evTuple = NULL;
546 estate->es_evTupleNull = NULL;
547 estate->es_useEvalPlan = false;
550 * initialize the private state information for all the nodes in the
551 * query tree. This opens files, allocates storage and leaves us
552 * ready to start processing tuples.
554 planstate = ExecInitNode(plan, estate);
557 * Get the tuple descriptor describing the type of tuples to return.
558 * (this is especially important if we are creating a relation with
561 tupType = ExecGetTupType(planstate);
564 * Initialize the junk filter if needed. SELECT and INSERT queries
565 * need a filter if there are any junk attrs in the tlist. UPDATE and
566 * DELETE always need one, since there's always a junk 'ctid'
567 * attribute present --- no need to look first.
570 bool junk_filter_needed = false;
577 foreach(tlist, plan->targetlist)
579 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
581 if (tle->resdom->resjunk)
583 junk_filter_needed = true;
590 junk_filter_needed = true;
596 if (junk_filter_needed)
599 * If there are multiple result relations, each one needs its
600 * own junk filter. Note this is only possible for
601 * UPDATE/DELETE, so we can't be fooled by some needing a
602 * filter and some not.
604 if (parseTree->resultRelations != NIL)
606 PlanState **appendplans;
608 ResultRelInfo *resultRelInfo;
611 /* Top plan had better be an Append here. */
612 Assert(IsA(plan, Append));
613 Assert(((Append *) plan)->isTarget);
614 Assert(IsA(planstate, AppendState));
615 appendplans = ((AppendState *) planstate)->appendplans;
616 as_nplans = ((AppendState *) planstate)->as_nplans;
617 Assert(as_nplans == estate->es_num_result_relations);
618 resultRelInfo = estate->es_result_relations;
619 for (i = 0; i < as_nplans; i++)
621 PlanState *subplan = appendplans[i];
624 j = ExecInitJunkFilter(subplan->plan->targetlist,
625 ExecGetTupType(subplan),
626 ExecAllocTableSlot(estate->es_tupleTable));
627 resultRelInfo->ri_junkFilter = j;
632 * Set active junkfilter too; at this point ExecInitAppend
633 * has already selected an active result relation...
635 estate->es_junkFilter =
636 estate->es_result_relation_info->ri_junkFilter;
640 /* Normal case with just one JunkFilter */
643 j = ExecInitJunkFilter(planstate->plan->targetlist,
645 ExecAllocTableSlot(estate->es_tupleTable));
646 estate->es_junkFilter = j;
647 if (estate->es_result_relation_info)
648 estate->es_result_relation_info->ri_junkFilter = j;
650 /* For SELECT, want to return the cleaned tuple type */
651 if (operation == CMD_SELECT)
652 tupType = j->jf_cleanTupType;
656 estate->es_junkFilter = NULL;
660 * initialize the "into" relation
662 intoRelationDesc = (Relation) NULL;
664 if (operation == CMD_SELECT)
666 if (!parseTree->isPortal)
669 * a select into table --- need to create the "into" table
671 if (parseTree->into != NULL)
680 * find namespace to create in, check permissions
682 intoName = parseTree->into->relname;
683 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
685 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
687 if (aclresult != ACLCHECK_OK)
688 aclcheck_error(aclresult,
689 get_namespace_name(namespaceId));
692 * have to copy tupType to get rid of constraints
694 tupdesc = CreateTupleDescCopy(tupType);
697 * Formerly we forced the output table to have OIDs, but
698 * as of 7.3 it will not have OIDs, because it's too late
699 * here to change the tupdescs of the already-initialized
700 * plan tree. (Perhaps we could recurse and change them
701 * all, but it's not really worth the trouble IMHO...)
705 heap_create_with_catalog(intoName,
711 allowSystemTableMods);
713 FreeTupleDesc(tupdesc);
716 * Advance command counter so that the newly-created
717 * relation's catalog tuples will be visible to heap_open.
719 CommandCounterIncrement();
722 * If necessary, create a TOAST table for the into
723 * relation. Note that AlterTableCreateToastTable ends
724 * with CommandCounterIncrement(), so that the TOAST table
725 * will be visible for insertion.
727 AlterTableCreateToastTable(intoRelationId, true);
729 intoRelationDesc = heap_open(intoRelationId,
730 AccessExclusiveLock);
735 estate->es_into_relation_descriptor = intoRelationDesc;
737 queryDesc->tupDesc = tupType;
738 queryDesc->planstate = planstate;
742 * Initialize ResultRelInfo data for one result relation
745 initResultRelInfo(ResultRelInfo *resultRelInfo,
746 Index resultRelationIndex,
750 Oid resultRelationOid;
751 Relation resultRelationDesc;
753 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
754 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
756 switch (resultRelationDesc->rd_rel->relkind)
758 case RELKIND_SEQUENCE:
759 elog(ERROR, "You can't change sequence relation %s",
760 RelationGetRelationName(resultRelationDesc));
762 case RELKIND_TOASTVALUE:
763 elog(ERROR, "You can't change toast relation %s",
764 RelationGetRelationName(resultRelationDesc));
767 elog(ERROR, "You can't change view relation %s",
768 RelationGetRelationName(resultRelationDesc));
772 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
773 resultRelInfo->type = T_ResultRelInfo;
774 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
775 resultRelInfo->ri_RelationDesc = resultRelationDesc;
776 resultRelInfo->ri_NumIndices = 0;
777 resultRelInfo->ri_IndexRelationDescs = NULL;
778 resultRelInfo->ri_IndexRelationInfo = NULL;
779 /* make a copy so as not to depend on relcache info not changing... */
780 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
781 resultRelInfo->ri_TrigFunctions = NULL;
782 resultRelInfo->ri_ConstraintExprs = NULL;
783 resultRelInfo->ri_junkFilter = NULL;
786 * If there are indices on the result relation, open them and save
787 * descriptors in the result relation info, so that we can add new
788 * index entries for the tuples we add/update. We need not do this
789 * for a DELETE, however, since deletion doesn't affect indexes.
791 if (resultRelationDesc->rd_rel->relhasindex &&
792 operation != CMD_DELETE)
793 ExecOpenIndices(resultRelInfo);
796 /* ----------------------------------------------------------------
799 * Cleans up the query plan -- closes files and frees up storage
800 * ----------------------------------------------------------------
803 EndPlan(PlanState *planstate, EState *estate)
805 ResultRelInfo *resultRelInfo;
810 * shut down any PlanQual processing we were doing
812 if (estate->es_evalPlanQual != NULL)
813 EndEvalPlanQual(estate);
816 * shut down the node-type-specific query processing
818 ExecEndNode(planstate);
821 * destroy the executor "tuple" table.
823 ExecDropTupleTable(estate->es_tupleTable, true);
824 estate->es_tupleTable = NULL;
827 * close the result relation(s) if any, but hold locks until xact
828 * commit. Also clean up junkfilters if present.
830 resultRelInfo = estate->es_result_relations;
831 for (i = estate->es_num_result_relations; i > 0; i--)
833 /* Close indices and then the relation itself */
834 ExecCloseIndices(resultRelInfo);
835 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
836 /* Delete the junkfilter if any */
837 if (resultRelInfo->ri_junkFilter != NULL)
838 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
843 * close the "into" relation if necessary, again keeping lock
845 if (estate->es_into_relation_descriptor != NULL)
846 heap_close(estate->es_into_relation_descriptor, NoLock);
849 * There might be a junkfilter without a result relation.
851 if (estate->es_num_result_relations == 0 &&
852 estate->es_junkFilter != NULL)
854 ExecFreeJunkFilter(estate->es_junkFilter);
855 estate->es_junkFilter = NULL;
859 * close any relations selected FOR UPDATE, again keeping locks
861 foreach(l, estate->es_rowMark)
863 execRowMark *erm = lfirst(l);
865 heap_close(erm->relation, NoLock);
869 /* ----------------------------------------------------------------
872 * processes the query plan to retrieve 'numberTuples' tuples in the
873 * direction specified.
874 * Retrieves all tuples if numberTuples is 0
876 * result is either a slot containing the last tuple in the case
877 * of a SELECT or NULL otherwise.
879 * Note: the ctid attribute is a 'junk' attribute that is removed before the
881 * ----------------------------------------------------------------
883 static TupleTableSlot *
884 ExecutePlan(EState *estate,
885 PlanState *planstate,
888 ScanDirection direction,
889 DestReceiver *destfunc)
891 JunkFilter *junkfilter;
892 TupleTableSlot *slot;
893 ItemPointer tupleid = NULL;
894 ItemPointerData tuple_ctid;
895 long current_tuple_count;
896 TupleTableSlot *result;
899 * initialize local variables
902 current_tuple_count = 0;
908 estate->es_direction = direction;
911 * Process BEFORE EACH STATEMENT triggers
916 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
919 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
922 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
930 * Loop until we've processed the proper number of tuples from the
936 /* Reset the per-output-tuple exprcontext */
937 ResetPerTupleExprContext(estate);
940 * Execute the plan and obtain a tuple
943 if (estate->es_useEvalPlan)
945 slot = EvalPlanQualNext(estate);
947 slot = ExecProcNode(planstate);
950 slot = ExecProcNode(planstate);
953 * if the tuple is null, then we assume there is nothing more to
954 * process so we just return null...
963 * if we have a junk filter, then project a new tuple with the
966 * Store this new "clean" tuple in the junkfilter's resultSlot.
967 * (Formerly, we stored it back over the "dirty" tuple, which is
968 * WRONG because that tuple slot has the wrong descriptor.)
970 * Also, extract all the junk information we need.
972 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
979 * extract the 'ctid' junk attribute.
981 if (operation == CMD_UPDATE || operation == CMD_DELETE)
983 if (!ExecGetJunkAttribute(junkfilter,
988 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
990 /* shouldn't ever get a null result... */
992 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
994 tupleid = (ItemPointer) DatumGetPointer(datum);
995 tuple_ctid = *tupleid; /* make sure we don't free the
997 tupleid = &tuple_ctid;
999 else if (estate->es_rowMark != NIL)
1004 foreach(l, estate->es_rowMark)
1006 execRowMark *erm = lfirst(l);
1008 HeapTupleData tuple;
1009 TupleTableSlot *newSlot;
1012 if (!ExecGetJunkAttribute(junkfilter,
1017 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1020 /* shouldn't ever get a null result... */
1022 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1025 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1026 test = heap_mark4update(erm->relation, &tuple, &buffer,
1027 estate->es_snapshot->curcid);
1028 ReleaseBuffer(buffer);
1031 case HeapTupleSelfUpdated:
1032 /* treat it as deleted; do not process */
1035 case HeapTupleMayBeUpdated:
1038 case HeapTupleUpdated:
1039 if (XactIsoLevel == XACT_SERIALIZABLE)
1040 elog(ERROR, "Can't serialize access due to concurrent update");
1041 if (!(ItemPointerEquals(&(tuple.t_self),
1042 (ItemPointer) DatumGetPointer(datum))))
1044 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1045 if (!(TupIsNull(newSlot)))
1048 estate->es_useEvalPlan = true;
1054 * if tuple was deleted or PlanQual failed for
1055 * updated tuple - we must not return this
1061 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1068 * Finally create a new "clean" tuple with all junk attributes
1071 newTuple = ExecRemoveJunk(junkfilter, slot);
1073 slot = ExecStoreTuple(newTuple, /* tuple to store */
1074 junkfilter->jf_resultSlot, /* dest slot */
1075 InvalidBuffer, /* this tuple has no
1077 true); /* tuple should be pfreed */
1081 * now that we have a tuple, do the appropriate thing with it..
1082 * either return it to the user, add it to a relation someplace,
1083 * delete it from a relation, or modify some of its attributes.
1088 ExecSelect(slot, /* slot containing tuple */
1089 destfunc, /* destination's tuple-receiver
1096 ExecInsert(slot, tupleid, estate);
1101 ExecDelete(slot, tupleid, estate);
1106 ExecUpdate(slot, tupleid, estate);
1111 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1117 * check our tuple count.. if we've processed the proper number
1118 * then quit, else loop again and process more tuples. Zero
1119 * number_tuples means no limit.
1121 current_tuple_count++;
1122 if (numberTuples == current_tuple_count)
1127 * Process AFTER EACH STATEMENT triggers
1132 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1135 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1138 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1146 * here, result is either a slot containing a tuple in the case of a
1147 * SELECT or NULL otherwise.
1152 /* ----------------------------------------------------------------
1155 * SELECTs are easy.. we just pass the tuple to the appropriate
1156 * print function. The only complexity is when we do a
1157 * "SELECT INTO", in which case we insert the tuple into
1158 * the appropriate relation (note: this is a newly created relation
1159 * so we don't need to worry about indices or locks.)
1160 * ----------------------------------------------------------------
1163 ExecSelect(TupleTableSlot *slot,
1164 DestReceiver *destfunc,
1171 * get the heap tuple out of the tuple table slot
1174 attrtype = slot->ttc_tupleDescriptor;
1177 * insert the tuple into the "into relation"
1179 if (estate->es_into_relation_descriptor != NULL)
1181 heap_insert(estate->es_into_relation_descriptor, tuple,
1182 estate->es_snapshot->curcid);
1187 * send the tuple to the front end (or the screen)
1189 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1191 (estate->es_processed)++;
1194 /* ----------------------------------------------------------------
1197 * INSERTs are trickier.. we have to insert the tuple into
1198 * the base relation and insert appropriate tuples into the
1200 * ----------------------------------------------------------------
1203 ExecInsert(TupleTableSlot *slot,
1204 ItemPointer tupleid,
1208 ResultRelInfo *resultRelInfo;
1209 Relation resultRelationDesc;
1214 * get the heap tuple out of the tuple table slot
1219 * get information on the (current) result relation
1221 resultRelInfo = estate->es_result_relation_info;
1222 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1224 /* BEFORE ROW INSERT Triggers */
1225 if (resultRelInfo->ri_TrigDesc &&
1226 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1230 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1232 if (newtuple == NULL) /* "do nothing" */
1235 if (newtuple != tuple) /* modified by Trigger(s) */
1238 * Insert modified tuple into tuple table slot, replacing the
1239 * original. We assume that it was allocated in per-tuple
1240 * memory context, and therefore will go away by itself. The
1241 * tuple table slot should not try to clear it.
1243 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1249 * Check the constraints of the tuple
1251 if (resultRelationDesc->rd_att->constr)
1252 ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1257 newId = heap_insert(resultRelationDesc, tuple,
1258 estate->es_snapshot->curcid);
1261 (estate->es_processed)++;
1262 estate->es_lastoid = newId;
1263 setLastTid(&(tuple->t_self));
1268 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1269 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1272 numIndices = resultRelInfo->ri_NumIndices;
1274 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1276 /* AFTER ROW INSERT Triggers */
1277 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1280 /* ----------------------------------------------------------------
1283 * DELETE is like UPDATE, we delete the tuple and its
1285 * ----------------------------------------------------------------
1288 ExecDelete(TupleTableSlot *slot,
1289 ItemPointer tupleid,
1292 ResultRelInfo *resultRelInfo;
1293 Relation resultRelationDesc;
1294 ItemPointerData ctid;
1298 * get information on the (current) result relation
1300 resultRelInfo = estate->es_result_relation_info;
1301 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1303 /* BEFORE ROW DELETE Triggers */
1304 if (resultRelInfo->ri_TrigDesc &&
1305 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1309 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1311 if (!dodelete) /* "do nothing" */
1319 result = heap_delete(resultRelationDesc, tupleid,
1321 estate->es_snapshot->curcid);
1324 case HeapTupleSelfUpdated:
1325 /* already deleted by self; nothing to do */
1328 case HeapTupleMayBeUpdated:
1331 case HeapTupleUpdated:
1332 if (XactIsoLevel == XACT_SERIALIZABLE)
1333 elog(ERROR, "Can't serialize access due to concurrent update");
1334 else if (!(ItemPointerEquals(tupleid, &ctid)))
1336 TupleTableSlot *epqslot = EvalPlanQual(estate,
1337 resultRelInfo->ri_RangeTableIndex, &ctid);
1339 if (!TupIsNull(epqslot))
1345 /* tuple already deleted; nothing to do */
1349 elog(ERROR, "Unknown status %u from heap_delete", result);
1354 (estate->es_processed)++;
1357 * Note: Normally one would think that we have to delete index tuples
1358 * associated with the heap tuple now..
1360 * ... but in POSTGRES, we have no need to do this because the vacuum
1361 * daemon automatically opens an index scan and deletes index tuples
1362 * when it finds deleted heap tuples. -cim 9/27/89
1365 /* AFTER ROW DELETE Triggers */
1366 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1369 /* ----------------------------------------------------------------
1372 * note: we can't run UPDATE queries with transactions
1373 * off because UPDATEs are actually INSERTs and our
1374 * scan will mistakenly loop forever, updating the tuple
1375 * it just inserted.. This should be fixed but until it
1376 * is, we don't want to get stuck in an infinite loop
1377 * which corrupts your database..
1378 * ----------------------------------------------------------------
1381 ExecUpdate(TupleTableSlot *slot,
1382 ItemPointer tupleid,
1386 ResultRelInfo *resultRelInfo;
1387 Relation resultRelationDesc;
1388 ItemPointerData ctid;
1393 * abort the operation if not running transactions
1395 if (IsBootstrapProcessingMode())
1397 elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1402 * get the heap tuple out of the tuple table slot
1407 * get information on the (current) result relation
1409 resultRelInfo = estate->es_result_relation_info;
1410 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1412 /* BEFORE ROW UPDATE Triggers */
1413 if (resultRelInfo->ri_TrigDesc &&
1414 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1418 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1421 if (newtuple == NULL) /* "do nothing" */
1424 if (newtuple != tuple) /* modified by Trigger(s) */
1427 * Insert modified tuple into tuple table slot, replacing the
1428 * original. We assume that it was allocated in per-tuple
1429 * memory context, and therefore will go away by itself. The
1430 * tuple table slot should not try to clear it.
1432 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1438 * Check the constraints of the tuple
1440 * If we generate a new candidate tuple after EvalPlanQual testing, we
1441 * must loop back here and recheck constraints. (We don't need to
1442 * redo triggers, however. If there are any BEFORE triggers then
1443 * trigger.c will have done mark4update to lock the correct tuple, so
1444 * there's no need to do them again.)
1447 if (resultRelationDesc->rd_att->constr)
1448 ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1451 * replace the heap tuple
1453 result = heap_update(resultRelationDesc, tupleid, tuple,
1455 estate->es_snapshot->curcid);
1458 case HeapTupleSelfUpdated:
1459 /* already deleted by self; nothing to do */
1462 case HeapTupleMayBeUpdated:
1465 case HeapTupleUpdated:
1466 if (XactIsoLevel == XACT_SERIALIZABLE)
1467 elog(ERROR, "Can't serialize access due to concurrent update");
1468 else if (!(ItemPointerEquals(tupleid, &ctid)))
1470 TupleTableSlot *epqslot = EvalPlanQual(estate,
1471 resultRelInfo->ri_RangeTableIndex, &ctid);
1473 if (!TupIsNull(epqslot))
1476 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1477 slot = ExecStoreTuple(tuple,
1478 estate->es_junkFilter->jf_resultSlot,
1479 InvalidBuffer, true);
1483 /* tuple already deleted; nothing to do */
1487 elog(ERROR, "Unknown status %u from heap_update", result);
1492 (estate->es_processed)++;
1495 * Note: instead of having to update the old index tuples associated
1496 * with the heap tuple, all we do is form and insert new index tuples.
1497 * This is because UPDATEs are actually DELETEs and INSERTs and index
1498 * tuple deletion is done automagically by the vacuum daemon. All we
1499 * do is insert new index tuples. -cim 9/27/89
1505 * heap_update updates a tuple in the base relation by invalidating it
1506 * and then inserting a new tuple to the relation. As a side effect,
1507 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1508 * field. So we now insert index tuples using the new tupleid stored
1512 numIndices = resultRelInfo->ri_NumIndices;
1514 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1516 /* AFTER ROW UPDATE Triggers */
1517 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1521 ExecRelCheck(ResultRelInfo *resultRelInfo,
1522 TupleTableSlot *slot, EState *estate)
1524 Relation rel = resultRelInfo->ri_RelationDesc;
1525 int ncheck = rel->rd_att->constr->num_check;
1526 ConstrCheck *check = rel->rd_att->constr->check;
1527 ExprContext *econtext;
1528 MemoryContext oldContext;
1533 * If first time through for this result relation, build expression
1534 * nodetrees for rel's constraint expressions. Keep them in the
1535 * per-query memory context so they'll survive throughout the query.
1537 if (resultRelInfo->ri_ConstraintExprs == NULL)
1539 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1540 resultRelInfo->ri_ConstraintExprs =
1541 (List **) palloc(ncheck * sizeof(List *));
1542 for (i = 0; i < ncheck; i++)
1544 qual = (List *) stringToNode(check[i].ccbin);
1545 fix_opfuncids((Node *) qual);
1546 resultRelInfo->ri_ConstraintExprs[i] = qual;
1548 MemoryContextSwitchTo(oldContext);
1552 * We will use the EState's per-tuple context for evaluating
1553 * constraint expressions (creating it if it's not already there).
1555 econtext = GetPerTupleExprContext(estate);
1557 /* Arrange for econtext's scan tuple to be the tuple under test */
1558 econtext->ecxt_scantuple = slot;
1560 /* And evaluate the constraints */
1561 for (i = 0; i < ncheck; i++)
1563 qual = resultRelInfo->ri_ConstraintExprs[i];
1566 * NOTE: SQL92 specifies that a NULL result from a constraint
1567 * expression is not to be treated as a failure. Therefore, tell
1568 * ExecQual to return TRUE for NULL.
1570 if (!ExecQual(qual, econtext, true))
1571 return check[i].ccname;
1574 /* NULL result means no error */
1575 return (char *) NULL;
1579 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1580 TupleTableSlot *slot, EState *estate)
1582 Relation rel = resultRelInfo->ri_RelationDesc;
1583 HeapTuple tuple = slot->val;
1584 TupleConstr *constr = rel->rd_att->constr;
1588 if (constr->has_not_null)
1590 int natts = rel->rd_att->natts;
1593 for (attrChk = 1; attrChk <= natts; attrChk++)
1595 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1596 heap_attisnull(tuple, attrChk))
1597 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1598 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1602 if (constr->num_check > 0)
1606 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1607 elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1608 caller, failed, RelationGetRelationName(rel));
1613 * Check a modified tuple to see if we want to process its updated version
1614 * under READ COMMITTED rules.
1616 * See backend/executor/README for some info about how this works.
1619 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1624 HeapTupleData tuple;
1625 HeapTuple copyTuple = NULL;
1632 * find relation containing target tuple
1634 if (estate->es_result_relation_info != NULL &&
1635 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1636 relation = estate->es_result_relation_info->ri_RelationDesc;
1642 foreach(l, estate->es_rowMark)
1644 if (((execRowMark *) lfirst(l))->rti == rti)
1646 relation = ((execRowMark *) lfirst(l))->relation;
1650 if (relation == NULL)
1651 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1657 * Loop here to deal with updated or busy tuples
1659 tuple.t_self = *tid;
1664 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1666 TransactionId xwait = SnapshotDirty->xmax;
1668 if (TransactionIdIsValid(SnapshotDirty->xmin))
1669 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1672 * If tuple is being updated by other transaction then we have
1673 * to wait for its commit/abort.
1675 if (TransactionIdIsValid(xwait))
1677 ReleaseBuffer(buffer);
1678 XactLockTableWait(xwait);
1683 * We got tuple - now copy it for use by recheck query.
1685 copyTuple = heap_copytuple(&tuple);
1686 ReleaseBuffer(buffer);
1691 * Oops! Invalid tuple. Have to check is it updated or deleted.
1692 * Note that it's possible to get invalid SnapshotDirty->tid if
1693 * tuple updated by this transaction. Have we to check this ?
1695 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1696 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1698 /* updated, so look at the updated copy */
1699 tuple.t_self = SnapshotDirty->tid;
1704 * Deleted or updated by this transaction; forget it.
1710 * For UPDATE/DELETE we have to return tid of actual row we're
1713 *tid = tuple.t_self;
1716 * Need to run a recheck subquery. Find or create a PQ stack entry.
1718 epq = (evalPlanQual *) estate->es_evalPlanQual;
1719 rtsize = length(estate->es_range_table);
1722 if (epq != NULL && epq->rti == 0)
1724 /* Top PQ stack entry is idle, so re-use it */
1725 Assert(!(estate->es_useEvalPlan) &&
1726 epq->estate.es_evalPlanQual == NULL);
1732 * If this is request for another RTE - Ra, - then we have to check
1733 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1734 * updated again and we have to re-start old execution for Ra and
1735 * forget all what we done after Ra was suspended. Cool? -:))
1737 if (epq != NULL && epq->rti != rti &&
1738 epq->estate.es_evTuple[rti - 1] != NULL)
1742 evalPlanQual *oldepq;
1744 /* pop previous PlanQual from the stack */
1745 epqstate = &(epq->estate);
1746 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1747 Assert(oldepq->rti != 0);
1748 /* stop execution */
1749 ExecEndNode(epq->planstate);
1750 ExecDropTupleTable(epqstate->es_tupleTable, true);
1751 epqstate->es_tupleTable = NULL;
1752 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1753 epqstate->es_evTuple[epq->rti - 1] = NULL;
1754 /* push current PQ to freePQ stack */
1757 estate->es_evalPlanQual = (Pointer) epq;
1758 } while (epq->rti != rti);
1762 * If we are requested for another RTE then we have to suspend
1763 * execution of current PlanQual and start execution for new one.
1765 if (epq == NULL || epq->rti != rti)
1767 /* try to reuse plan used previously */
1768 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1770 if (newepq == NULL) /* first call or freePQ stack is empty */
1772 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1773 newepq->free = NULL;
1776 * Each stack level has its own copy of the plan tree. This
1777 * is wasteful, but necessary until plan trees are fully
1780 newepq->plan = copyObject(estate->es_origPlan);
1783 * Init stack level's EState. We share top level's copy of
1784 * es_result_relations array and other non-changing status. We
1785 * need our own tupletable, es_param_exec_vals, and other
1788 epqstate = &(newepq->estate);
1789 memcpy(epqstate, estate, sizeof(EState));
1790 epqstate->es_direction = ForwardScanDirection;
1791 if (estate->es_origPlan->nParamExec > 0)
1792 epqstate->es_param_exec_vals = (ParamExecData *)
1793 palloc(estate->es_origPlan->nParamExec *
1794 sizeof(ParamExecData));
1795 epqstate->es_tupleTable = NULL;
1796 epqstate->es_per_tuple_exprcontext = NULL;
1799 * Each epqstate must have its own es_evTupleNull state, but
1800 * all the stack entries share es_evTuple state. This allows
1801 * sub-rechecks to inherit the value being examined by an
1804 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1806 /* first PQ stack entry */
1807 epqstate->es_evTuple = (HeapTuple *)
1808 palloc0(rtsize * sizeof(HeapTuple));
1810 /* later stack entries share the same storage */
1811 epqstate->es_evTuple = epq->estate.es_evTuple;
1815 /* recycle previously used EState */
1816 epqstate = &(newepq->estate);
1818 /* push current PQ to the stack */
1819 epqstate->es_evalPlanQual = (Pointer) epq;
1821 estate->es_evalPlanQual = (Pointer) epq;
1826 Assert(epq->rti == rti);
1827 epqstate = &(epq->estate);
1830 * Ok - we're requested for the same RTE. Unfortunately we still have
1831 * to end and restart execution of the plan, because ExecReScan
1832 * wouldn't ensure that upper plan nodes would reset themselves. We
1833 * could make that work if insertion of the target tuple were
1834 * integrated with the Param mechanism somehow, so that the upper plan
1835 * nodes know that their children's outputs have changed.
1839 /* stop execution */
1840 ExecEndNode(epq->planstate);
1841 ExecDropTupleTable(epqstate->es_tupleTable, true);
1842 epqstate->es_tupleTable = NULL;
1846 * free old RTE' tuple, if any, and store target tuple where
1847 * relation's scan node will see it
1849 if (epqstate->es_evTuple[rti - 1] != NULL)
1850 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1851 epqstate->es_evTuple[rti - 1] = copyTuple;
1854 * Initialize for new recheck query; be careful to copy down state
1855 * that might have changed in top EState.
1857 epqstate->es_result_relation_info = estate->es_result_relation_info;
1858 epqstate->es_junkFilter = estate->es_junkFilter;
1859 if (estate->es_origPlan->nParamExec > 0)
1860 memset(epqstate->es_param_exec_vals, 0,
1861 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1862 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1863 epqstate->es_useEvalPlan = false;
1864 Assert(epqstate->es_tupleTable == NULL);
1865 epqstate->es_tupleTable =
1866 ExecCreateTupleTable(estate->es_tupleTable->size);
1868 epq->planstate = ExecInitNode(epq->plan, epqstate);
1870 return EvalPlanQualNext(estate);
1873 static TupleTableSlot *
1874 EvalPlanQualNext(EState *estate)
1876 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1877 EState *epqstate = &(epq->estate);
1878 evalPlanQual *oldepq;
1879 TupleTableSlot *slot;
1881 Assert(epq->rti != 0);
1884 slot = ExecProcNode(epq->planstate);
1887 * No more tuples for this PQ. Continue previous one.
1889 if (TupIsNull(slot))
1891 /* stop execution */
1892 ExecEndNode(epq->planstate);
1893 ExecDropTupleTable(epqstate->es_tupleTable, true);
1894 epqstate->es_tupleTable = NULL;
1895 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1896 epqstate->es_evTuple[epq->rti - 1] = NULL;
1897 /* pop old PQ from the stack */
1898 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1899 if (oldepq == (evalPlanQual *) NULL)
1901 epq->rti = 0; /* this is the first (oldest) */
1902 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1903 return (NULL); /* continue Query execution */
1905 Assert(oldepq->rti != 0);
1906 /* push current PQ to freePQ stack */
1909 epqstate = &(epq->estate);
1910 estate->es_evalPlanQual = (Pointer) epq;
1918 EndEvalPlanQual(EState *estate)
1920 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1921 EState *epqstate = &(epq->estate);
1922 evalPlanQual *oldepq;
1924 if (epq->rti == 0) /* plans already shutdowned */
1926 Assert(epq->estate.es_evalPlanQual == NULL);
1932 /* stop execution */
1933 ExecEndNode(epq->planstate);
1934 ExecDropTupleTable(epqstate->es_tupleTable, true);
1935 epqstate->es_tupleTable = NULL;
1936 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1938 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1939 epqstate->es_evTuple[epq->rti - 1] = NULL;
1941 /* pop old PQ from the stack */
1942 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1943 if (oldepq == (evalPlanQual *) NULL)
1945 epq->rti = 0; /* this is the first (oldest) */
1946 estate->es_useEvalPlan = false; /* PQ - mark as free */
1949 Assert(oldepq->rti != 0);
1950 /* push current PQ to freePQ stack */
1953 epqstate = &(epq->estate);
1954 estate->es_evalPlanQual = (Pointer) epq;