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.192 2002/12/13 19:45:52 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] = (List *)
1547 ExecInitExpr((Expr *) qual, NULL);
1549 MemoryContextSwitchTo(oldContext);
1553 * We will use the EState's per-tuple context for evaluating
1554 * constraint expressions (creating it if it's not already there).
1556 econtext = GetPerTupleExprContext(estate);
1558 /* Arrange for econtext's scan tuple to be the tuple under test */
1559 econtext->ecxt_scantuple = slot;
1561 /* And evaluate the constraints */
1562 for (i = 0; i < ncheck; i++)
1564 qual = resultRelInfo->ri_ConstraintExprs[i];
1567 * NOTE: SQL92 specifies that a NULL result from a constraint
1568 * expression is not to be treated as a failure. Therefore, tell
1569 * ExecQual to return TRUE for NULL.
1571 if (!ExecQual(qual, econtext, true))
1572 return check[i].ccname;
1575 /* NULL result means no error */
1576 return (char *) NULL;
1580 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1581 TupleTableSlot *slot, EState *estate)
1583 Relation rel = resultRelInfo->ri_RelationDesc;
1584 HeapTuple tuple = slot->val;
1585 TupleConstr *constr = rel->rd_att->constr;
1589 if (constr->has_not_null)
1591 int natts = rel->rd_att->natts;
1594 for (attrChk = 1; attrChk <= natts; attrChk++)
1596 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1597 heap_attisnull(tuple, attrChk))
1598 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1599 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1603 if (constr->num_check > 0)
1607 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1608 elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1609 caller, failed, RelationGetRelationName(rel));
1614 * Check a modified tuple to see if we want to process its updated version
1615 * under READ COMMITTED rules.
1617 * See backend/executor/README for some info about how this works.
1620 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1625 HeapTupleData tuple;
1626 HeapTuple copyTuple = NULL;
1633 * find relation containing target tuple
1635 if (estate->es_result_relation_info != NULL &&
1636 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1637 relation = estate->es_result_relation_info->ri_RelationDesc;
1643 foreach(l, estate->es_rowMark)
1645 if (((execRowMark *) lfirst(l))->rti == rti)
1647 relation = ((execRowMark *) lfirst(l))->relation;
1651 if (relation == NULL)
1652 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1658 * Loop here to deal with updated or busy tuples
1660 tuple.t_self = *tid;
1665 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1667 TransactionId xwait = SnapshotDirty->xmax;
1669 if (TransactionIdIsValid(SnapshotDirty->xmin))
1670 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1673 * If tuple is being updated by other transaction then we have
1674 * to wait for its commit/abort.
1676 if (TransactionIdIsValid(xwait))
1678 ReleaseBuffer(buffer);
1679 XactLockTableWait(xwait);
1684 * We got tuple - now copy it for use by recheck query.
1686 copyTuple = heap_copytuple(&tuple);
1687 ReleaseBuffer(buffer);
1692 * Oops! Invalid tuple. Have to check is it updated or deleted.
1693 * Note that it's possible to get invalid SnapshotDirty->tid if
1694 * tuple updated by this transaction. Have we to check this ?
1696 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1697 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1699 /* updated, so look at the updated copy */
1700 tuple.t_self = SnapshotDirty->tid;
1705 * Deleted or updated by this transaction; forget it.
1711 * For UPDATE/DELETE we have to return tid of actual row we're
1714 *tid = tuple.t_self;
1717 * Need to run a recheck subquery. Find or create a PQ stack entry.
1719 epq = (evalPlanQual *) estate->es_evalPlanQual;
1720 rtsize = length(estate->es_range_table);
1723 if (epq != NULL && epq->rti == 0)
1725 /* Top PQ stack entry is idle, so re-use it */
1726 Assert(!(estate->es_useEvalPlan) &&
1727 epq->estate.es_evalPlanQual == NULL);
1733 * If this is request for another RTE - Ra, - then we have to check
1734 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1735 * updated again and we have to re-start old execution for Ra and
1736 * forget all what we done after Ra was suspended. Cool? -:))
1738 if (epq != NULL && epq->rti != rti &&
1739 epq->estate.es_evTuple[rti - 1] != NULL)
1743 evalPlanQual *oldepq;
1745 /* pop previous PlanQual from the stack */
1746 epqstate = &(epq->estate);
1747 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1748 Assert(oldepq->rti != 0);
1749 /* stop execution */
1750 ExecEndNode(epq->planstate);
1751 ExecDropTupleTable(epqstate->es_tupleTable, true);
1752 epqstate->es_tupleTable = NULL;
1753 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1754 epqstate->es_evTuple[epq->rti - 1] = NULL;
1755 /* push current PQ to freePQ stack */
1758 estate->es_evalPlanQual = (Pointer) epq;
1759 } while (epq->rti != rti);
1763 * If we are requested for another RTE then we have to suspend
1764 * execution of current PlanQual and start execution for new one.
1766 if (epq == NULL || epq->rti != rti)
1768 /* try to reuse plan used previously */
1769 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1771 if (newepq == NULL) /* first call or freePQ stack is empty */
1773 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1774 newepq->free = NULL;
1777 * Each stack level has its own copy of the plan tree. This
1778 * is wasteful, but necessary until plan trees are fully
1781 newepq->plan = copyObject(estate->es_origPlan);
1784 * Init stack level's EState. We share top level's copy of
1785 * es_result_relations array and other non-changing status. We
1786 * need our own tupletable, es_param_exec_vals, and other
1789 epqstate = &(newepq->estate);
1790 memcpy(epqstate, estate, sizeof(EState));
1791 epqstate->es_direction = ForwardScanDirection;
1792 if (estate->es_origPlan->nParamExec > 0)
1793 epqstate->es_param_exec_vals = (ParamExecData *)
1794 palloc(estate->es_origPlan->nParamExec *
1795 sizeof(ParamExecData));
1796 epqstate->es_tupleTable = NULL;
1797 epqstate->es_per_tuple_exprcontext = NULL;
1800 * Each epqstate must have its own es_evTupleNull state, but
1801 * all the stack entries share es_evTuple state. This allows
1802 * sub-rechecks to inherit the value being examined by an
1805 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1807 /* first PQ stack entry */
1808 epqstate->es_evTuple = (HeapTuple *)
1809 palloc0(rtsize * sizeof(HeapTuple));
1811 /* later stack entries share the same storage */
1812 epqstate->es_evTuple = epq->estate.es_evTuple;
1816 /* recycle previously used EState */
1817 epqstate = &(newepq->estate);
1819 /* push current PQ to the stack */
1820 epqstate->es_evalPlanQual = (Pointer) epq;
1822 estate->es_evalPlanQual = (Pointer) epq;
1827 Assert(epq->rti == rti);
1828 epqstate = &(epq->estate);
1831 * Ok - we're requested for the same RTE. Unfortunately we still have
1832 * to end and restart execution of the plan, because ExecReScan
1833 * wouldn't ensure that upper plan nodes would reset themselves. We
1834 * could make that work if insertion of the target tuple were
1835 * integrated with the Param mechanism somehow, so that the upper plan
1836 * nodes know that their children's outputs have changed.
1840 /* stop execution */
1841 ExecEndNode(epq->planstate);
1842 ExecDropTupleTable(epqstate->es_tupleTable, true);
1843 epqstate->es_tupleTable = NULL;
1847 * free old RTE' tuple, if any, and store target tuple where
1848 * relation's scan node will see it
1850 if (epqstate->es_evTuple[rti - 1] != NULL)
1851 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1852 epqstate->es_evTuple[rti - 1] = copyTuple;
1855 * Initialize for new recheck query; be careful to copy down state
1856 * that might have changed in top EState.
1858 epqstate->es_result_relation_info = estate->es_result_relation_info;
1859 epqstate->es_junkFilter = estate->es_junkFilter;
1860 if (estate->es_origPlan->nParamExec > 0)
1861 memset(epqstate->es_param_exec_vals, 0,
1862 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1863 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1864 epqstate->es_useEvalPlan = false;
1865 Assert(epqstate->es_tupleTable == NULL);
1866 epqstate->es_tupleTable =
1867 ExecCreateTupleTable(estate->es_tupleTable->size);
1869 epq->planstate = ExecInitNode(epq->plan, epqstate);
1871 return EvalPlanQualNext(estate);
1874 static TupleTableSlot *
1875 EvalPlanQualNext(EState *estate)
1877 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1878 EState *epqstate = &(epq->estate);
1879 evalPlanQual *oldepq;
1880 TupleTableSlot *slot;
1882 Assert(epq->rti != 0);
1885 slot = ExecProcNode(epq->planstate);
1888 * No more tuples for this PQ. Continue previous one.
1890 if (TupIsNull(slot))
1892 /* stop execution */
1893 ExecEndNode(epq->planstate);
1894 ExecDropTupleTable(epqstate->es_tupleTable, true);
1895 epqstate->es_tupleTable = NULL;
1896 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1897 epqstate->es_evTuple[epq->rti - 1] = NULL;
1898 /* pop old PQ from the stack */
1899 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1900 if (oldepq == (evalPlanQual *) NULL)
1902 epq->rti = 0; /* this is the first (oldest) */
1903 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1904 return (NULL); /* continue Query execution */
1906 Assert(oldepq->rti != 0);
1907 /* push current PQ to freePQ stack */
1910 epqstate = &(epq->estate);
1911 estate->es_evalPlanQual = (Pointer) epq;
1919 EndEvalPlanQual(EState *estate)
1921 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1922 EState *epqstate = &(epq->estate);
1923 evalPlanQual *oldepq;
1925 if (epq->rti == 0) /* plans already shutdowned */
1927 Assert(epq->estate.es_evalPlanQual == NULL);
1933 /* stop execution */
1934 ExecEndNode(epq->planstate);
1935 ExecDropTupleTable(epqstate->es_tupleTable, true);
1936 epqstate->es_tupleTable = NULL;
1937 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1939 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1940 epqstate->es_evTuple[epq->rti - 1] = NULL;
1942 /* pop old PQ from the stack */
1943 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1944 if (oldepq == (evalPlanQual *) NULL)
1946 epq->rti = 0; /* this is the first (oldest) */
1947 estate->es_useEvalPlan = false; /* PQ - mark as free */
1950 Assert(oldepq->rti != 0);
1951 /* push current PQ to freePQ stack */
1954 epqstate = &(epq->estate);
1955 estate->es_evalPlanQual = (Pointer) epq;