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.190 2002/12/05 15:50:30 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 /* decls for local routines only used within this module */
50 static void InitPlan(QueryDesc *queryDesc);
51 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
52 Index resultRelationIndex,
55 static void EndPlan(PlanState *planstate, EState *estate);
56 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
59 ScanDirection direction,
60 DestReceiver *destfunc);
61 static void ExecSelect(TupleTableSlot *slot,
62 DestReceiver *destfunc,
64 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
66 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
68 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
70 static TupleTableSlot *EvalPlanQualNext(EState *estate);
71 static void EndEvalPlanQual(EState *estate);
72 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
74 /* end of local decls */
77 /* ----------------------------------------------------------------
80 * This routine must be called at the beginning of any execution of any
83 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
84 * clear why we bother to separate the two functions, but...). The tupDesc
85 * field of the QueryDesc is filled in to describe the tuples that will be
86 * returned, and the internal fields (estate and planstate) are set up.
88 * XXX this will change soon:
89 * NB: the CurrentMemoryContext when this is called must be the context
90 * to be used as the per-query context for the query plan. ExecutorRun()
91 * and ExecutorEnd() must be called in this same memory context.
92 * ----------------------------------------------------------------
95 ExecutorStart(QueryDesc *queryDesc)
99 /* sanity checks: queryDesc must not be started already */
100 Assert(queryDesc != NULL);
101 Assert(queryDesc->estate == NULL);
104 * Build EState, fill with parameters from queryDesc
106 estate = CreateExecutorState();
107 queryDesc->estate = estate;
109 estate->es_param_list_info = queryDesc->params;
111 if (queryDesc->plantree->nParamExec > 0)
112 estate->es_param_exec_vals = (ParamExecData *)
113 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
115 estate->es_instrument = queryDesc->doInstrument;
118 * Make our own private copy of the current query snapshot data.
120 * This "freezes" our idea of which tuples are good and which are not for
121 * the life of this query, even if it outlives the current command and
124 estate->es_snapshot = CopyQuerySnapshot();
127 * Initialize the plan state tree
132 /* ----------------------------------------------------------------
135 * This is the main routine of the executor module. It accepts
136 * the query descriptor from the traffic cop and executes the
139 * ExecutorStart must have been called already.
141 * If direction is NoMovementScanDirection then nothing is done
142 * except to start up/shut down the destination. Otherwise,
143 * we retrieve up to 'count' tuples in the specified direction.
145 * Note: count = 0 is interpreted as no portal limit, e.g. run to
148 * ----------------------------------------------------------------
151 ExecutorRun(QueryDesc *queryDesc,
152 ScanDirection direction, long count)
157 DestReceiver *destfunc;
158 TupleTableSlot *result;
163 Assert(queryDesc != NULL);
166 * extract information from the query descriptor and the query
169 operation = queryDesc->operation;
170 estate = queryDesc->estate;
171 dest = queryDesc->dest;
174 * startup tuple receiver
176 estate->es_processed = 0;
177 estate->es_lastoid = InvalidOid;
179 destfunc = DestToFunction(dest);
180 (*destfunc->setup) (destfunc, (int) operation,
181 queryDesc->portalName, queryDesc->tupDesc);
186 if (direction == NoMovementScanDirection)
189 result = ExecutePlan(estate,
190 queryDesc->planstate,
199 (*destfunc->cleanup) (destfunc);
204 /* ----------------------------------------------------------------
207 * This routine must be called at the end of execution of any
209 * ----------------------------------------------------------------
212 ExecutorEnd(QueryDesc *queryDesc)
217 Assert(queryDesc != NULL);
219 estate = queryDesc->estate;
221 EndPlan(queryDesc->planstate, estate);
223 if (estate->es_snapshot != NULL)
225 if (estate->es_snapshot->xcnt > 0)
226 pfree(estate->es_snapshot->xip);
227 pfree(estate->es_snapshot);
228 estate->es_snapshot = NULL;
231 if (estate->es_param_exec_vals != NULL)
233 pfree(estate->es_param_exec_vals);
234 estate->es_param_exec_vals = NULL;
240 * CreateExecutorState
243 CreateExecutorState(void)
248 * create a new executor state
250 state = makeNode(EState);
253 * initialize the Executor State structure
255 state->es_direction = ForwardScanDirection;
256 state->es_range_table = NIL;
258 state->es_result_relations = NULL;
259 state->es_num_result_relations = 0;
260 state->es_result_relation_info = NULL;
262 state->es_junkFilter = NULL;
264 state->es_into_relation_descriptor = NULL;
266 state->es_param_list_info = NULL;
267 state->es_param_exec_vals = NULL;
269 state->es_tupleTable = NULL;
271 state->es_query_cxt = CurrentMemoryContext;
273 state->es_instrument = false;
275 state->es_per_tuple_exprcontext = NULL;
278 * return the executor state structure
286 * Check access permissions for all relations listed in a range table.
289 ExecCheckRTPerms(List *rangeTable, CmdType operation)
293 foreach(lp, rangeTable)
295 RangeTblEntry *rte = lfirst(lp);
297 ExecCheckRTEPerms(rte, operation);
303 * Check access permissions for a single RTE.
306 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
310 AclResult aclcheck_result;
313 * If it's a subquery, recursively examine its rangetable.
315 if (rte->rtekind == RTE_SUBQUERY)
317 ExecCheckRTPerms(rte->subquery->rtable, operation);
322 * Otherwise, only plain-relation RTEs need to be checked here.
323 * Function RTEs are checked by init_fcache when the function is prepared
324 * for execution. Join and special RTEs need no checks.
326 if (rte->rtekind != RTE_RELATION)
332 * userid to check as: current user unless we have a setuid
335 * Note: GetUserId() is presently fast enough that there's no harm in
336 * calling it separately for each RTE. If that stops being true, we
337 * could call it once in ExecCheckRTPerms and pass the userid down
338 * from there. But for now, no need for the extra clutter.
340 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
342 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
344 if (rte->checkForRead)
346 aclcheck_result = CHECK(ACL_SELECT);
347 if (aclcheck_result != ACLCHECK_OK)
348 aclcheck_error(aclcheck_result, get_rel_name(relOid));
351 if (rte->checkForWrite)
354 * Note: write access in a SELECT context means SELECT FOR UPDATE.
355 * Right now we don't distinguish that from true update as far as
356 * permissions checks are concerned.
361 aclcheck_result = CHECK(ACL_INSERT);
365 aclcheck_result = CHECK(ACL_UPDATE);
368 aclcheck_result = CHECK(ACL_DELETE);
371 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
373 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
376 if (aclcheck_result != ACLCHECK_OK)
377 aclcheck_error(aclcheck_result, get_rel_name(relOid));
382 /* ===============================================================
383 * ===============================================================
384 static routines follow
385 * ===============================================================
386 * ===============================================================
389 typedef struct execRowMark
396 typedef struct evalPlanQual
398 Plan *plan; /* XXX temporary */
399 PlanState *planstate;
402 struct evalPlanQual *free;
405 /* ----------------------------------------------------------------
408 * Initializes the query plan: open files, allocate storage
409 * and start up the rule manager
410 * ----------------------------------------------------------------
413 InitPlan(QueryDesc *queryDesc)
415 CmdType operation = queryDesc->operation;
416 Query *parseTree = queryDesc->parsetree;
417 Plan *plan = queryDesc->plantree;
418 EState *estate = queryDesc->estate;
419 PlanState *planstate;
421 Relation intoRelationDesc;
425 * Do permissions checks. It's sufficient to examine the query's
426 * top rangetable here --- subplan RTEs will be checked during
429 ExecCheckRTPerms(parseTree->rtable, operation);
432 * get information from query descriptor
434 rangeTable = parseTree->rtable;
437 * initialize the node's execution state
439 estate->es_range_table = rangeTable;
442 * if there is a result relation, initialize result relation stuff
444 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
446 List *resultRelations = parseTree->resultRelations;
447 int numResultRelations;
448 ResultRelInfo *resultRelInfos;
450 if (resultRelations != NIL)
453 * Multiple result relations (due to inheritance)
454 * parseTree->resultRelations identifies them all
456 ResultRelInfo *resultRelInfo;
458 numResultRelations = length(resultRelations);
459 resultRelInfos = (ResultRelInfo *)
460 palloc(numResultRelations * sizeof(ResultRelInfo));
461 resultRelInfo = resultRelInfos;
462 while (resultRelations != NIL)
464 initResultRelInfo(resultRelInfo,
465 lfirsti(resultRelations),
469 resultRelations = lnext(resultRelations);
475 * Single result relation identified by
476 * parseTree->resultRelation
478 numResultRelations = 1;
479 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
480 initResultRelInfo(resultRelInfos,
481 parseTree->resultRelation,
486 estate->es_result_relations = resultRelInfos;
487 estate->es_num_result_relations = numResultRelations;
488 /* Initialize to first or only result rel */
489 estate->es_result_relation_info = resultRelInfos;
494 * if no result relation, then set state appropriately
496 estate->es_result_relations = NULL;
497 estate->es_num_result_relations = 0;
498 estate->es_result_relation_info = NULL;
502 * Have to lock relations selected for update
504 estate->es_rowMark = NIL;
505 if (parseTree->rowMarks != NIL)
509 foreach(l, parseTree->rowMarks)
511 Index rti = lfirsti(l);
512 Oid relid = getrelid(rti, rangeTable);
516 relation = heap_open(relid, RowShareLock);
517 erm = (execRowMark *) palloc(sizeof(execRowMark));
518 erm->relation = relation;
520 snprintf(erm->resname, 32, "ctid%u", rti);
521 estate->es_rowMark = lappend(estate->es_rowMark, erm);
526 * initialize the executor "tuple" table. We need slots for all the
527 * plan nodes, plus possibly output slots for the junkfilter(s). At
528 * this point we aren't sure if we need junkfilters, so just add slots
529 * for them unconditionally.
532 int nSlots = ExecCountSlotsNode(plan);
534 if (parseTree->resultRelations != NIL)
535 nSlots += length(parseTree->resultRelations);
538 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
541 /* mark EvalPlanQual not active */
542 estate->es_origPlan = plan;
543 estate->es_evalPlanQual = NULL;
544 estate->es_evTuple = NULL;
545 estate->es_evTupleNull = NULL;
546 estate->es_useEvalPlan = false;
549 * initialize the private state information for all the nodes in the
550 * query tree. This opens files, allocates storage and leaves us
551 * ready to start processing tuples.
553 planstate = ExecInitNode(plan, estate);
556 * Get the tuple descriptor describing the type of tuples to return.
557 * (this is especially important if we are creating a relation with
560 tupType = ExecGetTupType(planstate);
563 * Initialize the junk filter if needed. SELECT and INSERT queries
564 * need a filter if there are any junk attrs in the tlist. UPDATE and
565 * DELETE always need one, since there's always a junk 'ctid'
566 * attribute present --- no need to look first.
569 bool junk_filter_needed = false;
576 foreach(tlist, plan->targetlist)
578 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
580 if (tle->resdom->resjunk)
582 junk_filter_needed = true;
589 junk_filter_needed = true;
595 if (junk_filter_needed)
598 * If there are multiple result relations, each one needs its
599 * own junk filter. Note this is only possible for
600 * UPDATE/DELETE, so we can't be fooled by some needing a
601 * filter and some not.
603 if (parseTree->resultRelations != NIL)
605 PlanState **appendplans;
607 ResultRelInfo *resultRelInfo;
610 /* Top plan had better be an Append here. */
611 Assert(IsA(plan, Append));
612 Assert(((Append *) plan)->isTarget);
613 Assert(IsA(planstate, AppendState));
614 appendplans = ((AppendState *) planstate)->appendplans;
615 as_nplans = ((AppendState *) planstate)->as_nplans;
616 Assert(as_nplans == estate->es_num_result_relations);
617 resultRelInfo = estate->es_result_relations;
618 for (i = 0; i < as_nplans; i++)
620 PlanState *subplan = appendplans[i];
623 j = ExecInitJunkFilter(subplan->plan->targetlist,
624 ExecGetTupType(subplan),
625 ExecAllocTableSlot(estate->es_tupleTable));
626 resultRelInfo->ri_junkFilter = j;
631 * Set active junkfilter too; at this point ExecInitAppend
632 * has already selected an active result relation...
634 estate->es_junkFilter =
635 estate->es_result_relation_info->ri_junkFilter;
639 /* Normal case with just one JunkFilter */
642 j = ExecInitJunkFilter(planstate->plan->targetlist,
644 ExecAllocTableSlot(estate->es_tupleTable));
645 estate->es_junkFilter = j;
646 if (estate->es_result_relation_info)
647 estate->es_result_relation_info->ri_junkFilter = j;
649 /* For SELECT, want to return the cleaned tuple type */
650 if (operation == CMD_SELECT)
651 tupType = j->jf_cleanTupType;
655 estate->es_junkFilter = NULL;
659 * initialize the "into" relation
661 intoRelationDesc = (Relation) NULL;
663 if (operation == CMD_SELECT)
665 if (!parseTree->isPortal)
668 * a select into table --- need to create the "into" table
670 if (parseTree->into != NULL)
679 * find namespace to create in, check permissions
681 intoName = parseTree->into->relname;
682 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
684 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
686 if (aclresult != ACLCHECK_OK)
687 aclcheck_error(aclresult,
688 get_namespace_name(namespaceId));
691 * have to copy tupType to get rid of constraints
693 tupdesc = CreateTupleDescCopy(tupType);
696 * Formerly we forced the output table to have OIDs, but
697 * as of 7.3 it will not have OIDs, because it's too late
698 * here to change the tupdescs of the already-initialized
699 * plan tree. (Perhaps we could recurse and change them
700 * all, but it's not really worth the trouble IMHO...)
704 heap_create_with_catalog(intoName,
710 allowSystemTableMods);
712 FreeTupleDesc(tupdesc);
715 * Advance command counter so that the newly-created
716 * relation's catalog tuples will be visible to heap_open.
718 CommandCounterIncrement();
721 * If necessary, create a TOAST table for the into
722 * relation. Note that AlterTableCreateToastTable ends
723 * with CommandCounterIncrement(), so that the TOAST table
724 * will be visible for insertion.
726 AlterTableCreateToastTable(intoRelationId, true);
728 intoRelationDesc = heap_open(intoRelationId,
729 AccessExclusiveLock);
734 estate->es_into_relation_descriptor = intoRelationDesc;
736 queryDesc->tupDesc = tupType;
737 queryDesc->planstate = planstate;
741 * Initialize ResultRelInfo data for one result relation
744 initResultRelInfo(ResultRelInfo *resultRelInfo,
745 Index resultRelationIndex,
749 Oid resultRelationOid;
750 Relation resultRelationDesc;
752 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
753 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
755 switch (resultRelationDesc->rd_rel->relkind)
757 case RELKIND_SEQUENCE:
758 elog(ERROR, "You can't change sequence relation %s",
759 RelationGetRelationName(resultRelationDesc));
761 case RELKIND_TOASTVALUE:
762 elog(ERROR, "You can't change toast relation %s",
763 RelationGetRelationName(resultRelationDesc));
766 elog(ERROR, "You can't change view relation %s",
767 RelationGetRelationName(resultRelationDesc));
771 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
772 resultRelInfo->type = T_ResultRelInfo;
773 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
774 resultRelInfo->ri_RelationDesc = resultRelationDesc;
775 resultRelInfo->ri_NumIndices = 0;
776 resultRelInfo->ri_IndexRelationDescs = NULL;
777 resultRelInfo->ri_IndexRelationInfo = NULL;
778 /* make a copy so as not to depend on relcache info not changing... */
779 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
780 resultRelInfo->ri_TrigFunctions = NULL;
781 resultRelInfo->ri_ConstraintExprs = NULL;
782 resultRelInfo->ri_junkFilter = NULL;
785 * If there are indices on the result relation, open them and save
786 * descriptors in the result relation info, so that we can add new
787 * index entries for the tuples we add/update. We need not do this
788 * for a DELETE, however, since deletion doesn't affect indexes.
790 if (resultRelationDesc->rd_rel->relhasindex &&
791 operation != CMD_DELETE)
792 ExecOpenIndices(resultRelInfo);
795 /* ----------------------------------------------------------------
798 * Cleans up the query plan -- closes files and frees up storage
799 * ----------------------------------------------------------------
802 EndPlan(PlanState *planstate, EState *estate)
804 ResultRelInfo *resultRelInfo;
809 * shut down any PlanQual processing we were doing
811 if (estate->es_evalPlanQual != NULL)
812 EndEvalPlanQual(estate);
815 * shut down the node-type-specific query processing
817 ExecEndNode(planstate);
820 * destroy the executor "tuple" table.
822 ExecDropTupleTable(estate->es_tupleTable, true);
823 estate->es_tupleTable = NULL;
826 * close the result relation(s) if any, but hold locks until xact
827 * commit. Also clean up junkfilters if present.
829 resultRelInfo = estate->es_result_relations;
830 for (i = estate->es_num_result_relations; i > 0; i--)
832 /* Close indices and then the relation itself */
833 ExecCloseIndices(resultRelInfo);
834 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
835 /* Delete the junkfilter if any */
836 if (resultRelInfo->ri_junkFilter != NULL)
837 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
842 * close the "into" relation if necessary, again keeping lock
844 if (estate->es_into_relation_descriptor != NULL)
845 heap_close(estate->es_into_relation_descriptor, NoLock);
848 * There might be a junkfilter without a result relation.
850 if (estate->es_num_result_relations == 0 &&
851 estate->es_junkFilter != NULL)
853 ExecFreeJunkFilter(estate->es_junkFilter);
854 estate->es_junkFilter = NULL;
858 * close any relations selected FOR UPDATE, again keeping locks
860 foreach(l, estate->es_rowMark)
862 execRowMark *erm = lfirst(l);
864 heap_close(erm->relation, NoLock);
868 /* ----------------------------------------------------------------
871 * processes the query plan to retrieve 'numberTuples' tuples in the
872 * direction specified.
873 * Retrieves all tuples if numberTuples is 0
875 * result is either a slot containing the last tuple in the case
876 * of a SELECT or NULL otherwise.
878 * Note: the ctid attribute is a 'junk' attribute that is removed before the
880 * ----------------------------------------------------------------
882 static TupleTableSlot *
883 ExecutePlan(EState *estate,
884 PlanState *planstate,
887 ScanDirection direction,
888 DestReceiver *destfunc)
890 JunkFilter *junkfilter;
891 TupleTableSlot *slot;
892 ItemPointer tupleid = NULL;
893 ItemPointerData tuple_ctid;
894 long current_tuple_count;
895 TupleTableSlot *result;
898 * initialize local variables
901 current_tuple_count = 0;
907 estate->es_direction = direction;
910 * Process BEFORE EACH STATEMENT triggers
915 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
918 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
921 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
929 * Loop until we've processed the proper number of tuples from the
935 /* Reset the per-output-tuple exprcontext */
936 ResetPerTupleExprContext(estate);
939 * Execute the plan and obtain a tuple
942 if (estate->es_useEvalPlan)
944 slot = EvalPlanQualNext(estate);
946 slot = ExecProcNode(planstate);
949 slot = ExecProcNode(planstate);
952 * if the tuple is null, then we assume there is nothing more to
953 * process so we just return null...
962 * if we have a junk filter, then project a new tuple with the
965 * Store this new "clean" tuple in the junkfilter's resultSlot.
966 * (Formerly, we stored it back over the "dirty" tuple, which is
967 * WRONG because that tuple slot has the wrong descriptor.)
969 * Also, extract all the junk information we need.
971 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
978 * extract the 'ctid' junk attribute.
980 if (operation == CMD_UPDATE || operation == CMD_DELETE)
982 if (!ExecGetJunkAttribute(junkfilter,
987 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
989 /* shouldn't ever get a null result... */
991 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
993 tupleid = (ItemPointer) DatumGetPointer(datum);
994 tuple_ctid = *tupleid; /* make sure we don't free the
996 tupleid = &tuple_ctid;
998 else if (estate->es_rowMark != NIL)
1003 foreach(l, estate->es_rowMark)
1005 execRowMark *erm = lfirst(l);
1007 HeapTupleData tuple;
1008 TupleTableSlot *newSlot;
1011 if (!ExecGetJunkAttribute(junkfilter,
1016 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1019 /* shouldn't ever get a null result... */
1021 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1024 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1025 test = heap_mark4update(erm->relation, &tuple, &buffer,
1026 estate->es_snapshot->curcid);
1027 ReleaseBuffer(buffer);
1030 case HeapTupleSelfUpdated:
1031 /* treat it as deleted; do not process */
1034 case HeapTupleMayBeUpdated:
1037 case HeapTupleUpdated:
1038 if (XactIsoLevel == XACT_SERIALIZABLE)
1039 elog(ERROR, "Can't serialize access due to concurrent update");
1040 if (!(ItemPointerEquals(&(tuple.t_self),
1041 (ItemPointer) DatumGetPointer(datum))))
1043 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1044 if (!(TupIsNull(newSlot)))
1047 estate->es_useEvalPlan = true;
1053 * if tuple was deleted or PlanQual failed for
1054 * updated tuple - we must not return this
1060 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1067 * Finally create a new "clean" tuple with all junk attributes
1070 newTuple = ExecRemoveJunk(junkfilter, slot);
1072 slot = ExecStoreTuple(newTuple, /* tuple to store */
1073 junkfilter->jf_resultSlot, /* dest slot */
1074 InvalidBuffer, /* this tuple has no
1076 true); /* tuple should be pfreed */
1080 * now that we have a tuple, do the appropriate thing with it..
1081 * either return it to the user, add it to a relation someplace,
1082 * delete it from a relation, or modify some of its attributes.
1087 ExecSelect(slot, /* slot containing tuple */
1088 destfunc, /* destination's tuple-receiver
1095 ExecInsert(slot, tupleid, estate);
1100 ExecDelete(slot, tupleid, estate);
1105 ExecUpdate(slot, tupleid, estate);
1110 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1116 * check our tuple count.. if we've processed the proper number
1117 * then quit, else loop again and process more tuples. Zero
1118 * number_tuples means no limit.
1120 current_tuple_count++;
1121 if (numberTuples == current_tuple_count)
1126 * Process AFTER EACH STATEMENT triggers
1131 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1134 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1137 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1145 * here, result is either a slot containing a tuple in the case of a
1146 * SELECT or NULL otherwise.
1151 /* ----------------------------------------------------------------
1154 * SELECTs are easy.. we just pass the tuple to the appropriate
1155 * print function. The only complexity is when we do a
1156 * "SELECT INTO", in which case we insert the tuple into
1157 * the appropriate relation (note: this is a newly created relation
1158 * so we don't need to worry about indices or locks.)
1159 * ----------------------------------------------------------------
1162 ExecSelect(TupleTableSlot *slot,
1163 DestReceiver *destfunc,
1170 * get the heap tuple out of the tuple table slot
1173 attrtype = slot->ttc_tupleDescriptor;
1176 * insert the tuple into the "into relation"
1178 if (estate->es_into_relation_descriptor != NULL)
1180 heap_insert(estate->es_into_relation_descriptor, tuple,
1181 estate->es_snapshot->curcid);
1186 * send the tuple to the front end (or the screen)
1188 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1190 (estate->es_processed)++;
1193 /* ----------------------------------------------------------------
1196 * INSERTs are trickier.. we have to insert the tuple into
1197 * the base relation and insert appropriate tuples into the
1199 * ----------------------------------------------------------------
1202 ExecInsert(TupleTableSlot *slot,
1203 ItemPointer tupleid,
1207 ResultRelInfo *resultRelInfo;
1208 Relation resultRelationDesc;
1213 * get the heap tuple out of the tuple table slot
1218 * get information on the (current) result relation
1220 resultRelInfo = estate->es_result_relation_info;
1221 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1223 /* BEFORE ROW INSERT Triggers */
1224 if (resultRelInfo->ri_TrigDesc &&
1225 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1229 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1231 if (newtuple == NULL) /* "do nothing" */
1234 if (newtuple != tuple) /* modified by Trigger(s) */
1237 * Insert modified tuple into tuple table slot, replacing the
1238 * original. We assume that it was allocated in per-tuple
1239 * memory context, and therefore will go away by itself. The
1240 * tuple table slot should not try to clear it.
1242 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1248 * Check the constraints of the tuple
1250 if (resultRelationDesc->rd_att->constr)
1251 ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1256 newId = heap_insert(resultRelationDesc, tuple,
1257 estate->es_snapshot->curcid);
1260 (estate->es_processed)++;
1261 estate->es_lastoid = newId;
1262 setLastTid(&(tuple->t_self));
1267 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1268 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1271 numIndices = resultRelInfo->ri_NumIndices;
1273 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1275 /* AFTER ROW INSERT Triggers */
1276 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1279 /* ----------------------------------------------------------------
1282 * DELETE is like UPDATE, we delete the tuple and its
1284 * ----------------------------------------------------------------
1287 ExecDelete(TupleTableSlot *slot,
1288 ItemPointer tupleid,
1291 ResultRelInfo *resultRelInfo;
1292 Relation resultRelationDesc;
1293 ItemPointerData ctid;
1297 * get information on the (current) result relation
1299 resultRelInfo = estate->es_result_relation_info;
1300 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1302 /* BEFORE ROW DELETE Triggers */
1303 if (resultRelInfo->ri_TrigDesc &&
1304 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1308 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1310 if (!dodelete) /* "do nothing" */
1318 result = heap_delete(resultRelationDesc, tupleid,
1320 estate->es_snapshot->curcid);
1323 case HeapTupleSelfUpdated:
1324 /* already deleted by self; nothing to do */
1327 case HeapTupleMayBeUpdated:
1330 case HeapTupleUpdated:
1331 if (XactIsoLevel == XACT_SERIALIZABLE)
1332 elog(ERROR, "Can't serialize access due to concurrent update");
1333 else if (!(ItemPointerEquals(tupleid, &ctid)))
1335 TupleTableSlot *epqslot = EvalPlanQual(estate,
1336 resultRelInfo->ri_RangeTableIndex, &ctid);
1338 if (!TupIsNull(epqslot))
1344 /* tuple already deleted; nothing to do */
1348 elog(ERROR, "Unknown status %u from heap_delete", result);
1353 (estate->es_processed)++;
1356 * Note: Normally one would think that we have to delete index tuples
1357 * associated with the heap tuple now..
1359 * ... but in POSTGRES, we have no need to do this because the vacuum
1360 * daemon automatically opens an index scan and deletes index tuples
1361 * when it finds deleted heap tuples. -cim 9/27/89
1364 /* AFTER ROW DELETE Triggers */
1365 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1368 /* ----------------------------------------------------------------
1371 * note: we can't run UPDATE queries with transactions
1372 * off because UPDATEs are actually INSERTs and our
1373 * scan will mistakenly loop forever, updating the tuple
1374 * it just inserted.. This should be fixed but until it
1375 * is, we don't want to get stuck in an infinite loop
1376 * which corrupts your database..
1377 * ----------------------------------------------------------------
1380 ExecUpdate(TupleTableSlot *slot,
1381 ItemPointer tupleid,
1385 ResultRelInfo *resultRelInfo;
1386 Relation resultRelationDesc;
1387 ItemPointerData ctid;
1392 * abort the operation if not running transactions
1394 if (IsBootstrapProcessingMode())
1396 elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1401 * get the heap tuple out of the tuple table slot
1406 * get information on the (current) result relation
1408 resultRelInfo = estate->es_result_relation_info;
1409 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1411 /* BEFORE ROW UPDATE Triggers */
1412 if (resultRelInfo->ri_TrigDesc &&
1413 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1417 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1420 if (newtuple == NULL) /* "do nothing" */
1423 if (newtuple != tuple) /* modified by Trigger(s) */
1426 * Insert modified tuple into tuple table slot, replacing the
1427 * original. We assume that it was allocated in per-tuple
1428 * memory context, and therefore will go away by itself. The
1429 * tuple table slot should not try to clear it.
1431 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1437 * Check the constraints of the tuple
1439 * If we generate a new candidate tuple after EvalPlanQual testing, we
1440 * must loop back here and recheck constraints. (We don't need to
1441 * redo triggers, however. If there are any BEFORE triggers then
1442 * trigger.c will have done mark4update to lock the correct tuple, so
1443 * there's no need to do them again.)
1446 if (resultRelationDesc->rd_att->constr)
1447 ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1450 * replace the heap tuple
1452 result = heap_update(resultRelationDesc, tupleid, tuple,
1454 estate->es_snapshot->curcid);
1457 case HeapTupleSelfUpdated:
1458 /* already deleted by self; nothing to do */
1461 case HeapTupleMayBeUpdated:
1464 case HeapTupleUpdated:
1465 if (XactIsoLevel == XACT_SERIALIZABLE)
1466 elog(ERROR, "Can't serialize access due to concurrent update");
1467 else if (!(ItemPointerEquals(tupleid, &ctid)))
1469 TupleTableSlot *epqslot = EvalPlanQual(estate,
1470 resultRelInfo->ri_RangeTableIndex, &ctid);
1472 if (!TupIsNull(epqslot))
1475 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1476 slot = ExecStoreTuple(tuple,
1477 estate->es_junkFilter->jf_resultSlot,
1478 InvalidBuffer, true);
1482 /* tuple already deleted; nothing to do */
1486 elog(ERROR, "Unknown status %u from heap_update", result);
1491 (estate->es_processed)++;
1494 * Note: instead of having to update the old index tuples associated
1495 * with the heap tuple, all we do is form and insert new index tuples.
1496 * This is because UPDATEs are actually DELETEs and INSERTs and index
1497 * tuple deletion is done automagically by the vacuum daemon. All we
1498 * do is insert new index tuples. -cim 9/27/89
1504 * heap_update updates a tuple in the base relation by invalidating it
1505 * and then inserting a new tuple to the relation. As a side effect,
1506 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1507 * field. So we now insert index tuples using the new tupleid stored
1511 numIndices = resultRelInfo->ri_NumIndices;
1513 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1515 /* AFTER ROW UPDATE Triggers */
1516 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1520 ExecRelCheck(ResultRelInfo *resultRelInfo,
1521 TupleTableSlot *slot, EState *estate)
1523 Relation rel = resultRelInfo->ri_RelationDesc;
1524 int ncheck = rel->rd_att->constr->num_check;
1525 ConstrCheck *check = rel->rd_att->constr->check;
1526 ExprContext *econtext;
1527 MemoryContext oldContext;
1532 * If first time through for this result relation, build expression
1533 * nodetrees for rel's constraint expressions. Keep them in the
1534 * per-query memory context so they'll survive throughout the query.
1536 if (resultRelInfo->ri_ConstraintExprs == NULL)
1538 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1539 resultRelInfo->ri_ConstraintExprs =
1540 (List **) palloc(ncheck * sizeof(List *));
1541 for (i = 0; i < ncheck; i++)
1543 qual = (List *) stringToNode(check[i].ccbin);
1544 resultRelInfo->ri_ConstraintExprs[i] = qual;
1546 MemoryContextSwitchTo(oldContext);
1550 * We will use the EState's per-tuple context for evaluating
1551 * constraint expressions (creating it if it's not already there).
1553 econtext = GetPerTupleExprContext(estate);
1555 /* Arrange for econtext's scan tuple to be the tuple under test */
1556 econtext->ecxt_scantuple = slot;
1558 /* And evaluate the constraints */
1559 for (i = 0; i < ncheck; i++)
1561 qual = resultRelInfo->ri_ConstraintExprs[i];
1564 * NOTE: SQL92 specifies that a NULL result from a constraint
1565 * expression is not to be treated as a failure. Therefore, tell
1566 * ExecQual to return TRUE for NULL.
1568 if (!ExecQual(qual, econtext, true))
1569 return check[i].ccname;
1572 /* NULL result means no error */
1573 return (char *) NULL;
1577 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1578 TupleTableSlot *slot, EState *estate)
1580 Relation rel = resultRelInfo->ri_RelationDesc;
1581 HeapTuple tuple = slot->val;
1582 TupleConstr *constr = rel->rd_att->constr;
1586 if (constr->has_not_null)
1588 int natts = rel->rd_att->natts;
1591 for (attrChk = 1; attrChk <= natts; attrChk++)
1593 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1594 heap_attisnull(tuple, attrChk))
1595 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1596 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1600 if (constr->num_check > 0)
1604 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1605 elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1606 caller, failed, RelationGetRelationName(rel));
1611 * Check a modified tuple to see if we want to process its updated version
1612 * under READ COMMITTED rules.
1614 * See backend/executor/README for some info about how this works.
1617 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1622 HeapTupleData tuple;
1623 HeapTuple copyTuple = NULL;
1630 * find relation containing target tuple
1632 if (estate->es_result_relation_info != NULL &&
1633 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1634 relation = estate->es_result_relation_info->ri_RelationDesc;
1640 foreach(l, estate->es_rowMark)
1642 if (((execRowMark *) lfirst(l))->rti == rti)
1644 relation = ((execRowMark *) lfirst(l))->relation;
1648 if (relation == NULL)
1649 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1655 * Loop here to deal with updated or busy tuples
1657 tuple.t_self = *tid;
1662 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1664 TransactionId xwait = SnapshotDirty->xmax;
1666 if (TransactionIdIsValid(SnapshotDirty->xmin))
1667 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1670 * If tuple is being updated by other transaction then we have
1671 * to wait for its commit/abort.
1673 if (TransactionIdIsValid(xwait))
1675 ReleaseBuffer(buffer);
1676 XactLockTableWait(xwait);
1681 * We got tuple - now copy it for use by recheck query.
1683 copyTuple = heap_copytuple(&tuple);
1684 ReleaseBuffer(buffer);
1689 * Oops! Invalid tuple. Have to check is it updated or deleted.
1690 * Note that it's possible to get invalid SnapshotDirty->tid if
1691 * tuple updated by this transaction. Have we to check this ?
1693 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1694 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1696 /* updated, so look at the updated copy */
1697 tuple.t_self = SnapshotDirty->tid;
1702 * Deleted or updated by this transaction; forget it.
1708 * For UPDATE/DELETE we have to return tid of actual row we're
1711 *tid = tuple.t_self;
1714 * Need to run a recheck subquery. Find or create a PQ stack entry.
1716 epq = (evalPlanQual *) estate->es_evalPlanQual;
1717 rtsize = length(estate->es_range_table);
1720 if (epq != NULL && epq->rti == 0)
1722 /* Top PQ stack entry is idle, so re-use it */
1723 Assert(!(estate->es_useEvalPlan) &&
1724 epq->estate.es_evalPlanQual == NULL);
1730 * If this is request for another RTE - Ra, - then we have to check
1731 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1732 * updated again and we have to re-start old execution for Ra and
1733 * forget all what we done after Ra was suspended. Cool? -:))
1735 if (epq != NULL && epq->rti != rti &&
1736 epq->estate.es_evTuple[rti - 1] != NULL)
1740 evalPlanQual *oldepq;
1742 /* pop previous PlanQual from the stack */
1743 epqstate = &(epq->estate);
1744 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1745 Assert(oldepq->rti != 0);
1746 /* stop execution */
1747 ExecEndNode(epq->planstate);
1748 ExecDropTupleTable(epqstate->es_tupleTable, true);
1749 epqstate->es_tupleTable = NULL;
1750 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1751 epqstate->es_evTuple[epq->rti - 1] = NULL;
1752 /* push current PQ to freePQ stack */
1755 estate->es_evalPlanQual = (Pointer) epq;
1756 } while (epq->rti != rti);
1760 * If we are requested for another RTE then we have to suspend
1761 * execution of current PlanQual and start execution for new one.
1763 if (epq == NULL || epq->rti != rti)
1765 /* try to reuse plan used previously */
1766 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1768 if (newepq == NULL) /* first call or freePQ stack is empty */
1770 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1771 newepq->free = NULL;
1774 * Each stack level has its own copy of the plan tree. This
1775 * is wasteful, but necessary until plan trees are fully
1778 newepq->plan = copyObject(estate->es_origPlan);
1781 * Init stack level's EState. We share top level's copy of
1782 * es_result_relations array and other non-changing status. We
1783 * need our own tupletable, es_param_exec_vals, and other
1786 epqstate = &(newepq->estate);
1787 memcpy(epqstate, estate, sizeof(EState));
1788 epqstate->es_direction = ForwardScanDirection;
1789 if (estate->es_origPlan->nParamExec > 0)
1790 epqstate->es_param_exec_vals = (ParamExecData *)
1791 palloc(estate->es_origPlan->nParamExec *
1792 sizeof(ParamExecData));
1793 epqstate->es_tupleTable = NULL;
1794 epqstate->es_per_tuple_exprcontext = NULL;
1797 * Each epqstate must have its own es_evTupleNull state, but
1798 * all the stack entries share es_evTuple state. This allows
1799 * sub-rechecks to inherit the value being examined by an
1802 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1804 /* first PQ stack entry */
1805 epqstate->es_evTuple = (HeapTuple *)
1806 palloc0(rtsize * sizeof(HeapTuple));
1808 /* later stack entries share the same storage */
1809 epqstate->es_evTuple = epq->estate.es_evTuple;
1813 /* recycle previously used EState */
1814 epqstate = &(newepq->estate);
1816 /* push current PQ to the stack */
1817 epqstate->es_evalPlanQual = (Pointer) epq;
1819 estate->es_evalPlanQual = (Pointer) epq;
1824 Assert(epq->rti == rti);
1825 epqstate = &(epq->estate);
1828 * Ok - we're requested for the same RTE. Unfortunately we still have
1829 * to end and restart execution of the plan, because ExecReScan
1830 * wouldn't ensure that upper plan nodes would reset themselves. We
1831 * could make that work if insertion of the target tuple were
1832 * integrated with the Param mechanism somehow, so that the upper plan
1833 * nodes know that their children's outputs have changed.
1837 /* stop execution */
1838 ExecEndNode(epq->planstate);
1839 ExecDropTupleTable(epqstate->es_tupleTable, true);
1840 epqstate->es_tupleTable = NULL;
1844 * free old RTE' tuple, if any, and store target tuple where
1845 * relation's scan node will see it
1847 if (epqstate->es_evTuple[rti - 1] != NULL)
1848 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1849 epqstate->es_evTuple[rti - 1] = copyTuple;
1852 * Initialize for new recheck query; be careful to copy down state
1853 * that might have changed in top EState.
1855 epqstate->es_result_relation_info = estate->es_result_relation_info;
1856 epqstate->es_junkFilter = estate->es_junkFilter;
1857 if (estate->es_origPlan->nParamExec > 0)
1858 memset(epqstate->es_param_exec_vals, 0,
1859 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1860 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1861 epqstate->es_useEvalPlan = false;
1862 Assert(epqstate->es_tupleTable == NULL);
1863 epqstate->es_tupleTable =
1864 ExecCreateTupleTable(estate->es_tupleTable->size);
1866 epq->planstate = ExecInitNode(epq->plan, epqstate);
1868 return EvalPlanQualNext(estate);
1871 static TupleTableSlot *
1872 EvalPlanQualNext(EState *estate)
1874 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1875 EState *epqstate = &(epq->estate);
1876 evalPlanQual *oldepq;
1877 TupleTableSlot *slot;
1879 Assert(epq->rti != 0);
1882 slot = ExecProcNode(epq->planstate);
1885 * No more tuples for this PQ. Continue previous one.
1887 if (TupIsNull(slot))
1889 /* stop execution */
1890 ExecEndNode(epq->planstate);
1891 ExecDropTupleTable(epqstate->es_tupleTable, true);
1892 epqstate->es_tupleTable = NULL;
1893 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1894 epqstate->es_evTuple[epq->rti - 1] = NULL;
1895 /* pop old PQ from the stack */
1896 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1897 if (oldepq == (evalPlanQual *) NULL)
1899 epq->rti = 0; /* this is the first (oldest) */
1900 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1901 return (NULL); /* continue Query execution */
1903 Assert(oldepq->rti != 0);
1904 /* push current PQ to freePQ stack */
1907 epqstate = &(epq->estate);
1908 estate->es_evalPlanQual = (Pointer) epq;
1916 EndEvalPlanQual(EState *estate)
1918 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1919 EState *epqstate = &(epq->estate);
1920 evalPlanQual *oldepq;
1922 if (epq->rti == 0) /* plans already shutdowned */
1924 Assert(epq->estate.es_evalPlanQual == NULL);
1930 /* stop execution */
1931 ExecEndNode(epq->planstate);
1932 ExecDropTupleTable(epqstate->es_tupleTable, true);
1933 epqstate->es_tupleTable = NULL;
1934 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1936 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1937 epqstate->es_evTuple[epq->rti - 1] = NULL;
1939 /* pop old PQ from the stack */
1940 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1941 if (oldepq == (evalPlanQual *) NULL)
1943 epq->rti = 0; /* this is the first (oldest) */
1944 estate->es_useEvalPlan = false; /* PQ - mark as free */
1947 Assert(oldepq->rti != 0);
1948 /* push current PQ to freePQ stack */
1951 epqstate = &(epq->estate);
1952 estate->es_evalPlanQual = (Pointer) epq;