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-2003, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
29 * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.223 2003/12/01 22:07:58 momjian 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/guc.h"
47 #include "utils/lsyscache.h"
50 typedef struct execRowMark
57 typedef struct evalPlanQual
62 struct evalPlanQual *next; /* stack of active PlanQual plans */
63 struct evalPlanQual *free; /* list of free PlanQual plans */
66 /* decls for local routines only used within this module */
67 static void InitPlan(QueryDesc *queryDesc, bool explainOnly);
68 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
69 Index resultRelationIndex,
72 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
75 ScanDirection direction,
77 static void ExecSelect(TupleTableSlot *slot,
80 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
82 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
84 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
86 static TupleTableSlot *EvalPlanQualNext(EState *estate);
87 static void EndEvalPlanQual(EState *estate);
88 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
89 static void ExecCheckXactReadOnly(Query *parsetree, CmdType operation);
90 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
91 evalPlanQual *priorepq);
92 static void EvalPlanQualStop(evalPlanQual *epq);
94 /* end of local decls */
97 /* ----------------------------------------------------------------
100 * This routine must be called at the beginning of any execution of any
103 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
104 * clear why we bother to separate the two functions, but...). The tupDesc
105 * field of the QueryDesc is filled in to describe the tuples that will be
106 * returned, and the internal fields (estate and planstate) are set up.
108 * If useCurrentSnapshot is true, run the query with the latest available
109 * snapshot, instead of the normal QuerySnapshot. Also, if it's an update
110 * or delete query, check that the rows to be updated or deleted would be
111 * visible to the normal QuerySnapshot. (This is a special-case behavior
112 * needed for referential integrity updates in serializable transactions.
113 * We must check all currently-committed rows, but we want to throw a
114 * can't-serialize error if any rows that would need updates would not be
115 * visible under the normal serializable snapshot.)
117 * If explainOnly is true, we are not actually intending to run the plan,
118 * only to set up for EXPLAIN; so skip unwanted side-effects.
120 * NB: the CurrentMemoryContext when this is called will become the parent
121 * of the per-query context used for this Executor invocation.
122 * ----------------------------------------------------------------
125 ExecutorStart(QueryDesc *queryDesc, bool useCurrentSnapshot, bool explainOnly)
128 MemoryContext oldcontext;
130 /* sanity checks: queryDesc must not be started already */
131 Assert(queryDesc != NULL);
132 Assert(queryDesc->estate == NULL);
135 * If the transaction is read-only, we need to check if any writes are
136 * planned to non-temporary tables.
139 ExecCheckXactReadOnly(queryDesc->parsetree, queryDesc->operation);
142 * Build EState, switch into per-query memory context for startup.
144 estate = CreateExecutorState();
145 queryDesc->estate = estate;
147 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
150 * Fill in parameters, if any, from queryDesc
152 estate->es_param_list_info = queryDesc->params;
154 if (queryDesc->plantree->nParamExec > 0)
155 estate->es_param_exec_vals = (ParamExecData *)
156 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
158 estate->es_instrument = queryDesc->doInstrument;
161 * Make our own private copy of the current query snapshot data.
163 * This "freezes" our idea of which tuples are good and which are not for
164 * the life of this query, even if it outlives the current command and
167 if (useCurrentSnapshot)
169 /* RI update/delete query --- must use an up-to-date snapshot */
170 estate->es_snapshot = CopyCurrentSnapshot();
171 /* crosscheck updates/deletes against transaction snapshot */
172 estate->es_crosscheck_snapshot = CopyQuerySnapshot();
176 /* normal query --- use query snapshot, no crosscheck */
177 estate->es_snapshot = CopyQuerySnapshot();
178 estate->es_crosscheck_snapshot = SnapshotAny;
182 * Initialize the plan state tree
184 InitPlan(queryDesc, explainOnly);
186 MemoryContextSwitchTo(oldcontext);
189 /* ----------------------------------------------------------------
192 * This is the main routine of the executor module. It accepts
193 * the query descriptor from the traffic cop and executes the
196 * ExecutorStart must have been called already.
198 * If direction is NoMovementScanDirection then nothing is done
199 * except to start up/shut down the destination. Otherwise,
200 * we retrieve up to 'count' tuples in the specified direction.
202 * Note: count = 0 is interpreted as no portal limit, i.e., run to
205 * ----------------------------------------------------------------
208 ExecutorRun(QueryDesc *queryDesc,
209 ScanDirection direction, long count)
214 TupleTableSlot *result;
215 MemoryContext oldcontext;
218 Assert(queryDesc != NULL);
220 estate = queryDesc->estate;
222 Assert(estate != NULL);
225 * Switch into per-query memory context
227 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
230 * extract information from the query descriptor and the query
233 operation = queryDesc->operation;
234 dest = queryDesc->dest;
237 * startup tuple receiver
239 estate->es_processed = 0;
240 estate->es_lastoid = InvalidOid;
242 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
247 if (direction == NoMovementScanDirection)
250 result = ExecutePlan(estate,
251 queryDesc->planstate,
260 (*dest->rShutdown) (dest);
262 MemoryContextSwitchTo(oldcontext);
267 /* ----------------------------------------------------------------
270 * This routine must be called at the end of execution of any
272 * ----------------------------------------------------------------
275 ExecutorEnd(QueryDesc *queryDesc)
278 MemoryContext oldcontext;
281 Assert(queryDesc != NULL);
283 estate = queryDesc->estate;
285 Assert(estate != NULL);
288 * Switch into per-query memory context to run ExecEndPlan
290 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
292 ExecEndPlan(queryDesc->planstate, estate);
295 * Must switch out of context before destroying it
297 MemoryContextSwitchTo(oldcontext);
300 * Release EState and per-query memory context. This should release
301 * everything the executor has allocated.
303 FreeExecutorState(estate);
305 /* Reset queryDesc fields that no longer point to anything */
306 queryDesc->tupDesc = NULL;
307 queryDesc->estate = NULL;
308 queryDesc->planstate = NULL;
311 /* ----------------------------------------------------------------
314 * This routine may be called on an open queryDesc to rewind it
316 * ----------------------------------------------------------------
319 ExecutorRewind(QueryDesc *queryDesc)
322 MemoryContext oldcontext;
325 Assert(queryDesc != NULL);
327 estate = queryDesc->estate;
329 Assert(estate != NULL);
331 /* It's probably not sensible to rescan updating queries */
332 Assert(queryDesc->operation == CMD_SELECT);
335 * Switch into per-query memory context
337 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
342 ExecReScan(queryDesc->planstate, NULL);
344 MemoryContextSwitchTo(oldcontext);
350 * Check access permissions for all relations listed in a range table.
353 ExecCheckRTPerms(List *rangeTable, CmdType operation)
357 foreach(lp, rangeTable)
359 RangeTblEntry *rte = lfirst(lp);
361 ExecCheckRTEPerms(rte, operation);
367 * Check access permissions for a single RTE.
370 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
374 AclResult aclcheck_result;
377 * If it's a subquery, recursively examine its rangetable.
379 if (rte->rtekind == RTE_SUBQUERY)
381 ExecCheckRTPerms(rte->subquery->rtable, operation);
386 * Otherwise, only plain-relation RTEs need to be checked here.
387 * Function RTEs are checked by init_fcache when the function is
388 * prepared for execution. Join and special RTEs need no checks.
390 if (rte->rtekind != RTE_RELATION)
396 * userid to check as: current user unless we have a setuid
399 * Note: GetUserId() is presently fast enough that there's no harm in
400 * calling it separately for each RTE. If that stops being true, we
401 * could call it once in ExecCheckRTPerms and pass the userid down
402 * from there. But for now, no need for the extra clutter.
404 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
406 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
408 if (rte->checkForRead)
410 aclcheck_result = CHECK(ACL_SELECT);
411 if (aclcheck_result != ACLCHECK_OK)
412 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
413 get_rel_name(relOid));
416 if (rte->checkForWrite)
419 * Note: write access in a SELECT context means SELECT FOR UPDATE.
420 * Right now we don't distinguish that from true update as far as
421 * permissions checks are concerned.
426 aclcheck_result = CHECK(ACL_INSERT);
430 aclcheck_result = CHECK(ACL_UPDATE);
433 aclcheck_result = CHECK(ACL_DELETE);
436 elog(ERROR, "unrecognized operation code: %d",
438 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
441 if (aclcheck_result != ACLCHECK_OK)
442 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
443 get_rel_name(relOid));
448 ExecCheckXactReadOnly(Query *parsetree, CmdType operation)
453 /* CREATE TABLE AS or SELECT INTO */
454 if (operation == CMD_SELECT && parsetree->into != NULL)
457 if (operation == CMD_DELETE || operation == CMD_INSERT
458 || operation == CMD_UPDATE)
462 foreach(lp, parsetree->rtable)
464 RangeTblEntry *rte = lfirst(lp);
466 if (rte->rtekind != RTE_RELATION)
469 if (!rte->checkForWrite)
472 if (isTempNamespace(get_rel_namespace(rte->relid)))
483 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
484 errmsg("transaction is read-only")));
488 /* ----------------------------------------------------------------
491 * Initializes the query plan: open files, allocate storage
492 * and start up the rule manager
493 * ----------------------------------------------------------------
496 InitPlan(QueryDesc *queryDesc, bool explainOnly)
498 CmdType operation = queryDesc->operation;
499 Query *parseTree = queryDesc->parsetree;
500 Plan *plan = queryDesc->plantree;
501 EState *estate = queryDesc->estate;
502 PlanState *planstate;
504 Relation intoRelationDesc;
509 * Do permissions checks. It's sufficient to examine the query's top
510 * rangetable here --- subplan RTEs will be checked during
513 ExecCheckRTPerms(parseTree->rtable, operation);
516 * get information from query descriptor
518 rangeTable = parseTree->rtable;
521 * initialize the node's execution state
523 estate->es_range_table = rangeTable;
526 * if there is a result relation, initialize result relation stuff
528 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
530 List *resultRelations = parseTree->resultRelations;
531 int numResultRelations;
532 ResultRelInfo *resultRelInfos;
534 if (resultRelations != NIL)
537 * Multiple result relations (due to inheritance)
538 * parseTree->resultRelations identifies them all
540 ResultRelInfo *resultRelInfo;
542 numResultRelations = length(resultRelations);
543 resultRelInfos = (ResultRelInfo *)
544 palloc(numResultRelations * sizeof(ResultRelInfo));
545 resultRelInfo = resultRelInfos;
546 while (resultRelations != NIL)
548 initResultRelInfo(resultRelInfo,
549 lfirsti(resultRelations),
553 resultRelations = lnext(resultRelations);
559 * Single result relation identified by
560 * parseTree->resultRelation
562 numResultRelations = 1;
563 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
564 initResultRelInfo(resultRelInfos,
565 parseTree->resultRelation,
570 estate->es_result_relations = resultRelInfos;
571 estate->es_num_result_relations = numResultRelations;
572 /* Initialize to first or only result rel */
573 estate->es_result_relation_info = resultRelInfos;
578 * if no result relation, then set state appropriately
580 estate->es_result_relations = NULL;
581 estate->es_num_result_relations = 0;
582 estate->es_result_relation_info = NULL;
586 * Detect whether we're doing SELECT INTO. If so, set the force_oids
587 * flag appropriately so that the plan tree will be initialized with
588 * the correct tuple descriptors.
590 do_select_into = false;
592 if (operation == CMD_SELECT && parseTree->into != NULL)
594 do_select_into = true;
597 * The presence of OIDs in the result set of SELECT INTO is
598 * controlled by the default_with_oids GUC parameter. The
599 * behavior in versions of PostgreSQL prior to 7.5 is to
600 * always include OIDs.
602 estate->es_force_oids = default_with_oids;
606 * Have to lock relations selected for update
608 estate->es_rowMark = NIL;
609 if (parseTree->rowMarks != NIL)
613 foreach(l, parseTree->rowMarks)
615 Index rti = lfirsti(l);
616 Oid relid = getrelid(rti, rangeTable);
620 relation = heap_open(relid, RowShareLock);
621 erm = (execRowMark *) palloc(sizeof(execRowMark));
622 erm->relation = relation;
624 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rti);
625 estate->es_rowMark = lappend(estate->es_rowMark, erm);
630 * initialize the executor "tuple" table. We need slots for all the
631 * plan nodes, plus possibly output slots for the junkfilter(s). At
632 * this point we aren't sure if we need junkfilters, so just add slots
633 * for them unconditionally.
636 int nSlots = ExecCountSlotsNode(plan);
638 if (parseTree->resultRelations != NIL)
639 nSlots += length(parseTree->resultRelations);
642 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
645 /* mark EvalPlanQual not active */
646 estate->es_topPlan = plan;
647 estate->es_evalPlanQual = NULL;
648 estate->es_evTupleNull = NULL;
649 estate->es_evTuple = NULL;
650 estate->es_useEvalPlan = false;
653 * initialize the private state information for all the nodes in the
654 * query tree. This opens files, allocates storage and leaves us
655 * ready to start processing tuples.
657 planstate = ExecInitNode(plan, estate);
660 * Get the tuple descriptor describing the type of tuples to return.
661 * (this is especially important if we are creating a relation with
664 tupType = ExecGetResultType(planstate);
667 * Initialize the junk filter if needed. SELECT and INSERT queries
668 * need a filter if there are any junk attrs in the tlist. INSERT and
669 * SELECT INTO also need a filter if the top plan node is a scan node
670 * that's not doing projection (else we'll be scribbling on the scan
671 * tuple!) UPDATE and DELETE always need a filter, since there's
672 * always a junk 'ctid' attribute present --- no need to look first.
675 bool junk_filter_needed = false;
682 foreach(tlist, plan->targetlist)
684 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
686 if (tle->resdom->resjunk)
688 junk_filter_needed = true;
692 if (!junk_filter_needed &&
693 (operation == CMD_INSERT || do_select_into))
695 if (IsA(planstate, SeqScanState) ||
696 IsA(planstate, IndexScanState) ||
697 IsA(planstate, TidScanState) ||
698 IsA(planstate, SubqueryScanState) ||
699 IsA(planstate, FunctionScanState))
701 if (planstate->ps_ProjInfo == NULL)
702 junk_filter_needed = true;
708 junk_filter_needed = true;
714 if (junk_filter_needed)
717 * If there are multiple result relations, each one needs its
718 * own junk filter. Note this is only possible for
719 * UPDATE/DELETE, so we can't be fooled by some needing a
720 * filter and some not.
722 if (parseTree->resultRelations != NIL)
724 PlanState **appendplans;
726 ResultRelInfo *resultRelInfo;
729 /* Top plan had better be an Append here. */
730 Assert(IsA(plan, Append));
731 Assert(((Append *) plan)->isTarget);
732 Assert(IsA(planstate, AppendState));
733 appendplans = ((AppendState *) planstate)->appendplans;
734 as_nplans = ((AppendState *) planstate)->as_nplans;
735 Assert(as_nplans == estate->es_num_result_relations);
736 resultRelInfo = estate->es_result_relations;
737 for (i = 0; i < as_nplans; i++)
739 PlanState *subplan = appendplans[i];
742 j = ExecInitJunkFilter(subplan->plan->targetlist,
743 ExecGetResultType(subplan),
744 ExecAllocTableSlot(estate->es_tupleTable));
745 resultRelInfo->ri_junkFilter = j;
750 * Set active junkfilter too; at this point ExecInitAppend
751 * has already selected an active result relation...
753 estate->es_junkFilter =
754 estate->es_result_relation_info->ri_junkFilter;
758 /* Normal case with just one JunkFilter */
761 j = ExecInitJunkFilter(planstate->plan->targetlist,
763 ExecAllocTableSlot(estate->es_tupleTable));
764 estate->es_junkFilter = j;
765 if (estate->es_result_relation_info)
766 estate->es_result_relation_info->ri_junkFilter = j;
768 /* For SELECT, want to return the cleaned tuple type */
769 if (operation == CMD_SELECT)
770 tupType = j->jf_cleanTupType;
774 estate->es_junkFilter = NULL;
778 * If doing SELECT INTO, initialize the "into" relation. We must wait
779 * till now so we have the "clean" result tuple type to create the new
782 * If EXPLAIN, skip creating the "into" relation.
784 intoRelationDesc = (Relation) NULL;
786 if (do_select_into && !explainOnly)
795 * find namespace to create in, check permissions
797 intoName = parseTree->into->relname;
798 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
800 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
802 if (aclresult != ACLCHECK_OK)
803 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
804 get_namespace_name(namespaceId));
807 * have to copy tupType to get rid of constraints
809 tupdesc = CreateTupleDescCopy(tupType);
811 intoRelationId = heap_create_with_catalog(intoName,
817 allowSystemTableMods);
819 FreeTupleDesc(tupdesc);
822 * Advance command counter so that the newly-created relation's
823 * catalog tuples will be visible to heap_open.
825 CommandCounterIncrement();
828 * If necessary, create a TOAST table for the into relation. Note
829 * that AlterTableCreateToastTable ends with
830 * CommandCounterIncrement(), so that the TOAST table will be
831 * visible for insertion.
833 AlterTableCreateToastTable(intoRelationId, true);
836 * And open the constructed table for writing.
838 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
841 estate->es_into_relation_descriptor = intoRelationDesc;
843 queryDesc->tupDesc = tupType;
844 queryDesc->planstate = planstate;
848 * Initialize ResultRelInfo data for one result relation
851 initResultRelInfo(ResultRelInfo *resultRelInfo,
852 Index resultRelationIndex,
856 Oid resultRelationOid;
857 Relation resultRelationDesc;
859 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
860 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
862 switch (resultRelationDesc->rd_rel->relkind)
864 case RELKIND_SEQUENCE:
866 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
867 errmsg("cannot change sequence \"%s\"",
868 RelationGetRelationName(resultRelationDesc))));
870 case RELKIND_TOASTVALUE:
872 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
873 errmsg("cannot change TOAST relation \"%s\"",
874 RelationGetRelationName(resultRelationDesc))));
878 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
879 errmsg("cannot change view \"%s\"",
880 RelationGetRelationName(resultRelationDesc))));
884 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
885 resultRelInfo->type = T_ResultRelInfo;
886 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
887 resultRelInfo->ri_RelationDesc = resultRelationDesc;
888 resultRelInfo->ri_NumIndices = 0;
889 resultRelInfo->ri_IndexRelationDescs = NULL;
890 resultRelInfo->ri_IndexRelationInfo = NULL;
891 /* make a copy so as not to depend on relcache info not changing... */
892 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
893 resultRelInfo->ri_TrigFunctions = NULL;
894 resultRelInfo->ri_ConstraintExprs = NULL;
895 resultRelInfo->ri_junkFilter = NULL;
898 * If there are indices on the result relation, open them and save
899 * descriptors in the result relation info, so that we can add new
900 * index entries for the tuples we add/update. We need not do this
901 * for a DELETE, however, since deletion doesn't affect indexes.
903 if (resultRelationDesc->rd_rel->relhasindex &&
904 operation != CMD_DELETE)
905 ExecOpenIndices(resultRelInfo);
908 /* ----------------------------------------------------------------
911 * Cleans up the query plan -- closes files and frees up storage
913 * NOTE: we are no longer very worried about freeing storage per se
914 * in this code; FreeExecutorState should be guaranteed to release all
915 * memory that needs to be released. What we are worried about doing
916 * is closing relations and dropping buffer pins. Thus, for example,
917 * tuple tables must be cleared or dropped to ensure pins are released.
918 * ----------------------------------------------------------------
921 ExecEndPlan(PlanState *planstate, EState *estate)
923 ResultRelInfo *resultRelInfo;
928 * shut down any PlanQual processing we were doing
930 if (estate->es_evalPlanQual != NULL)
931 EndEvalPlanQual(estate);
934 * shut down the node-type-specific query processing
936 ExecEndNode(planstate);
939 * destroy the executor "tuple" table.
941 ExecDropTupleTable(estate->es_tupleTable, true);
942 estate->es_tupleTable = NULL;
945 * close the result relation(s) if any, but hold locks until xact
948 resultRelInfo = estate->es_result_relations;
949 for (i = estate->es_num_result_relations; i > 0; i--)
951 /* Close indices and then the relation itself */
952 ExecCloseIndices(resultRelInfo);
953 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
958 * close the "into" relation if necessary, again keeping lock
960 if (estate->es_into_relation_descriptor != NULL)
961 heap_close(estate->es_into_relation_descriptor, NoLock);
964 * close any relations selected FOR UPDATE, again keeping locks
966 foreach(l, estate->es_rowMark)
968 execRowMark *erm = lfirst(l);
970 heap_close(erm->relation, NoLock);
974 /* ----------------------------------------------------------------
977 * processes the query plan to retrieve 'numberTuples' tuples in the
978 * direction specified.
980 * Retrieves all tuples if numberTuples is 0
982 * result is either a slot containing the last tuple in the case
983 * of a SELECT or NULL otherwise.
985 * Note: the ctid attribute is a 'junk' attribute that is removed before the
987 * ----------------------------------------------------------------
989 static TupleTableSlot *
990 ExecutePlan(EState *estate,
991 PlanState *planstate,
994 ScanDirection direction,
997 JunkFilter *junkfilter;
998 TupleTableSlot *slot;
999 ItemPointer tupleid = NULL;
1000 ItemPointerData tuple_ctid;
1001 long current_tuple_count;
1002 TupleTableSlot *result;
1005 * initialize local variables
1008 current_tuple_count = 0;
1012 * Set the direction.
1014 estate->es_direction = direction;
1017 * Process BEFORE EACH STATEMENT triggers
1022 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1025 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1028 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1036 * Loop until we've processed the proper number of tuples from the
1042 /* Reset the per-output-tuple exprcontext */
1043 ResetPerTupleExprContext(estate);
1046 * Execute the plan and obtain a tuple
1049 if (estate->es_useEvalPlan)
1051 slot = EvalPlanQualNext(estate);
1052 if (TupIsNull(slot))
1053 slot = ExecProcNode(planstate);
1056 slot = ExecProcNode(planstate);
1059 * if the tuple is null, then we assume there is nothing more to
1060 * process so we just return null...
1062 if (TupIsNull(slot))
1069 * if we have a junk filter, then project a new tuple with the
1072 * Store this new "clean" tuple in the junkfilter's resultSlot.
1073 * (Formerly, we stored it back over the "dirty" tuple, which is
1074 * WRONG because that tuple slot has the wrong descriptor.)
1076 * Also, extract all the junk information we need.
1078 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
1085 * extract the 'ctid' junk attribute.
1087 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1089 if (!ExecGetJunkAttribute(junkfilter,
1094 elog(ERROR, "could not find junk ctid column");
1096 /* shouldn't ever get a null result... */
1098 elog(ERROR, "ctid is NULL");
1100 tupleid = (ItemPointer) DatumGetPointer(datum);
1101 tuple_ctid = *tupleid; /* make sure we don't free the
1103 tupleid = &tuple_ctid;
1105 else if (estate->es_rowMark != NIL)
1110 foreach(l, estate->es_rowMark)
1112 execRowMark *erm = lfirst(l);
1114 HeapTupleData tuple;
1115 TupleTableSlot *newSlot;
1118 if (!ExecGetJunkAttribute(junkfilter,
1123 elog(ERROR, "could not find junk \"%s\" column",
1126 /* shouldn't ever get a null result... */
1128 elog(ERROR, "\"%s\" is NULL", erm->resname);
1130 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1131 test = heap_mark4update(erm->relation, &tuple, &buffer,
1132 estate->es_snapshot->curcid);
1133 ReleaseBuffer(buffer);
1136 case HeapTupleSelfUpdated:
1137 /* treat it as deleted; do not process */
1140 case HeapTupleMayBeUpdated:
1143 case HeapTupleUpdated:
1144 if (IsXactIsoLevelSerializable)
1146 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1147 errmsg("could not serialize access due to concurrent update")));
1148 if (!(ItemPointerEquals(&(tuple.t_self),
1149 (ItemPointer) DatumGetPointer(datum))))
1151 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1152 if (!(TupIsNull(newSlot)))
1155 estate->es_useEvalPlan = true;
1161 * if tuple was deleted or PlanQual failed for
1162 * updated tuple - we must not return this
1168 elog(ERROR, "unrecognized heap_mark4update status: %u",
1176 * Finally create a new "clean" tuple with all junk attributes
1179 newTuple = ExecRemoveJunk(junkfilter, slot);
1181 slot = ExecStoreTuple(newTuple, /* tuple to store */
1182 junkfilter->jf_resultSlot, /* dest slot */
1183 InvalidBuffer, /* this tuple has no
1185 true); /* tuple should be pfreed */
1189 * now that we have a tuple, do the appropriate thing with it..
1190 * either return it to the user, add it to a relation someplace,
1191 * delete it from a relation, or modify some of its attributes.
1196 ExecSelect(slot, /* slot containing tuple */
1197 dest, /* destination's tuple-receiver obj */
1203 ExecInsert(slot, tupleid, estate);
1208 ExecDelete(slot, tupleid, estate);
1213 ExecUpdate(slot, tupleid, estate);
1218 elog(ERROR, "unrecognized operation code: %d",
1225 * check our tuple count.. if we've processed the proper number
1226 * then quit, else loop again and process more tuples. Zero
1227 * numberTuples means no limit.
1229 current_tuple_count++;
1230 if (numberTuples && numberTuples == current_tuple_count)
1235 * Process AFTER EACH STATEMENT triggers
1240 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1243 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1246 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1254 * here, result is either a slot containing a tuple in the case of a
1255 * SELECT or NULL otherwise.
1260 /* ----------------------------------------------------------------
1263 * SELECTs are easy.. we just pass the tuple to the appropriate
1264 * print function. The only complexity is when we do a
1265 * "SELECT INTO", in which case we insert the tuple into
1266 * the appropriate relation (note: this is a newly created relation
1267 * so we don't need to worry about indices or locks.)
1268 * ----------------------------------------------------------------
1271 ExecSelect(TupleTableSlot *slot,
1279 * get the heap tuple out of the tuple table slot
1282 attrtype = slot->ttc_tupleDescriptor;
1285 * insert the tuple into the "into relation"
1287 * XXX this probably ought to be replaced by a separate destination
1289 if (estate->es_into_relation_descriptor != NULL)
1291 heap_insert(estate->es_into_relation_descriptor, tuple,
1292 estate->es_snapshot->curcid);
1297 * send the tuple to the destination
1299 (*dest->receiveTuple) (tuple, attrtype, dest);
1301 (estate->es_processed)++;
1304 /* ----------------------------------------------------------------
1307 * INSERTs are trickier.. we have to insert the tuple into
1308 * the base relation and insert appropriate tuples into the
1310 * ----------------------------------------------------------------
1313 ExecInsert(TupleTableSlot *slot,
1314 ItemPointer tupleid,
1318 ResultRelInfo *resultRelInfo;
1319 Relation resultRelationDesc;
1324 * get the heap tuple out of the tuple table slot
1329 * get information on the (current) result relation
1331 resultRelInfo = estate->es_result_relation_info;
1332 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1334 /* BEFORE ROW INSERT Triggers */
1335 if (resultRelInfo->ri_TrigDesc &&
1336 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1340 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1342 if (newtuple == NULL) /* "do nothing" */
1345 if (newtuple != tuple) /* modified by Trigger(s) */
1348 * Insert modified tuple into tuple table slot, replacing the
1349 * original. We assume that it was allocated in per-tuple
1350 * memory context, and therefore will go away by itself. The
1351 * tuple table slot should not try to clear it.
1353 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1359 * Check the constraints of the tuple
1361 if (resultRelationDesc->rd_att->constr)
1362 ExecConstraints(resultRelInfo, slot, estate);
1367 newId = heap_insert(resultRelationDesc, tuple,
1368 estate->es_snapshot->curcid);
1371 (estate->es_processed)++;
1372 estate->es_lastoid = newId;
1373 setLastTid(&(tuple->t_self));
1378 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1379 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1382 numIndices = resultRelInfo->ri_NumIndices;
1384 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1386 /* AFTER ROW INSERT Triggers */
1387 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1390 /* ----------------------------------------------------------------
1393 * DELETE is like UPDATE, we delete the tuple and its
1395 * ----------------------------------------------------------------
1398 ExecDelete(TupleTableSlot *slot,
1399 ItemPointer tupleid,
1402 ResultRelInfo *resultRelInfo;
1403 Relation resultRelationDesc;
1404 ItemPointerData ctid;
1408 * get information on the (current) result relation
1410 resultRelInfo = estate->es_result_relation_info;
1411 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1413 /* BEFORE ROW DELETE Triggers */
1414 if (resultRelInfo->ri_TrigDesc &&
1415 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1419 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1420 estate->es_snapshot->curcid);
1422 if (!dodelete) /* "do nothing" */
1430 result = heap_delete(resultRelationDesc, tupleid,
1432 estate->es_snapshot->curcid,
1433 estate->es_crosscheck_snapshot,
1434 true /* wait for commit */);
1437 case HeapTupleSelfUpdated:
1438 /* already deleted by self; nothing to do */
1441 case HeapTupleMayBeUpdated:
1444 case HeapTupleUpdated:
1445 if (IsXactIsoLevelSerializable)
1447 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1448 errmsg("could not serialize access due to concurrent update")));
1449 else if (!(ItemPointerEquals(tupleid, &ctid)))
1451 TupleTableSlot *epqslot = EvalPlanQual(estate,
1452 resultRelInfo->ri_RangeTableIndex, &ctid);
1454 if (!TupIsNull(epqslot))
1460 /* tuple already deleted; nothing to do */
1464 elog(ERROR, "unrecognized heap_delete status: %u", result);
1469 (estate->es_processed)++;
1472 * Note: Normally one would think that we have to delete index tuples
1473 * associated with the heap tuple now..
1475 * ... but in POSTGRES, we have no need to do this because the vacuum
1476 * daemon automatically opens an index scan and deletes index tuples
1477 * when it finds deleted heap tuples. -cim 9/27/89
1480 /* AFTER ROW DELETE Triggers */
1481 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1484 /* ----------------------------------------------------------------
1487 * note: we can't run UPDATE queries with transactions
1488 * off because UPDATEs are actually INSERTs and our
1489 * scan will mistakenly loop forever, updating the tuple
1490 * it just inserted.. This should be fixed but until it
1491 * is, we don't want to get stuck in an infinite loop
1492 * which corrupts your database..
1493 * ----------------------------------------------------------------
1496 ExecUpdate(TupleTableSlot *slot,
1497 ItemPointer tupleid,
1501 ResultRelInfo *resultRelInfo;
1502 Relation resultRelationDesc;
1503 ItemPointerData ctid;
1508 * abort the operation if not running transactions
1510 if (IsBootstrapProcessingMode())
1511 elog(ERROR, "cannot UPDATE during bootstrap");
1514 * get the heap tuple out of the tuple table slot
1519 * get information on the (current) result relation
1521 resultRelInfo = estate->es_result_relation_info;
1522 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1524 /* BEFORE ROW UPDATE Triggers */
1525 if (resultRelInfo->ri_TrigDesc &&
1526 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1530 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1532 estate->es_snapshot->curcid);
1534 if (newtuple == NULL) /* "do nothing" */
1537 if (newtuple != tuple) /* modified by Trigger(s) */
1540 * Insert modified tuple into tuple table slot, replacing the
1541 * original. We assume that it was allocated in per-tuple
1542 * memory context, and therefore will go away by itself. The
1543 * tuple table slot should not try to clear it.
1545 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1551 * Check the constraints of the tuple
1553 * If we generate a new candidate tuple after EvalPlanQual testing, we
1554 * must loop back here and recheck constraints. (We don't need to
1555 * redo triggers, however. If there are any BEFORE triggers then
1556 * trigger.c will have done mark4update to lock the correct tuple, so
1557 * there's no need to do them again.)
1560 if (resultRelationDesc->rd_att->constr)
1561 ExecConstraints(resultRelInfo, slot, estate);
1564 * replace the heap tuple
1566 result = heap_update(resultRelationDesc, tupleid, tuple,
1568 estate->es_snapshot->curcid,
1569 estate->es_crosscheck_snapshot,
1570 true /* wait for commit */);
1573 case HeapTupleSelfUpdated:
1574 /* already deleted by self; nothing to do */
1577 case HeapTupleMayBeUpdated:
1580 case HeapTupleUpdated:
1581 if (IsXactIsoLevelSerializable)
1583 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1584 errmsg("could not serialize access due to concurrent update")));
1585 else if (!(ItemPointerEquals(tupleid, &ctid)))
1587 TupleTableSlot *epqslot = EvalPlanQual(estate,
1588 resultRelInfo->ri_RangeTableIndex, &ctid);
1590 if (!TupIsNull(epqslot))
1593 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1594 slot = ExecStoreTuple(tuple,
1595 estate->es_junkFilter->jf_resultSlot,
1596 InvalidBuffer, true);
1600 /* tuple already deleted; nothing to do */
1604 elog(ERROR, "unrecognized heap_update status: %u", result);
1609 (estate->es_processed)++;
1612 * Note: instead of having to update the old index tuples associated
1613 * with the heap tuple, all we do is form and insert new index tuples.
1614 * This is because UPDATEs are actually DELETEs and INSERTs and index
1615 * tuple deletion is done automagically by the vacuum daemon. All we
1616 * do is insert new index tuples. -cim 9/27/89
1622 * heap_update updates a tuple in the base relation by invalidating it
1623 * and then inserting a new tuple to the relation. As a side effect,
1624 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1625 * field. So we now insert index tuples using the new tupleid stored
1629 numIndices = resultRelInfo->ri_NumIndices;
1631 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1633 /* AFTER ROW UPDATE Triggers */
1634 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1638 ExecRelCheck(ResultRelInfo *resultRelInfo,
1639 TupleTableSlot *slot, EState *estate)
1641 Relation rel = resultRelInfo->ri_RelationDesc;
1642 int ncheck = rel->rd_att->constr->num_check;
1643 ConstrCheck *check = rel->rd_att->constr->check;
1644 ExprContext *econtext;
1645 MemoryContext oldContext;
1650 * If first time through for this result relation, build expression
1651 * nodetrees for rel's constraint expressions. Keep them in the
1652 * per-query memory context so they'll survive throughout the query.
1654 if (resultRelInfo->ri_ConstraintExprs == NULL)
1656 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1657 resultRelInfo->ri_ConstraintExprs =
1658 (List **) palloc(ncheck * sizeof(List *));
1659 for (i = 0; i < ncheck; i++)
1661 qual = (List *) stringToNode(check[i].ccbin);
1662 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1663 ExecPrepareExpr((Expr *) qual, estate);
1665 MemoryContextSwitchTo(oldContext);
1669 * We will use the EState's per-tuple context for evaluating
1670 * constraint expressions (creating it if it's not already there).
1672 econtext = GetPerTupleExprContext(estate);
1674 /* Arrange for econtext's scan tuple to be the tuple under test */
1675 econtext->ecxt_scantuple = slot;
1677 /* And evaluate the constraints */
1678 for (i = 0; i < ncheck; i++)
1680 qual = resultRelInfo->ri_ConstraintExprs[i];
1683 * NOTE: SQL92 specifies that a NULL result from a constraint
1684 * expression is not to be treated as a failure. Therefore, tell
1685 * ExecQual to return TRUE for NULL.
1687 if (!ExecQual(qual, econtext, true))
1688 return check[i].ccname;
1691 /* NULL result means no error */
1696 ExecConstraints(ResultRelInfo *resultRelInfo,
1697 TupleTableSlot *slot, EState *estate)
1699 Relation rel = resultRelInfo->ri_RelationDesc;
1700 HeapTuple tuple = slot->val;
1701 TupleConstr *constr = rel->rd_att->constr;
1705 if (constr->has_not_null)
1707 int natts = rel->rd_att->natts;
1710 for (attrChk = 1; attrChk <= natts; attrChk++)
1712 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1713 heap_attisnull(tuple, attrChk))
1715 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1716 errmsg("null value in column \"%s\" violates not-null constraint",
1717 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1721 if (constr->num_check > 0)
1725 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1727 (errcode(ERRCODE_CHECK_VIOLATION),
1728 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1729 RelationGetRelationName(rel), failed)));
1734 * Check a modified tuple to see if we want to process its updated version
1735 * under READ COMMITTED rules.
1737 * See backend/executor/README for some info about how this works.
1740 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1745 HeapTupleData tuple;
1746 HeapTuple copyTuple = NULL;
1752 * find relation containing target tuple
1754 if (estate->es_result_relation_info != NULL &&
1755 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1756 relation = estate->es_result_relation_info->ri_RelationDesc;
1762 foreach(l, estate->es_rowMark)
1764 if (((execRowMark *) lfirst(l))->rti == rti)
1766 relation = ((execRowMark *) lfirst(l))->relation;
1770 if (relation == NULL)
1771 elog(ERROR, "could not find RowMark for RT index %u", rti);
1777 * Loop here to deal with updated or busy tuples
1779 tuple.t_self = *tid;
1784 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1786 TransactionId xwait = SnapshotDirty->xmax;
1788 /* xmin should not be dirty... */
1789 if (TransactionIdIsValid(SnapshotDirty->xmin))
1790 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1793 * If tuple is being updated by other transaction then we have
1794 * to wait for its commit/abort.
1796 if (TransactionIdIsValid(xwait))
1798 ReleaseBuffer(buffer);
1799 XactLockTableWait(xwait);
1804 * We got tuple - now copy it for use by recheck query.
1806 copyTuple = heap_copytuple(&tuple);
1807 ReleaseBuffer(buffer);
1812 * Oops! Invalid tuple. Have to check is it updated or deleted.
1813 * Note that it's possible to get invalid SnapshotDirty->tid if
1814 * tuple updated by this transaction. Have we to check this ?
1816 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1817 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1819 /* updated, so look at the updated copy */
1820 tuple.t_self = SnapshotDirty->tid;
1825 * Deleted or updated by this transaction; forget it.
1831 * For UPDATE/DELETE we have to return tid of actual row we're
1834 *tid = tuple.t_self;
1837 * Need to run a recheck subquery. Find or create a PQ stack entry.
1839 epq = estate->es_evalPlanQual;
1842 if (epq != NULL && epq->rti == 0)
1844 /* Top PQ stack entry is idle, so re-use it */
1845 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
1851 * If this is request for another RTE - Ra, - then we have to check
1852 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1853 * updated again and we have to re-start old execution for Ra and
1854 * forget all what we done after Ra was suspended. Cool? -:))
1856 if (epq != NULL && epq->rti != rti &&
1857 epq->estate->es_evTuple[rti - 1] != NULL)
1861 evalPlanQual *oldepq;
1863 /* stop execution */
1864 EvalPlanQualStop(epq);
1865 /* pop previous PlanQual from the stack */
1867 Assert(oldepq && oldepq->rti != 0);
1868 /* push current PQ to freePQ stack */
1871 estate->es_evalPlanQual = epq;
1872 } while (epq->rti != rti);
1876 * If we are requested for another RTE then we have to suspend
1877 * execution of current PlanQual and start execution for new one.
1879 if (epq == NULL || epq->rti != rti)
1881 /* try to reuse plan used previously */
1882 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1884 if (newepq == NULL) /* first call or freePQ stack is empty */
1886 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
1887 newepq->free = NULL;
1888 newepq->estate = NULL;
1889 newepq->planstate = NULL;
1893 /* recycle previously used PlanQual */
1894 Assert(newepq->estate == NULL);
1897 /* push current PQ to the stack */
1900 estate->es_evalPlanQual = epq;
1905 Assert(epq->rti == rti);
1908 * Ok - we're requested for the same RTE. Unfortunately we still have
1909 * to end and restart execution of the plan, because ExecReScan
1910 * wouldn't ensure that upper plan nodes would reset themselves. We
1911 * could make that work if insertion of the target tuple were
1912 * integrated with the Param mechanism somehow, so that the upper plan
1913 * nodes know that their children's outputs have changed.
1915 * Note that the stack of free evalPlanQual nodes is quite useless at the
1916 * moment, since it only saves us from pallocing/releasing the
1917 * evalPlanQual nodes themselves. But it will be useful once we
1918 * implement ReScan instead of end/restart for re-using PlanQual
1923 /* stop execution */
1924 EvalPlanQualStop(epq);
1928 * Initialize new recheck query.
1930 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
1931 * instead copy down changeable state from the top plan (including
1932 * es_result_relation_info, es_junkFilter) and reset locally
1933 * changeable state in the epq (including es_param_exec_vals,
1936 EvalPlanQualStart(epq, estate, epq->next);
1939 * free old RTE' tuple, if any, and store target tuple where
1940 * relation's scan node will see it
1942 epqstate = epq->estate;
1943 if (epqstate->es_evTuple[rti - 1] != NULL)
1944 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1945 epqstate->es_evTuple[rti - 1] = copyTuple;
1947 return EvalPlanQualNext(estate);
1950 static TupleTableSlot *
1951 EvalPlanQualNext(EState *estate)
1953 evalPlanQual *epq = estate->es_evalPlanQual;
1954 MemoryContext oldcontext;
1955 TupleTableSlot *slot;
1957 Assert(epq->rti != 0);
1960 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
1961 slot = ExecProcNode(epq->planstate);
1962 MemoryContextSwitchTo(oldcontext);
1965 * No more tuples for this PQ. Continue previous one.
1967 if (TupIsNull(slot))
1969 evalPlanQual *oldepq;
1971 /* stop execution */
1972 EvalPlanQualStop(epq);
1973 /* pop old PQ from the stack */
1977 /* this is the first (oldest) PQ - mark as free */
1979 estate->es_useEvalPlan = false;
1980 /* and continue Query execution */
1983 Assert(oldepq->rti != 0);
1984 /* push current PQ to freePQ stack */
1987 estate->es_evalPlanQual = epq;
1995 EndEvalPlanQual(EState *estate)
1997 evalPlanQual *epq = estate->es_evalPlanQual;
1999 if (epq->rti == 0) /* plans already shutdowned */
2001 Assert(epq->next == NULL);
2007 evalPlanQual *oldepq;
2009 /* stop execution */
2010 EvalPlanQualStop(epq);
2011 /* pop old PQ from the stack */
2015 /* this is the first (oldest) PQ - mark as free */
2017 estate->es_useEvalPlan = false;
2020 Assert(oldepq->rti != 0);
2021 /* push current PQ to freePQ stack */
2024 estate->es_evalPlanQual = epq;
2029 * Start execution of one level of PlanQual.
2031 * This is a cut-down version of ExecutorStart(): we copy some state from
2032 * the top-level estate rather than initializing it fresh.
2035 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2039 MemoryContext oldcontext;
2041 rtsize = length(estate->es_range_table);
2043 epq->estate = epqstate = CreateExecutorState();
2045 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2048 * The epqstates share the top query's copy of unchanging state such
2049 * as the snapshot, rangetable, result-rel info, and external Param
2050 * info. They need their own copies of local state, including a tuple
2051 * table, es_param_exec_vals, etc.
2053 epqstate->es_direction = ForwardScanDirection;
2054 epqstate->es_snapshot = estate->es_snapshot;
2055 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2056 epqstate->es_range_table = estate->es_range_table;
2057 epqstate->es_result_relations = estate->es_result_relations;
2058 epqstate->es_num_result_relations = estate->es_num_result_relations;
2059 epqstate->es_result_relation_info = estate->es_result_relation_info;
2060 epqstate->es_junkFilter = estate->es_junkFilter;
2061 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2062 epqstate->es_param_list_info = estate->es_param_list_info;
2063 if (estate->es_topPlan->nParamExec > 0)
2064 epqstate->es_param_exec_vals = (ParamExecData *)
2065 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2066 epqstate->es_rowMark = estate->es_rowMark;
2067 epqstate->es_instrument = estate->es_instrument;
2068 epqstate->es_force_oids = estate->es_force_oids;
2069 epqstate->es_topPlan = estate->es_topPlan;
2072 * Each epqstate must have its own es_evTupleNull state, but all the
2073 * stack entries share es_evTuple state. This allows sub-rechecks to
2074 * inherit the value being examined by an outer recheck.
2076 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2077 if (priorepq == NULL)
2078 /* first PQ stack entry */
2079 epqstate->es_evTuple = (HeapTuple *)
2080 palloc0(rtsize * sizeof(HeapTuple));
2082 /* later stack entries share the same storage */
2083 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2085 epqstate->es_tupleTable =
2086 ExecCreateTupleTable(estate->es_tupleTable->size);
2088 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
2090 MemoryContextSwitchTo(oldcontext);
2094 * End execution of one level of PlanQual.
2096 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2097 * of the normal cleanup, but *not* close result relations (which we are
2098 * just sharing from the outer query).
2101 EvalPlanQualStop(evalPlanQual *epq)
2103 EState *epqstate = epq->estate;
2104 MemoryContext oldcontext;
2106 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2108 ExecEndNode(epq->planstate);
2110 ExecDropTupleTable(epqstate->es_tupleTable, true);
2111 epqstate->es_tupleTable = NULL;
2113 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2115 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2116 epqstate->es_evTuple[epq->rti - 1] = NULL;
2119 MemoryContextSwitchTo(oldcontext);
2121 FreeExecutorState(epqstate);
2124 epq->planstate = NULL;