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.207 2003/05/06 00:20:31 tgl Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "catalog/heap.h"
37 #include "catalog/namespace.h"
38 #include "commands/tablecmds.h"
39 #include "commands/trigger.h"
40 #include "executor/execdebug.h"
41 #include "executor/execdefs.h"
42 #include "miscadmin.h"
43 #include "optimizer/var.h"
44 #include "parser/parsetree.h"
45 #include "utils/acl.h"
46 #include "utils/lsyscache.h"
49 typedef struct execRowMark
56 typedef struct evalPlanQual
61 struct evalPlanQual *next; /* stack of active PlanQual plans */
62 struct evalPlanQual *free; /* list of free PlanQual plans */
65 /* decls for local routines only used within this module */
66 static void InitPlan(QueryDesc *queryDesc, bool explainOnly);
67 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
68 Index resultRelationIndex,
71 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
74 ScanDirection direction,
75 DestReceiver *destfunc);
76 static void ExecSelect(TupleTableSlot *slot,
77 DestReceiver *destfunc,
79 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
81 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
83 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
85 static TupleTableSlot *EvalPlanQualNext(EState *estate);
86 static void EndEvalPlanQual(EState *estate);
87 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
88 static void ExecCheckXactReadOnly(Query *parsetree, CmdType operation);
89 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
90 evalPlanQual *priorepq);
91 static void EvalPlanQualStop(evalPlanQual *epq);
93 /* end of local decls */
96 /* ----------------------------------------------------------------
99 * This routine must be called at the beginning of any execution of any
102 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
103 * clear why we bother to separate the two functions, but...). The tupDesc
104 * field of the QueryDesc is filled in to describe the tuples that will be
105 * returned, and the internal fields (estate and planstate) are set up.
107 * If explainOnly is true, we are not actually intending to run the plan,
108 * only to set up for EXPLAIN; so skip unwanted side-effects.
110 * NB: the CurrentMemoryContext when this is called will become the parent
111 * of the per-query context used for this Executor invocation.
112 * ----------------------------------------------------------------
115 ExecutorStart(QueryDesc *queryDesc, bool explainOnly)
118 MemoryContext oldcontext;
120 /* sanity checks: queryDesc must not be started already */
121 Assert(queryDesc != NULL);
122 Assert(queryDesc->estate == NULL);
125 * If the transaction is read-only, we need to check if any writes
126 * are planned to non-temporary tables.
129 ExecCheckXactReadOnly(queryDesc->parsetree, queryDesc->operation);
132 * Build EState, switch into per-query memory context for startup.
134 estate = CreateExecutorState();
135 queryDesc->estate = estate;
137 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
140 * Fill in parameters, if any, from queryDesc
142 estate->es_param_list_info = queryDesc->params;
144 if (queryDesc->plantree->nParamExec > 0)
145 estate->es_param_exec_vals = (ParamExecData *)
146 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
148 estate->es_instrument = queryDesc->doInstrument;
151 * Make our own private copy of the current query snapshot data.
153 * This "freezes" our idea of which tuples are good and which are not for
154 * the life of this query, even if it outlives the current command and
157 estate->es_snapshot = CopyQuerySnapshot();
160 * Initialize the plan state tree
162 InitPlan(queryDesc, explainOnly);
164 MemoryContextSwitchTo(oldcontext);
167 /* ----------------------------------------------------------------
170 * This is the main routine of the executor module. It accepts
171 * the query descriptor from the traffic cop and executes the
174 * ExecutorStart must have been called already.
176 * If direction is NoMovementScanDirection then nothing is done
177 * except to start up/shut down the destination. Otherwise,
178 * we retrieve up to 'count' tuples in the specified direction.
180 * Note: count = 0 is interpreted as no portal limit, i.e., run to
183 * ----------------------------------------------------------------
186 ExecutorRun(QueryDesc *queryDesc,
187 ScanDirection direction, long count)
192 DestReceiver *destfunc;
193 TupleTableSlot *result;
194 MemoryContext oldcontext;
197 Assert(queryDesc != NULL);
199 estate = queryDesc->estate;
201 Assert(estate != NULL);
204 * Switch into per-query memory context
206 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
209 * extract information from the query descriptor and the query
212 operation = queryDesc->operation;
213 dest = queryDesc->dest;
216 * startup tuple receiver
218 estate->es_processed = 0;
219 estate->es_lastoid = InvalidOid;
221 destfunc = DestToFunction(dest);
222 (*destfunc->setup) (destfunc, operation,
223 queryDesc->portalName,
225 queryDesc->planstate->plan->targetlist);
230 if (direction == NoMovementScanDirection)
233 result = ExecutePlan(estate,
234 queryDesc->planstate,
243 (*destfunc->cleanup) (destfunc);
245 MemoryContextSwitchTo(oldcontext);
250 /* ----------------------------------------------------------------
253 * This routine must be called at the end of execution of any
255 * ----------------------------------------------------------------
258 ExecutorEnd(QueryDesc *queryDesc)
261 MemoryContext oldcontext;
264 Assert(queryDesc != NULL);
266 estate = queryDesc->estate;
268 Assert(estate != NULL);
271 * Switch into per-query memory context to run ExecEndPlan
273 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
275 ExecEndPlan(queryDesc->planstate, estate);
278 * Must switch out of context before destroying it
280 MemoryContextSwitchTo(oldcontext);
283 * Release EState and per-query memory context. This should release
284 * everything the executor has allocated.
286 FreeExecutorState(estate);
288 /* Reset queryDesc fields that no longer point to anything */
289 queryDesc->tupDesc = NULL;
290 queryDesc->estate = NULL;
291 queryDesc->planstate = NULL;
294 /* ----------------------------------------------------------------
297 * This routine may be called on an open queryDesc to rewind it
299 * ----------------------------------------------------------------
302 ExecutorRewind(QueryDesc *queryDesc)
305 MemoryContext oldcontext;
308 Assert(queryDesc != NULL);
310 estate = queryDesc->estate;
312 Assert(estate != NULL);
314 /* It's probably not sensible to rescan updating queries */
315 Assert(queryDesc->operation == CMD_SELECT);
318 * Switch into per-query memory context
320 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
325 ExecReScan(queryDesc->planstate, NULL);
327 MemoryContextSwitchTo(oldcontext);
333 * Check access permissions for all relations listed in a range table.
336 ExecCheckRTPerms(List *rangeTable, CmdType operation)
340 foreach(lp, rangeTable)
342 RangeTblEntry *rte = lfirst(lp);
344 ExecCheckRTEPerms(rte, operation);
350 * Check access permissions for a single RTE.
353 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
357 AclResult aclcheck_result;
360 * If it's a subquery, recursively examine its rangetable.
362 if (rte->rtekind == RTE_SUBQUERY)
364 ExecCheckRTPerms(rte->subquery->rtable, operation);
369 * Otherwise, only plain-relation RTEs need to be checked here.
370 * Function RTEs are checked by init_fcache when the function is prepared
371 * for execution. Join and special RTEs need no checks.
373 if (rte->rtekind != RTE_RELATION)
379 * userid to check as: current user unless we have a setuid
382 * Note: GetUserId() is presently fast enough that there's no harm in
383 * calling it separately for each RTE. If that stops being true, we
384 * could call it once in ExecCheckRTPerms and pass the userid down
385 * from there. But for now, no need for the extra clutter.
387 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
389 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
391 if (rte->checkForRead)
393 aclcheck_result = CHECK(ACL_SELECT);
394 if (aclcheck_result != ACLCHECK_OK)
395 aclcheck_error(aclcheck_result, get_rel_name(relOid));
398 if (rte->checkForWrite)
401 * Note: write access in a SELECT context means SELECT FOR UPDATE.
402 * Right now we don't distinguish that from true update as far as
403 * permissions checks are concerned.
408 aclcheck_result = CHECK(ACL_INSERT);
412 aclcheck_result = CHECK(ACL_UPDATE);
415 aclcheck_result = CHECK(ACL_DELETE);
418 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
420 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
423 if (aclcheck_result != ACLCHECK_OK)
424 aclcheck_error(aclcheck_result, get_rel_name(relOid));
429 ExecCheckXactReadOnly(Query *parsetree, CmdType operation)
434 /* CREATE TABLE AS or SELECT INTO */
435 if (operation == CMD_SELECT && parsetree->into != NULL)
438 if (operation == CMD_DELETE || operation == CMD_INSERT
439 || operation == CMD_UPDATE)
443 foreach(lp, parsetree->rtable)
445 RangeTblEntry *rte = lfirst(lp);
447 if (rte->rtekind != RTE_RELATION)
450 if (!rte->checkForWrite)
453 if (isTempNamespace(get_rel_namespace(rte->relid)))
463 elog(ERROR, "transaction is read-only");
467 /* ----------------------------------------------------------------
470 * Initializes the query plan: open files, allocate storage
471 * and start up the rule manager
472 * ----------------------------------------------------------------
475 InitPlan(QueryDesc *queryDesc, bool explainOnly)
477 CmdType operation = queryDesc->operation;
478 Query *parseTree = queryDesc->parsetree;
479 Plan *plan = queryDesc->plantree;
480 EState *estate = queryDesc->estate;
481 PlanState *planstate;
483 Relation intoRelationDesc;
488 * Do permissions checks. It's sufficient to examine the query's
489 * top rangetable here --- subplan RTEs will be checked during
492 ExecCheckRTPerms(parseTree->rtable, operation);
495 * get information from query descriptor
497 rangeTable = parseTree->rtable;
500 * initialize the node's execution state
502 estate->es_range_table = rangeTable;
505 * if there is a result relation, initialize result relation stuff
507 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
509 List *resultRelations = parseTree->resultRelations;
510 int numResultRelations;
511 ResultRelInfo *resultRelInfos;
513 if (resultRelations != NIL)
516 * Multiple result relations (due to inheritance)
517 * parseTree->resultRelations identifies them all
519 ResultRelInfo *resultRelInfo;
521 numResultRelations = length(resultRelations);
522 resultRelInfos = (ResultRelInfo *)
523 palloc(numResultRelations * sizeof(ResultRelInfo));
524 resultRelInfo = resultRelInfos;
525 while (resultRelations != NIL)
527 initResultRelInfo(resultRelInfo,
528 lfirsti(resultRelations),
532 resultRelations = lnext(resultRelations);
538 * Single result relation identified by
539 * parseTree->resultRelation
541 numResultRelations = 1;
542 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
543 initResultRelInfo(resultRelInfos,
544 parseTree->resultRelation,
549 estate->es_result_relations = resultRelInfos;
550 estate->es_num_result_relations = numResultRelations;
551 /* Initialize to first or only result rel */
552 estate->es_result_relation_info = resultRelInfos;
557 * if no result relation, then set state appropriately
559 estate->es_result_relations = NULL;
560 estate->es_num_result_relations = 0;
561 estate->es_result_relation_info = NULL;
565 * Detect whether we're doing SELECT INTO. If so, set the force_oids
566 * flag appropriately so that the plan tree will be initialized with
567 * the correct tuple descriptors.
569 do_select_into = false;
571 if (operation == CMD_SELECT && parseTree->into != NULL)
573 do_select_into = true;
575 * For now, always create OIDs in SELECT INTO; this is for backwards
576 * compatibility with pre-7.3 behavior. Eventually we might want
577 * to allow the user to choose.
579 estate->es_force_oids = true;
583 * Have to lock relations selected for update
585 estate->es_rowMark = NIL;
586 if (parseTree->rowMarks != NIL)
590 foreach(l, parseTree->rowMarks)
592 Index rti = lfirsti(l);
593 Oid relid = getrelid(rti, rangeTable);
597 relation = heap_open(relid, RowShareLock);
598 erm = (execRowMark *) palloc(sizeof(execRowMark));
599 erm->relation = relation;
601 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rti);
602 estate->es_rowMark = lappend(estate->es_rowMark, erm);
607 * initialize the executor "tuple" table. We need slots for all the
608 * plan nodes, plus possibly output slots for the junkfilter(s). At
609 * this point we aren't sure if we need junkfilters, so just add slots
610 * for them unconditionally.
613 int nSlots = ExecCountSlotsNode(plan);
615 if (parseTree->resultRelations != NIL)
616 nSlots += length(parseTree->resultRelations);
619 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
622 /* mark EvalPlanQual not active */
623 estate->es_topPlan = plan;
624 estate->es_evalPlanQual = NULL;
625 estate->es_evTupleNull = NULL;
626 estate->es_evTuple = NULL;
627 estate->es_useEvalPlan = false;
630 * initialize the private state information for all the nodes in the
631 * query tree. This opens files, allocates storage and leaves us
632 * ready to start processing tuples.
634 planstate = ExecInitNode(plan, estate);
637 * Get the tuple descriptor describing the type of tuples to return.
638 * (this is especially important if we are creating a relation with
641 tupType = ExecGetResultType(planstate);
644 * Initialize the junk filter if needed. SELECT and INSERT queries need a
645 * filter if there are any junk attrs in the tlist. INSERT and SELECT
646 * INTO also need a filter if the top plan node is a scan node that's not
647 * doing projection (else we'll be scribbling on the scan tuple!) UPDATE
648 * and DELETE always need a filter, since there's always a junk 'ctid'
649 * attribute present --- no need to look first.
652 bool junk_filter_needed = false;
659 foreach(tlist, plan->targetlist)
661 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
663 if (tle->resdom->resjunk)
665 junk_filter_needed = true;
669 if (!junk_filter_needed &&
670 (operation == CMD_INSERT || do_select_into))
672 if (IsA(planstate, SeqScanState) ||
673 IsA(planstate, IndexScanState) ||
674 IsA(planstate, TidScanState) ||
675 IsA(planstate, SubqueryScanState) ||
676 IsA(planstate, FunctionScanState))
678 if (planstate->ps_ProjInfo == NULL)
679 junk_filter_needed = true;
685 junk_filter_needed = true;
691 if (junk_filter_needed)
694 * If there are multiple result relations, each one needs its
695 * own junk filter. Note this is only possible for
696 * UPDATE/DELETE, so we can't be fooled by some needing a
697 * filter and some not.
699 if (parseTree->resultRelations != NIL)
701 PlanState **appendplans;
703 ResultRelInfo *resultRelInfo;
706 /* Top plan had better be an Append here. */
707 Assert(IsA(plan, Append));
708 Assert(((Append *) plan)->isTarget);
709 Assert(IsA(planstate, AppendState));
710 appendplans = ((AppendState *) planstate)->appendplans;
711 as_nplans = ((AppendState *) planstate)->as_nplans;
712 Assert(as_nplans == estate->es_num_result_relations);
713 resultRelInfo = estate->es_result_relations;
714 for (i = 0; i < as_nplans; i++)
716 PlanState *subplan = appendplans[i];
719 j = ExecInitJunkFilter(subplan->plan->targetlist,
720 ExecGetResultType(subplan),
721 ExecAllocTableSlot(estate->es_tupleTable));
722 resultRelInfo->ri_junkFilter = j;
727 * Set active junkfilter too; at this point ExecInitAppend
728 * has already selected an active result relation...
730 estate->es_junkFilter =
731 estate->es_result_relation_info->ri_junkFilter;
735 /* Normal case with just one JunkFilter */
738 j = ExecInitJunkFilter(planstate->plan->targetlist,
740 ExecAllocTableSlot(estate->es_tupleTable));
741 estate->es_junkFilter = j;
742 if (estate->es_result_relation_info)
743 estate->es_result_relation_info->ri_junkFilter = j;
745 /* For SELECT, want to return the cleaned tuple type */
746 if (operation == CMD_SELECT)
747 tupType = j->jf_cleanTupType;
751 estate->es_junkFilter = NULL;
755 * If doing SELECT INTO, initialize the "into" relation. We must wait
756 * till now so we have the "clean" result tuple type to create the
759 * If EXPLAIN, skip creating the "into" relation.
761 intoRelationDesc = (Relation) NULL;
763 if (do_select_into && !explainOnly)
772 * find namespace to create in, check permissions
774 intoName = parseTree->into->relname;
775 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
777 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
779 if (aclresult != ACLCHECK_OK)
780 aclcheck_error(aclresult, get_namespace_name(namespaceId));
783 * have to copy tupType to get rid of constraints
785 tupdesc = CreateTupleDescCopy(tupType);
787 intoRelationId = heap_create_with_catalog(intoName,
793 allowSystemTableMods);
795 FreeTupleDesc(tupdesc);
798 * Advance command counter so that the newly-created
799 * relation's catalog tuples will be visible to heap_open.
801 CommandCounterIncrement();
804 * If necessary, create a TOAST table for the into
805 * relation. Note that AlterTableCreateToastTable ends
806 * with CommandCounterIncrement(), so that the TOAST table
807 * will be visible for insertion.
809 AlterTableCreateToastTable(intoRelationId, true);
812 * And open the constructed table for writing.
814 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
817 estate->es_into_relation_descriptor = intoRelationDesc;
819 queryDesc->tupDesc = tupType;
820 queryDesc->planstate = planstate;
824 * Initialize ResultRelInfo data for one result relation
827 initResultRelInfo(ResultRelInfo *resultRelInfo,
828 Index resultRelationIndex,
832 Oid resultRelationOid;
833 Relation resultRelationDesc;
835 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
836 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
838 switch (resultRelationDesc->rd_rel->relkind)
840 case RELKIND_SEQUENCE:
841 elog(ERROR, "You can't change sequence relation %s",
842 RelationGetRelationName(resultRelationDesc));
844 case RELKIND_TOASTVALUE:
845 elog(ERROR, "You can't change toast relation %s",
846 RelationGetRelationName(resultRelationDesc));
849 elog(ERROR, "You can't change view relation %s",
850 RelationGetRelationName(resultRelationDesc));
854 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
855 resultRelInfo->type = T_ResultRelInfo;
856 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
857 resultRelInfo->ri_RelationDesc = resultRelationDesc;
858 resultRelInfo->ri_NumIndices = 0;
859 resultRelInfo->ri_IndexRelationDescs = NULL;
860 resultRelInfo->ri_IndexRelationInfo = NULL;
861 /* make a copy so as not to depend on relcache info not changing... */
862 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
863 resultRelInfo->ri_TrigFunctions = NULL;
864 resultRelInfo->ri_ConstraintExprs = NULL;
865 resultRelInfo->ri_junkFilter = NULL;
868 * If there are indices on the result relation, open them and save
869 * descriptors in the result relation info, so that we can add new
870 * index entries for the tuples we add/update. We need not do this
871 * for a DELETE, however, since deletion doesn't affect indexes.
873 if (resultRelationDesc->rd_rel->relhasindex &&
874 operation != CMD_DELETE)
875 ExecOpenIndices(resultRelInfo);
878 /* ----------------------------------------------------------------
881 * Cleans up the query plan -- closes files and frees up storage
883 * NOTE: we are no longer very worried about freeing storage per se
884 * in this code; FreeExecutorState should be guaranteed to release all
885 * memory that needs to be released. What we are worried about doing
886 * is closing relations and dropping buffer pins. Thus, for example,
887 * tuple tables must be cleared or dropped to ensure pins are released.
888 * ----------------------------------------------------------------
891 ExecEndPlan(PlanState *planstate, EState *estate)
893 ResultRelInfo *resultRelInfo;
898 * shut down any PlanQual processing we were doing
900 if (estate->es_evalPlanQual != NULL)
901 EndEvalPlanQual(estate);
904 * shut down the node-type-specific query processing
906 ExecEndNode(planstate);
909 * destroy the executor "tuple" table.
911 ExecDropTupleTable(estate->es_tupleTable, true);
912 estate->es_tupleTable = NULL;
915 * close the result relation(s) if any, but hold locks until xact
918 resultRelInfo = estate->es_result_relations;
919 for (i = estate->es_num_result_relations; i > 0; i--)
921 /* Close indices and then the relation itself */
922 ExecCloseIndices(resultRelInfo);
923 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
928 * close the "into" relation if necessary, again keeping lock
930 if (estate->es_into_relation_descriptor != NULL)
931 heap_close(estate->es_into_relation_descriptor, NoLock);
934 * close any relations selected FOR UPDATE, again keeping locks
936 foreach(l, estate->es_rowMark)
938 execRowMark *erm = lfirst(l);
940 heap_close(erm->relation, NoLock);
944 /* ----------------------------------------------------------------
947 * processes the query plan to retrieve 'numberTuples' tuples in the
948 * direction specified.
950 * Retrieves all tuples if numberTuples is 0
952 * result is either a slot containing the last tuple in the case
953 * of a SELECT or NULL otherwise.
955 * Note: the ctid attribute is a 'junk' attribute that is removed before the
957 * ----------------------------------------------------------------
959 static TupleTableSlot *
960 ExecutePlan(EState *estate,
961 PlanState *planstate,
964 ScanDirection direction,
965 DestReceiver *destfunc)
967 JunkFilter *junkfilter;
968 TupleTableSlot *slot;
969 ItemPointer tupleid = NULL;
970 ItemPointerData tuple_ctid;
971 long current_tuple_count;
972 TupleTableSlot *result;
975 * initialize local variables
978 current_tuple_count = 0;
984 estate->es_direction = direction;
987 * Process BEFORE EACH STATEMENT triggers
992 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
995 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
998 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1006 * Loop until we've processed the proper number of tuples from the
1012 /* Reset the per-output-tuple exprcontext */
1013 ResetPerTupleExprContext(estate);
1016 * Execute the plan and obtain a tuple
1019 if (estate->es_useEvalPlan)
1021 slot = EvalPlanQualNext(estate);
1022 if (TupIsNull(slot))
1023 slot = ExecProcNode(planstate);
1026 slot = ExecProcNode(planstate);
1029 * if the tuple is null, then we assume there is nothing more to
1030 * process so we just return null...
1032 if (TupIsNull(slot))
1039 * if we have a junk filter, then project a new tuple with the
1042 * Store this new "clean" tuple in the junkfilter's resultSlot.
1043 * (Formerly, we stored it back over the "dirty" tuple, which is
1044 * WRONG because that tuple slot has the wrong descriptor.)
1046 * Also, extract all the junk information we need.
1048 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
1055 * extract the 'ctid' junk attribute.
1057 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1059 if (!ExecGetJunkAttribute(junkfilter,
1064 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1066 /* shouldn't ever get a null result... */
1068 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1070 tupleid = (ItemPointer) DatumGetPointer(datum);
1071 tuple_ctid = *tupleid; /* make sure we don't free the
1073 tupleid = &tuple_ctid;
1075 else if (estate->es_rowMark != NIL)
1080 foreach(l, estate->es_rowMark)
1082 execRowMark *erm = lfirst(l);
1084 HeapTupleData tuple;
1085 TupleTableSlot *newSlot;
1088 if (!ExecGetJunkAttribute(junkfilter,
1093 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1096 /* shouldn't ever get a null result... */
1098 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1101 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1102 test = heap_mark4update(erm->relation, &tuple, &buffer,
1103 estate->es_snapshot->curcid);
1104 ReleaseBuffer(buffer);
1107 case HeapTupleSelfUpdated:
1108 /* treat it as deleted; do not process */
1111 case HeapTupleMayBeUpdated:
1114 case HeapTupleUpdated:
1115 if (XactIsoLevel == XACT_SERIALIZABLE)
1116 elog(ERROR, "Can't serialize access due to concurrent update");
1117 if (!(ItemPointerEquals(&(tuple.t_self),
1118 (ItemPointer) DatumGetPointer(datum))))
1120 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1121 if (!(TupIsNull(newSlot)))
1124 estate->es_useEvalPlan = true;
1130 * if tuple was deleted or PlanQual failed for
1131 * updated tuple - we must not return this
1137 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1144 * Finally create a new "clean" tuple with all junk attributes
1147 newTuple = ExecRemoveJunk(junkfilter, slot);
1149 slot = ExecStoreTuple(newTuple, /* tuple to store */
1150 junkfilter->jf_resultSlot, /* dest slot */
1151 InvalidBuffer, /* this tuple has no
1153 true); /* tuple should be pfreed */
1157 * now that we have a tuple, do the appropriate thing with it..
1158 * either return it to the user, add it to a relation someplace,
1159 * delete it from a relation, or modify some of its attributes.
1164 ExecSelect(slot, /* slot containing tuple */
1165 destfunc, /* destination's tuple-receiver
1172 ExecInsert(slot, tupleid, estate);
1177 ExecDelete(slot, tupleid, estate);
1182 ExecUpdate(slot, tupleid, estate);
1187 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1193 * check our tuple count.. if we've processed the proper number
1194 * then quit, else loop again and process more tuples. Zero
1195 * numberTuples means no limit.
1197 current_tuple_count++;
1198 if (numberTuples && numberTuples == current_tuple_count)
1203 * Process AFTER EACH STATEMENT triggers
1208 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1211 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1214 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1222 * here, result is either a slot containing a tuple in the case of a
1223 * SELECT or NULL otherwise.
1228 /* ----------------------------------------------------------------
1231 * SELECTs are easy.. we just pass the tuple to the appropriate
1232 * print function. The only complexity is when we do a
1233 * "SELECT INTO", in which case we insert the tuple into
1234 * the appropriate relation (note: this is a newly created relation
1235 * so we don't need to worry about indices or locks.)
1236 * ----------------------------------------------------------------
1239 ExecSelect(TupleTableSlot *slot,
1240 DestReceiver *destfunc,
1247 * get the heap tuple out of the tuple table slot
1250 attrtype = slot->ttc_tupleDescriptor;
1253 * insert the tuple into the "into relation"
1255 if (estate->es_into_relation_descriptor != NULL)
1257 heap_insert(estate->es_into_relation_descriptor, tuple,
1258 estate->es_snapshot->curcid);
1263 * send the tuple to the front end (or the screen)
1265 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1267 (estate->es_processed)++;
1270 /* ----------------------------------------------------------------
1273 * INSERTs are trickier.. we have to insert the tuple into
1274 * the base relation and insert appropriate tuples into the
1276 * ----------------------------------------------------------------
1279 ExecInsert(TupleTableSlot *slot,
1280 ItemPointer tupleid,
1284 ResultRelInfo *resultRelInfo;
1285 Relation resultRelationDesc;
1290 * get the heap tuple out of the tuple table slot
1295 * get information on the (current) result relation
1297 resultRelInfo = estate->es_result_relation_info;
1298 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1300 /* BEFORE ROW INSERT Triggers */
1301 if (resultRelInfo->ri_TrigDesc &&
1302 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1306 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1308 if (newtuple == NULL) /* "do nothing" */
1311 if (newtuple != tuple) /* modified by Trigger(s) */
1314 * Insert modified tuple into tuple table slot, replacing the
1315 * original. We assume that it was allocated in per-tuple
1316 * memory context, and therefore will go away by itself. The
1317 * tuple table slot should not try to clear it.
1319 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1325 * Check the constraints of the tuple
1327 if (resultRelationDesc->rd_att->constr)
1328 ExecConstraints("ExecInsert", resultRelInfo, slot, estate);
1333 newId = heap_insert(resultRelationDesc, tuple,
1334 estate->es_snapshot->curcid);
1337 (estate->es_processed)++;
1338 estate->es_lastoid = newId;
1339 setLastTid(&(tuple->t_self));
1344 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1345 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1348 numIndices = resultRelInfo->ri_NumIndices;
1350 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1352 /* AFTER ROW INSERT Triggers */
1353 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1356 /* ----------------------------------------------------------------
1359 * DELETE is like UPDATE, we delete the tuple and its
1361 * ----------------------------------------------------------------
1364 ExecDelete(TupleTableSlot *slot,
1365 ItemPointer tupleid,
1368 ResultRelInfo *resultRelInfo;
1369 Relation resultRelationDesc;
1370 ItemPointerData ctid;
1374 * get information on the (current) result relation
1376 resultRelInfo = estate->es_result_relation_info;
1377 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1379 /* BEFORE ROW DELETE Triggers */
1380 if (resultRelInfo->ri_TrigDesc &&
1381 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1385 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1386 estate->es_snapshot->curcid);
1388 if (!dodelete) /* "do nothing" */
1396 result = heap_delete(resultRelationDesc, tupleid,
1398 estate->es_snapshot->curcid);
1401 case HeapTupleSelfUpdated:
1402 /* already deleted by self; nothing to do */
1405 case HeapTupleMayBeUpdated:
1408 case HeapTupleUpdated:
1409 if (XactIsoLevel == XACT_SERIALIZABLE)
1410 elog(ERROR, "Can't serialize access due to concurrent update");
1411 else if (!(ItemPointerEquals(tupleid, &ctid)))
1413 TupleTableSlot *epqslot = EvalPlanQual(estate,
1414 resultRelInfo->ri_RangeTableIndex, &ctid);
1416 if (!TupIsNull(epqslot))
1422 /* tuple already deleted; nothing to do */
1426 elog(ERROR, "Unknown status %u from heap_delete", result);
1431 (estate->es_processed)++;
1434 * Note: Normally one would think that we have to delete index tuples
1435 * associated with the heap tuple now..
1437 * ... but in POSTGRES, we have no need to do this because the vacuum
1438 * daemon automatically opens an index scan and deletes index tuples
1439 * when it finds deleted heap tuples. -cim 9/27/89
1442 /* AFTER ROW DELETE Triggers */
1443 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1446 /* ----------------------------------------------------------------
1449 * note: we can't run UPDATE queries with transactions
1450 * off because UPDATEs are actually INSERTs and our
1451 * scan will mistakenly loop forever, updating the tuple
1452 * it just inserted.. This should be fixed but until it
1453 * is, we don't want to get stuck in an infinite loop
1454 * which corrupts your database..
1455 * ----------------------------------------------------------------
1458 ExecUpdate(TupleTableSlot *slot,
1459 ItemPointer tupleid,
1463 ResultRelInfo *resultRelInfo;
1464 Relation resultRelationDesc;
1465 ItemPointerData ctid;
1470 * abort the operation if not running transactions
1472 if (IsBootstrapProcessingMode())
1474 elog(WARNING, "ExecUpdate: UPDATE can't run without transactions");
1479 * get the heap tuple out of the tuple table slot
1484 * get information on the (current) result relation
1486 resultRelInfo = estate->es_result_relation_info;
1487 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1489 /* BEFORE ROW UPDATE Triggers */
1490 if (resultRelInfo->ri_TrigDesc &&
1491 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1495 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1497 estate->es_snapshot->curcid);
1499 if (newtuple == NULL) /* "do nothing" */
1502 if (newtuple != tuple) /* modified by Trigger(s) */
1505 * Insert modified tuple into tuple table slot, replacing the
1506 * original. We assume that it was allocated in per-tuple
1507 * memory context, and therefore will go away by itself. The
1508 * tuple table slot should not try to clear it.
1510 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1516 * Check the constraints of the tuple
1518 * If we generate a new candidate tuple after EvalPlanQual testing, we
1519 * must loop back here and recheck constraints. (We don't need to
1520 * redo triggers, however. If there are any BEFORE triggers then
1521 * trigger.c will have done mark4update to lock the correct tuple, so
1522 * there's no need to do them again.)
1525 if (resultRelationDesc->rd_att->constr)
1526 ExecConstraints("ExecUpdate", resultRelInfo, slot, estate);
1529 * replace the heap tuple
1531 result = heap_update(resultRelationDesc, tupleid, tuple,
1533 estate->es_snapshot->curcid);
1536 case HeapTupleSelfUpdated:
1537 /* already deleted by self; nothing to do */
1540 case HeapTupleMayBeUpdated:
1543 case HeapTupleUpdated:
1544 if (XactIsoLevel == XACT_SERIALIZABLE)
1545 elog(ERROR, "Can't serialize access due to concurrent update");
1546 else if (!(ItemPointerEquals(tupleid, &ctid)))
1548 TupleTableSlot *epqslot = EvalPlanQual(estate,
1549 resultRelInfo->ri_RangeTableIndex, &ctid);
1551 if (!TupIsNull(epqslot))
1554 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1555 slot = ExecStoreTuple(tuple,
1556 estate->es_junkFilter->jf_resultSlot,
1557 InvalidBuffer, true);
1561 /* tuple already deleted; nothing to do */
1565 elog(ERROR, "Unknown status %u from heap_update", result);
1570 (estate->es_processed)++;
1573 * Note: instead of having to update the old index tuples associated
1574 * with the heap tuple, all we do is form and insert new index tuples.
1575 * This is because UPDATEs are actually DELETEs and INSERTs and index
1576 * tuple deletion is done automagically by the vacuum daemon. All we
1577 * do is insert new index tuples. -cim 9/27/89
1583 * heap_update updates a tuple in the base relation by invalidating it
1584 * and then inserting a new tuple to the relation. As a side effect,
1585 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1586 * field. So we now insert index tuples using the new tupleid stored
1590 numIndices = resultRelInfo->ri_NumIndices;
1592 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1594 /* AFTER ROW UPDATE Triggers */
1595 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1599 ExecRelCheck(ResultRelInfo *resultRelInfo,
1600 TupleTableSlot *slot, EState *estate)
1602 Relation rel = resultRelInfo->ri_RelationDesc;
1603 int ncheck = rel->rd_att->constr->num_check;
1604 ConstrCheck *check = rel->rd_att->constr->check;
1605 ExprContext *econtext;
1606 MemoryContext oldContext;
1611 * If first time through for this result relation, build expression
1612 * nodetrees for rel's constraint expressions. Keep them in the
1613 * per-query memory context so they'll survive throughout the query.
1615 if (resultRelInfo->ri_ConstraintExprs == NULL)
1617 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1618 resultRelInfo->ri_ConstraintExprs =
1619 (List **) palloc(ncheck * sizeof(List *));
1620 for (i = 0; i < ncheck; i++)
1622 qual = (List *) stringToNode(check[i].ccbin);
1623 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1624 ExecPrepareExpr((Expr *) qual, estate);
1626 MemoryContextSwitchTo(oldContext);
1630 * We will use the EState's per-tuple context for evaluating
1631 * constraint expressions (creating it if it's not already there).
1633 econtext = GetPerTupleExprContext(estate);
1635 /* Arrange for econtext's scan tuple to be the tuple under test */
1636 econtext->ecxt_scantuple = slot;
1638 /* And evaluate the constraints */
1639 for (i = 0; i < ncheck; i++)
1641 qual = resultRelInfo->ri_ConstraintExprs[i];
1644 * NOTE: SQL92 specifies that a NULL result from a constraint
1645 * expression is not to be treated as a failure. Therefore, tell
1646 * ExecQual to return TRUE for NULL.
1648 if (!ExecQual(qual, econtext, true))
1649 return check[i].ccname;
1652 /* NULL result means no error */
1653 return (char *) NULL;
1657 ExecConstraints(const char *caller, ResultRelInfo *resultRelInfo,
1658 TupleTableSlot *slot, EState *estate)
1660 Relation rel = resultRelInfo->ri_RelationDesc;
1661 HeapTuple tuple = slot->val;
1662 TupleConstr *constr = rel->rd_att->constr;
1666 if (constr->has_not_null)
1668 int natts = rel->rd_att->natts;
1671 for (attrChk = 1; attrChk <= natts; attrChk++)
1673 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1674 heap_attisnull(tuple, attrChk))
1675 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1676 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1680 if (constr->num_check > 0)
1684 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1685 elog(ERROR, "%s: rejected due to CHECK constraint \"%s\" on \"%s\"",
1686 caller, failed, RelationGetRelationName(rel));
1691 * Check a modified tuple to see if we want to process its updated version
1692 * under READ COMMITTED rules.
1694 * See backend/executor/README for some info about how this works.
1697 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1702 HeapTupleData tuple;
1703 HeapTuple copyTuple = NULL;
1709 * find relation containing target tuple
1711 if (estate->es_result_relation_info != NULL &&
1712 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1713 relation = estate->es_result_relation_info->ri_RelationDesc;
1719 foreach(l, estate->es_rowMark)
1721 if (((execRowMark *) lfirst(l))->rti == rti)
1723 relation = ((execRowMark *) lfirst(l))->relation;
1727 if (relation == NULL)
1728 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1734 * Loop here to deal with updated or busy tuples
1736 tuple.t_self = *tid;
1741 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1743 TransactionId xwait = SnapshotDirty->xmax;
1745 if (TransactionIdIsValid(SnapshotDirty->xmin))
1746 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1749 * If tuple is being updated by other transaction then we have
1750 * to wait for its commit/abort.
1752 if (TransactionIdIsValid(xwait))
1754 ReleaseBuffer(buffer);
1755 XactLockTableWait(xwait);
1760 * We got tuple - now copy it for use by recheck query.
1762 copyTuple = heap_copytuple(&tuple);
1763 ReleaseBuffer(buffer);
1768 * Oops! Invalid tuple. Have to check is it updated or deleted.
1769 * Note that it's possible to get invalid SnapshotDirty->tid if
1770 * tuple updated by this transaction. Have we to check this ?
1772 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1773 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1775 /* updated, so look at the updated copy */
1776 tuple.t_self = SnapshotDirty->tid;
1781 * Deleted or updated by this transaction; forget it.
1787 * For UPDATE/DELETE we have to return tid of actual row we're
1790 *tid = tuple.t_self;
1793 * Need to run a recheck subquery. Find or create a PQ stack entry.
1795 epq = estate->es_evalPlanQual;
1798 if (epq != NULL && epq->rti == 0)
1800 /* Top PQ stack entry is idle, so re-use it */
1801 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
1807 * If this is request for another RTE - Ra, - then we have to check
1808 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1809 * updated again and we have to re-start old execution for Ra and
1810 * forget all what we done after Ra was suspended. Cool? -:))
1812 if (epq != NULL && epq->rti != rti &&
1813 epq->estate->es_evTuple[rti - 1] != NULL)
1817 evalPlanQual *oldepq;
1819 /* stop execution */
1820 EvalPlanQualStop(epq);
1821 /* pop previous PlanQual from the stack */
1823 Assert(oldepq && oldepq->rti != 0);
1824 /* push current PQ to freePQ stack */
1827 estate->es_evalPlanQual = epq;
1828 } while (epq->rti != rti);
1832 * If we are requested for another RTE then we have to suspend
1833 * execution of current PlanQual and start execution for new one.
1835 if (epq == NULL || epq->rti != rti)
1837 /* try to reuse plan used previously */
1838 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1840 if (newepq == NULL) /* first call or freePQ stack is empty */
1842 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
1843 newepq->free = NULL;
1844 newepq->estate = NULL;
1845 newepq->planstate = NULL;
1849 /* recycle previously used PlanQual */
1850 Assert(newepq->estate == NULL);
1853 /* push current PQ to the stack */
1856 estate->es_evalPlanQual = epq;
1861 Assert(epq->rti == rti);
1864 * Ok - we're requested for the same RTE. Unfortunately we still have
1865 * to end and restart execution of the plan, because ExecReScan
1866 * wouldn't ensure that upper plan nodes would reset themselves. We
1867 * could make that work if insertion of the target tuple were
1868 * integrated with the Param mechanism somehow, so that the upper plan
1869 * nodes know that their children's outputs have changed.
1871 * Note that the stack of free evalPlanQual nodes is quite useless at
1872 * the moment, since it only saves us from pallocing/releasing the
1873 * evalPlanQual nodes themselves. But it will be useful once we
1874 * implement ReScan instead of end/restart for re-using PlanQual nodes.
1878 /* stop execution */
1879 EvalPlanQualStop(epq);
1883 * Initialize new recheck query.
1885 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need
1886 * to instead copy down changeable state from the top plan (including
1887 * es_result_relation_info, es_junkFilter) and reset locally changeable
1888 * state in the epq (including es_param_exec_vals, es_evTupleNull).
1890 EvalPlanQualStart(epq, estate, epq->next);
1893 * free old RTE' tuple, if any, and store target tuple where
1894 * relation's scan node will see it
1896 epqstate = epq->estate;
1897 if (epqstate->es_evTuple[rti - 1] != NULL)
1898 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1899 epqstate->es_evTuple[rti - 1] = copyTuple;
1901 return EvalPlanQualNext(estate);
1904 static TupleTableSlot *
1905 EvalPlanQualNext(EState *estate)
1907 evalPlanQual *epq = estate->es_evalPlanQual;
1908 MemoryContext oldcontext;
1909 TupleTableSlot *slot;
1911 Assert(epq->rti != 0);
1914 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
1915 slot = ExecProcNode(epq->planstate);
1916 MemoryContextSwitchTo(oldcontext);
1919 * No more tuples for this PQ. Continue previous one.
1921 if (TupIsNull(slot))
1923 evalPlanQual *oldepq;
1925 /* stop execution */
1926 EvalPlanQualStop(epq);
1927 /* pop old PQ from the stack */
1931 /* this is the first (oldest) PQ - mark as free */
1933 estate->es_useEvalPlan = false;
1934 /* and continue Query execution */
1937 Assert(oldepq->rti != 0);
1938 /* push current PQ to freePQ stack */
1941 estate->es_evalPlanQual = epq;
1949 EndEvalPlanQual(EState *estate)
1951 evalPlanQual *epq = estate->es_evalPlanQual;
1953 if (epq->rti == 0) /* plans already shutdowned */
1955 Assert(epq->next == NULL);
1961 evalPlanQual *oldepq;
1963 /* stop execution */
1964 EvalPlanQualStop(epq);
1965 /* pop old PQ from the stack */
1969 /* this is the first (oldest) PQ - mark as free */
1971 estate->es_useEvalPlan = false;
1974 Assert(oldepq->rti != 0);
1975 /* push current PQ to freePQ stack */
1978 estate->es_evalPlanQual = epq;
1983 * Start execution of one level of PlanQual.
1985 * This is a cut-down version of ExecutorStart(): we copy some state from
1986 * the top-level estate rather than initializing it fresh.
1989 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
1993 MemoryContext oldcontext;
1995 rtsize = length(estate->es_range_table);
1997 epq->estate = epqstate = CreateExecutorState();
1999 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2002 * The epqstates share the top query's copy of unchanging state such
2003 * as the snapshot, rangetable, result-rel info, and external Param info.
2004 * They need their own copies of local state, including a tuple table,
2005 * es_param_exec_vals, etc.
2007 epqstate->es_direction = ForwardScanDirection;
2008 epqstate->es_snapshot = estate->es_snapshot;
2009 epqstate->es_range_table = estate->es_range_table;
2010 epqstate->es_result_relations = estate->es_result_relations;
2011 epqstate->es_num_result_relations = estate->es_num_result_relations;
2012 epqstate->es_result_relation_info = estate->es_result_relation_info;
2013 epqstate->es_junkFilter = estate->es_junkFilter;
2014 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2015 epqstate->es_param_list_info = estate->es_param_list_info;
2016 if (estate->es_topPlan->nParamExec > 0)
2017 epqstate->es_param_exec_vals = (ParamExecData *)
2018 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2019 epqstate->es_rowMark = estate->es_rowMark;
2020 epqstate->es_instrument = estate->es_instrument;
2021 epqstate->es_force_oids = estate->es_force_oids;
2022 epqstate->es_topPlan = estate->es_topPlan;
2024 * Each epqstate must have its own es_evTupleNull state, but
2025 * all the stack entries share es_evTuple state. This allows
2026 * sub-rechecks to inherit the value being examined by an
2029 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2030 if (priorepq == NULL)
2031 /* first PQ stack entry */
2032 epqstate->es_evTuple = (HeapTuple *)
2033 palloc0(rtsize * sizeof(HeapTuple));
2035 /* later stack entries share the same storage */
2036 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2038 epqstate->es_tupleTable =
2039 ExecCreateTupleTable(estate->es_tupleTable->size);
2041 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
2043 MemoryContextSwitchTo(oldcontext);
2047 * End execution of one level of PlanQual.
2049 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2050 * of the normal cleanup, but *not* close result relations (which we are
2051 * just sharing from the outer query).
2054 EvalPlanQualStop(evalPlanQual *epq)
2056 EState *epqstate = epq->estate;
2057 MemoryContext oldcontext;
2059 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2061 ExecEndNode(epq->planstate);
2063 ExecDropTupleTable(epqstate->es_tupleTable, true);
2064 epqstate->es_tupleTable = NULL;
2066 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2068 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2069 epqstate->es_evTuple[epq->rti - 1] = NULL;
2072 MemoryContextSwitchTo(oldcontext);
2074 FreeExecutorState(epqstate);
2077 epq->planstate = NULL;