1 /*-------------------------------------------------------------------------
4 * top level executor interface routines
12 * These four procedures are the external interface to the executor.
13 * In each case, the query descriptor is required as an argument.
15 * ExecutorStart must be called at the beginning of execution of any
16 * query plan and ExecutorEnd must always be called at the end of
17 * execution of a plan (unless it is aborted due to error).
19 * ExecutorRun accepts direction and count arguments that specify whether
20 * the plan is to be executed forwards, backwards, and for how many tuples.
21 * In some cases ExecutorRun may be called multiple times to process all
22 * the tuples for a plan. It is also acceptable to stop short of executing
23 * the whole plan (but only if it is a SELECT).
25 * ExecutorFinish must be called after the final ExecutorRun call and
26 * before ExecutorEnd. This can be omitted only in case of EXPLAIN,
27 * which should also omit ExecutorRun.
29 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
30 * Portions Copyright (c) 1994, Regents of the University of California
34 * src/backend/executor/execMain.c
36 *-------------------------------------------------------------------------
40 #include "access/htup_details.h"
41 #include "access/sysattr.h"
42 #include "access/transam.h"
43 #include "access/xact.h"
44 #include "catalog/namespace.h"
45 #include "commands/matview.h"
46 #include "commands/trigger.h"
47 #include "executor/execdebug.h"
48 #include "foreign/fdwapi.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
51 #include "optimizer/clauses.h"
52 #include "parser/parsetree.h"
53 #include "storage/bufmgr.h"
54 #include "storage/lmgr.h"
55 #include "tcop/utility.h"
56 #include "utils/acl.h"
57 #include "utils/lsyscache.h"
58 #include "utils/memutils.h"
59 #include "utils/snapmgr.h"
60 #include "utils/tqual.h"
63 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
64 ExecutorStart_hook_type ExecutorStart_hook = NULL;
65 ExecutorRun_hook_type ExecutorRun_hook = NULL;
66 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
67 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
69 /* Hook for plugin to get control in ExecCheckRTPerms() */
70 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
72 /* decls for local routines only used within this module */
73 static void InitPlan(QueryDesc *queryDesc, int eflags);
74 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
75 static void ExecPostprocessPlan(EState *estate);
76 static void ExecEndPlan(PlanState *planstate, EState *estate);
77 static void ExecutePlan(EState *estate, PlanState *planstate,
81 ScanDirection direction,
83 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
84 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
85 static char *ExecBuildSlotValueDescription(TupleTableSlot *slot,
87 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
90 /* end of local decls */
93 /* ----------------------------------------------------------------
96 * This routine must be called at the beginning of any execution of any
99 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
100 * only because some places use QueryDescs for utility commands). The tupDesc
101 * field of the QueryDesc is filled in to describe the tuples that will be
102 * returned, and the internal fields (estate and planstate) are set up.
104 * eflags contains flag bits as described in executor.h.
106 * NB: the CurrentMemoryContext when this is called will become the parent
107 * of the per-query context used for this Executor invocation.
109 * We provide a function hook variable that lets loadable plugins
110 * get control when ExecutorStart is called. Such a plugin would
111 * normally call standard_ExecutorStart().
113 * ----------------------------------------------------------------
116 ExecutorStart(QueryDesc *queryDesc, int eflags)
118 if (ExecutorStart_hook)
119 (*ExecutorStart_hook) (queryDesc, eflags);
121 standard_ExecutorStart(queryDesc, eflags);
125 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
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. EXPLAIN is considered read-only.
138 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
139 ExecCheckXactReadOnly(queryDesc->plannedstmt);
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 external parameters, if any, from queryDesc; and allocate
151 * workspace for internal parameters
153 estate->es_param_list_info = queryDesc->params;
155 if (queryDesc->plannedstmt->nParamExec > 0)
156 estate->es_param_exec_vals = (ParamExecData *)
157 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
160 * If non-read-only query, set the command ID to mark output tuples with
162 switch (queryDesc->operation)
167 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
170 if (queryDesc->plannedstmt->rowMarks != NIL ||
171 queryDesc->plannedstmt->hasModifyingCTE)
172 estate->es_output_cid = GetCurrentCommandId(true);
175 * A SELECT without modifying CTEs can't possibly queue triggers,
176 * so force skip-triggers mode. This is just a marginal efficiency
177 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
178 * all that expensive, but we might as well do it.
180 if (!queryDesc->plannedstmt->hasModifyingCTE)
181 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
187 estate->es_output_cid = GetCurrentCommandId(true);
191 elog(ERROR, "unrecognized operation code: %d",
192 (int) queryDesc->operation);
197 * Copy other important information into the EState
199 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
200 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
201 estate->es_top_eflags = eflags;
202 estate->es_instrument = queryDesc->instrument_options;
205 * Initialize the plan state tree
207 InitPlan(queryDesc, eflags);
210 * Set up an AFTER-trigger statement context, unless told not to, or
211 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
213 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
214 AfterTriggerBeginQuery();
216 MemoryContextSwitchTo(oldcontext);
219 /* ----------------------------------------------------------------
222 * This is the main routine of the executor module. It accepts
223 * the query descriptor from the traffic cop and executes the
226 * ExecutorStart must have been called already.
228 * If direction is NoMovementScanDirection then nothing is done
229 * except to start up/shut down the destination. Otherwise,
230 * we retrieve up to 'count' tuples in the specified direction.
232 * Note: count = 0 is interpreted as no portal limit, i.e., run to
233 * completion. Also note that the count limit is only applied to
234 * retrieved tuples, not for instance to those inserted/updated/deleted
235 * by a ModifyTable plan node.
237 * There is no return value, but output tuples (if any) are sent to
238 * the destination receiver specified in the QueryDesc; and the number
239 * of tuples processed at the top level can be found in
240 * estate->es_processed.
242 * We provide a function hook variable that lets loadable plugins
243 * get control when ExecutorRun is called. Such a plugin would
244 * normally call standard_ExecutorRun().
246 * ----------------------------------------------------------------
249 ExecutorRun(QueryDesc *queryDesc,
250 ScanDirection direction, long count)
252 if (ExecutorRun_hook)
253 (*ExecutorRun_hook) (queryDesc, direction, count);
255 standard_ExecutorRun(queryDesc, direction, count);
259 standard_ExecutorRun(QueryDesc *queryDesc,
260 ScanDirection direction, long count)
266 MemoryContext oldcontext;
269 Assert(queryDesc != NULL);
271 estate = queryDesc->estate;
273 Assert(estate != NULL);
274 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
277 * Switch into per-query memory context
279 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
281 /* Allow instrumentation of Executor overall runtime */
282 if (queryDesc->totaltime)
283 InstrStartNode(queryDesc->totaltime);
286 * extract information from the query descriptor and the query feature.
288 operation = queryDesc->operation;
289 dest = queryDesc->dest;
292 * startup tuple receiver, if we will be emitting tuples
294 estate->es_processed = 0;
295 estate->es_lastoid = InvalidOid;
297 sendTuples = (operation == CMD_SELECT ||
298 queryDesc->plannedstmt->hasReturning);
301 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
306 if (!ScanDirectionIsNoMovement(direction))
308 queryDesc->planstate,
316 * shutdown tuple receiver, if we started it
319 (*dest->rShutdown) (dest);
321 if (queryDesc->totaltime)
322 InstrStopNode(queryDesc->totaltime, estate->es_processed);
324 MemoryContextSwitchTo(oldcontext);
327 /* ----------------------------------------------------------------
330 * This routine must be called after the last ExecutorRun call.
331 * It performs cleanup such as firing AFTER triggers. It is
332 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
333 * include these actions in the total runtime.
335 * We provide a function hook variable that lets loadable plugins
336 * get control when ExecutorFinish is called. Such a plugin would
337 * normally call standard_ExecutorFinish().
339 * ----------------------------------------------------------------
342 ExecutorFinish(QueryDesc *queryDesc)
344 if (ExecutorFinish_hook)
345 (*ExecutorFinish_hook) (queryDesc);
347 standard_ExecutorFinish(queryDesc);
351 standard_ExecutorFinish(QueryDesc *queryDesc)
354 MemoryContext oldcontext;
357 Assert(queryDesc != NULL);
359 estate = queryDesc->estate;
361 Assert(estate != NULL);
362 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
364 /* This should be run once and only once per Executor instance */
365 Assert(!estate->es_finished);
367 /* Switch into per-query memory context */
368 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
370 /* Allow instrumentation of Executor overall runtime */
371 if (queryDesc->totaltime)
372 InstrStartNode(queryDesc->totaltime);
374 /* Run ModifyTable nodes to completion */
375 ExecPostprocessPlan(estate);
377 /* Execute queued AFTER triggers, unless told not to */
378 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
379 AfterTriggerEndQuery(estate);
381 if (queryDesc->totaltime)
382 InstrStopNode(queryDesc->totaltime, 0);
384 MemoryContextSwitchTo(oldcontext);
386 estate->es_finished = true;
389 /* ----------------------------------------------------------------
392 * This routine must be called at the end of execution of any
395 * We provide a function hook variable that lets loadable plugins
396 * get control when ExecutorEnd is called. Such a plugin would
397 * normally call standard_ExecutorEnd().
399 * ----------------------------------------------------------------
402 ExecutorEnd(QueryDesc *queryDesc)
404 if (ExecutorEnd_hook)
405 (*ExecutorEnd_hook) (queryDesc);
407 standard_ExecutorEnd(queryDesc);
411 standard_ExecutorEnd(QueryDesc *queryDesc)
414 MemoryContext oldcontext;
417 Assert(queryDesc != NULL);
419 estate = queryDesc->estate;
421 Assert(estate != NULL);
424 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
425 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
426 * might forget to call it.
428 Assert(estate->es_finished ||
429 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
432 * Switch into per-query memory context to run ExecEndPlan
434 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
436 ExecEndPlan(queryDesc->planstate, estate);
438 /* do away with our snapshots */
439 UnregisterSnapshot(estate->es_snapshot);
440 UnregisterSnapshot(estate->es_crosscheck_snapshot);
443 * Must switch out of context before destroying it
445 MemoryContextSwitchTo(oldcontext);
448 * Release EState and per-query memory context. This should release
449 * everything the executor has allocated.
451 FreeExecutorState(estate);
453 /* Reset queryDesc fields that no longer point to anything */
454 queryDesc->tupDesc = NULL;
455 queryDesc->estate = NULL;
456 queryDesc->planstate = NULL;
457 queryDesc->totaltime = NULL;
460 /* ----------------------------------------------------------------
463 * This routine may be called on an open queryDesc to rewind it
465 * ----------------------------------------------------------------
468 ExecutorRewind(QueryDesc *queryDesc)
471 MemoryContext oldcontext;
474 Assert(queryDesc != NULL);
476 estate = queryDesc->estate;
478 Assert(estate != NULL);
480 /* It's probably not sensible to rescan updating queries */
481 Assert(queryDesc->operation == CMD_SELECT);
484 * Switch into per-query memory context
486 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
491 ExecReScan(queryDesc->planstate);
493 MemoryContextSwitchTo(oldcontext);
499 * Check access permissions for all relations listed in a range table.
501 * Returns true if permissions are adequate. Otherwise, throws an appropriate
502 * error if ereport_on_violation is true, or simply returns false otherwise.
505 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
510 foreach(l, rangeTable)
512 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
514 result = ExecCheckRTEPerms(rte);
517 Assert(rte->rtekind == RTE_RELATION);
518 if (ereport_on_violation)
519 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
520 get_rel_name(rte->relid));
525 if (ExecutorCheckPerms_hook)
526 result = (*ExecutorCheckPerms_hook) (rangeTable,
527 ereport_on_violation);
533 * Check access permissions for a single RTE.
536 ExecCheckRTEPerms(RangeTblEntry *rte)
538 AclMode requiredPerms;
540 AclMode remainingPerms;
547 * Only plain-relation RTEs need to be checked here. Function RTEs are
548 * checked by init_fcache when the function is prepared for execution.
549 * Join, subquery, and special RTEs need no checks.
551 if (rte->rtekind != RTE_RELATION)
555 * No work if requiredPerms is empty.
557 requiredPerms = rte->requiredPerms;
558 if (requiredPerms == 0)
564 * userid to check as: current user unless we have a setuid indication.
566 * Note: GetUserId() is presently fast enough that there's no harm in
567 * calling it separately for each RTE. If that stops being true, we could
568 * call it once in ExecCheckRTPerms and pass the userid down from there.
569 * But for now, no need for the extra clutter.
571 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
574 * We must have *all* the requiredPerms bits, but some of the bits can be
575 * satisfied from column-level rather than relation-level permissions.
576 * First, remove any bits that are satisfied by relation permissions.
578 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
579 remainingPerms = requiredPerms & ~relPerms;
580 if (remainingPerms != 0)
583 * If we lack any permissions that exist only as relation permissions,
584 * we can fail straight away.
586 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
590 * Check to see if we have the needed privileges at column level.
592 * Note: failures just report a table-level error; it would be nicer
593 * to report a column-level error if we have some but not all of the
596 if (remainingPerms & ACL_SELECT)
599 * When the query doesn't explicitly reference any columns (for
600 * example, SELECT COUNT(*) FROM table), allow the query if we
601 * have SELECT on any column of the rel, as per SQL spec.
603 if (bms_is_empty(rte->selectedCols))
605 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
606 ACLMASK_ANY) != ACLCHECK_OK)
610 tmpset = bms_copy(rte->selectedCols);
611 while ((col = bms_first_member(tmpset)) >= 0)
613 /* remove the column number offset */
614 col += FirstLowInvalidHeapAttributeNumber;
615 if (col == InvalidAttrNumber)
617 /* Whole-row reference, must have priv on all cols */
618 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
619 ACLMASK_ALL) != ACLCHECK_OK)
624 if (pg_attribute_aclcheck(relOid, col, userid,
625 ACL_SELECT) != ACLCHECK_OK)
633 * Basically the same for the mod columns, with either INSERT or
634 * UPDATE privilege as specified by remainingPerms.
636 remainingPerms &= ~ACL_SELECT;
637 if (remainingPerms != 0)
640 * When the query doesn't explicitly change any columns, allow the
641 * query if we have permission on any column of the rel. This is
642 * to handle SELECT FOR UPDATE as well as possible corner cases in
645 if (bms_is_empty(rte->modifiedCols))
647 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
648 ACLMASK_ANY) != ACLCHECK_OK)
652 tmpset = bms_copy(rte->modifiedCols);
653 while ((col = bms_first_member(tmpset)) >= 0)
655 /* remove the column number offset */
656 col += FirstLowInvalidHeapAttributeNumber;
657 if (col == InvalidAttrNumber)
659 /* whole-row reference can't happen here */
660 elog(ERROR, "whole-row update is not implemented");
664 if (pg_attribute_aclcheck(relOid, col, userid,
665 remainingPerms) != ACLCHECK_OK)
676 * Check that the query does not imply any writes to non-temp tables.
678 * Note: in a Hot Standby slave this would need to reject writes to temp
679 * tables as well; but an HS slave can't have created any temp tables
680 * in the first place, so no need to check that.
683 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
687 /* Fail if write permissions are requested on any non-temp table */
688 foreach(l, plannedstmt->rtable)
690 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
692 if (rte->rtekind != RTE_RELATION)
695 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
698 if (isTempNamespace(get_rel_namespace(rte->relid)))
701 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
706 /* ----------------------------------------------------------------
709 * Initializes the query plan: open files, allocate storage
710 * and start up the rule manager
711 * ----------------------------------------------------------------
714 InitPlan(QueryDesc *queryDesc, int eflags)
716 CmdType operation = queryDesc->operation;
717 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
718 Plan *plan = plannedstmt->planTree;
719 List *rangeTable = plannedstmt->rtable;
720 EState *estate = queryDesc->estate;
721 PlanState *planstate;
727 * Do permissions checks
729 ExecCheckRTPerms(rangeTable, true);
732 * initialize the node's execution state
734 estate->es_range_table = rangeTable;
735 estate->es_plannedstmt = plannedstmt;
738 * initialize result relation stuff, and open/lock the result rels.
740 * We must do this before initializing the plan tree, else we might try to
741 * do a lock upgrade if a result rel is also a source rel.
743 if (plannedstmt->resultRelations)
745 List *resultRelations = plannedstmt->resultRelations;
746 int numResultRelations = list_length(resultRelations);
747 ResultRelInfo *resultRelInfos;
748 ResultRelInfo *resultRelInfo;
750 resultRelInfos = (ResultRelInfo *)
751 palloc(numResultRelations * sizeof(ResultRelInfo));
752 resultRelInfo = resultRelInfos;
753 foreach(l, resultRelations)
755 Index resultRelationIndex = lfirst_int(l);
756 Oid resultRelationOid;
757 Relation resultRelation;
759 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
760 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
761 InitResultRelInfo(resultRelInfo,
764 estate->es_instrument);
767 estate->es_result_relations = resultRelInfos;
768 estate->es_num_result_relations = numResultRelations;
769 /* es_result_relation_info is NULL except when within ModifyTable */
770 estate->es_result_relation_info = NULL;
775 * if no result relation, then set state appropriately
777 estate->es_result_relations = NULL;
778 estate->es_num_result_relations = 0;
779 estate->es_result_relation_info = NULL;
783 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
784 * before we initialize the plan tree, else we'd be risking lock upgrades.
785 * While we are at it, build the ExecRowMark list.
787 estate->es_rowMarks = NIL;
788 foreach(l, plannedstmt->rowMarks)
790 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
795 /* ignore "parent" rowmarks; they are irrelevant at runtime */
799 switch (rc->markType)
801 case ROW_MARK_EXCLUSIVE:
802 case ROW_MARK_NOKEYEXCLUSIVE:
804 case ROW_MARK_KEYSHARE:
805 relid = getrelid(rc->rti, rangeTable);
806 relation = heap_open(relid, RowShareLock);
808 case ROW_MARK_REFERENCE:
809 relid = getrelid(rc->rti, rangeTable);
810 relation = heap_open(relid, AccessShareLock);
813 /* there's no real table here ... */
817 elog(ERROR, "unrecognized markType: %d", rc->markType);
818 relation = NULL; /* keep compiler quiet */
822 /* Check that relation is a legal target for marking */
824 CheckValidRowMarkRel(relation, rc->markType);
826 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
827 erm->relation = relation;
829 erm->prti = rc->prti;
830 erm->rowmarkId = rc->rowmarkId;
831 erm->markType = rc->markType;
832 erm->noWait = rc->noWait;
833 ItemPointerSetInvalid(&(erm->curCtid));
834 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
838 * Initialize the executor's tuple table to empty.
840 estate->es_tupleTable = NIL;
841 estate->es_trig_tuple_slot = NULL;
842 estate->es_trig_oldtup_slot = NULL;
843 estate->es_trig_newtup_slot = NULL;
845 /* mark EvalPlanQual not active */
846 estate->es_epqTuple = NULL;
847 estate->es_epqTupleSet = NULL;
848 estate->es_epqScanDone = NULL;
851 * Initialize private state information for each SubPlan. We must do this
852 * before running ExecInitNode on the main query tree, since
853 * ExecInitSubPlan expects to be able to find these entries.
855 Assert(estate->es_subplanstates == NIL);
856 i = 1; /* subplan indices count from 1 */
857 foreach(l, plannedstmt->subplans)
859 Plan *subplan = (Plan *) lfirst(l);
860 PlanState *subplanstate;
864 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
865 * it is a parameterless subplan (not initplan), we suggest that it be
866 * prepared to handle REWIND efficiently; otherwise there is no need.
869 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
870 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
871 sp_eflags |= EXEC_FLAG_REWIND;
873 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
875 estate->es_subplanstates = lappend(estate->es_subplanstates,
882 * Initialize the private state information for all the nodes in the query
883 * tree. This opens files, allocates storage and leaves us ready to start
886 planstate = ExecInitNode(plan, estate, eflags);
889 * Get the tuple descriptor describing the type of tuples to return.
891 tupType = ExecGetResultType(planstate);
894 * Initialize the junk filter if needed. SELECT queries need a filter if
895 * there are any junk attrs in the top-level tlist.
897 if (operation == CMD_SELECT)
899 bool junk_filter_needed = false;
902 foreach(tlist, plan->targetlist)
904 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
908 junk_filter_needed = true;
913 if (junk_filter_needed)
917 j = ExecInitJunkFilter(planstate->plan->targetlist,
919 ExecInitExtraTupleSlot(estate));
920 estate->es_junkFilter = j;
922 /* Want to return the cleaned tuple type */
923 tupType = j->jf_cleanTupType;
927 queryDesc->tupDesc = tupType;
928 queryDesc->planstate = planstate;
932 * Check that a proposed result relation is a legal target for the operation
934 * Generally the parser and/or planner should have noticed any such mistake
935 * already, but let's make sure.
937 * Note: when changing this function, you probably also need to look at
938 * CheckValidRowMarkRel.
941 CheckValidResultRel(Relation resultRel, CmdType operation)
943 TriggerDesc *trigDesc = resultRel->trigdesc;
944 FdwRoutine *fdwroutine;
946 switch (resultRel->rd_rel->relkind)
948 case RELKIND_RELATION:
951 case RELKIND_SEQUENCE:
953 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
954 errmsg("cannot change sequence \"%s\"",
955 RelationGetRelationName(resultRel))));
957 case RELKIND_TOASTVALUE:
959 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
960 errmsg("cannot change TOAST relation \"%s\"",
961 RelationGetRelationName(resultRel))));
966 * Okay only if there's a suitable INSTEAD OF trigger. Messages
967 * here should match rewriteHandler.c's rewriteTargetView, except
968 * that we omit errdetail because we haven't got the information
969 * handy (and given that we really shouldn't get here anyway, it's
970 * not worth great exertion to get).
975 if (!trigDesc || !trigDesc->trig_insert_instead_row)
977 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
978 errmsg("cannot insert into view \"%s\"",
979 RelationGetRelationName(resultRel)),
980 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
983 if (!trigDesc || !trigDesc->trig_update_instead_row)
985 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
986 errmsg("cannot update view \"%s\"",
987 RelationGetRelationName(resultRel)),
988 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
991 if (!trigDesc || !trigDesc->trig_delete_instead_row)
993 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
994 errmsg("cannot delete from view \"%s\"",
995 RelationGetRelationName(resultRel)),
996 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
999 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1003 case RELKIND_MATVIEW:
1004 if (!MatViewIncrementalMaintenanceIsEnabled())
1006 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1007 errmsg("cannot change materialized view \"%s\"",
1008 RelationGetRelationName(resultRel))));
1010 case RELKIND_FOREIGN_TABLE:
1011 /* Okay only if the FDW supports it */
1012 fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1016 if (fdwroutine->ExecForeignInsert == NULL)
1018 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1019 errmsg("cannot insert into foreign table \"%s\"",
1020 RelationGetRelationName(resultRel))));
1021 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1022 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1024 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1025 errmsg("foreign table \"%s\" does not allow inserts",
1026 RelationGetRelationName(resultRel))));
1029 if (fdwroutine->ExecForeignUpdate == NULL)
1031 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1032 errmsg("cannot update foreign table \"%s\"",
1033 RelationGetRelationName(resultRel))));
1034 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1035 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1037 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1038 errmsg("foreign table \"%s\" does not allow updates",
1039 RelationGetRelationName(resultRel))));
1042 if (fdwroutine->ExecForeignDelete == NULL)
1044 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1045 errmsg("cannot delete from foreign table \"%s\"",
1046 RelationGetRelationName(resultRel))));
1047 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1048 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1050 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1051 errmsg("foreign table \"%s\" does not allow deletes",
1052 RelationGetRelationName(resultRel))));
1055 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1061 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1062 errmsg("cannot change relation \"%s\"",
1063 RelationGetRelationName(resultRel))));
1069 * Check that a proposed rowmark target relation is a legal target
1071 * In most cases parser and/or planner should have noticed this already, but
1072 * they don't cover all cases.
1075 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1077 switch (rel->rd_rel->relkind)
1079 case RELKIND_RELATION:
1082 case RELKIND_SEQUENCE:
1083 /* Must disallow this because we don't vacuum sequences */
1085 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1086 errmsg("cannot lock rows in sequence \"%s\"",
1087 RelationGetRelationName(rel))));
1089 case RELKIND_TOASTVALUE:
1090 /* We could allow this, but there seems no good reason to */
1092 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1093 errmsg("cannot lock rows in TOAST relation \"%s\"",
1094 RelationGetRelationName(rel))));
1097 /* Should not get here; planner should have expanded the view */
1099 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1100 errmsg("cannot lock rows in view \"%s\"",
1101 RelationGetRelationName(rel))));
1103 case RELKIND_MATVIEW:
1104 /* Should not get here */
1106 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1107 errmsg("cannot lock rows in materialized view \"%s\"",
1108 RelationGetRelationName(rel))));
1110 case RELKIND_FOREIGN_TABLE:
1111 /* Should not get here */
1113 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1114 errmsg("cannot lock rows in foreign table \"%s\"",
1115 RelationGetRelationName(rel))));
1119 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1120 errmsg("cannot lock rows in relation \"%s\"",
1121 RelationGetRelationName(rel))));
1127 * Initialize ResultRelInfo data for one result relation
1129 * Caution: before Postgres 9.1, this function included the relkind checking
1130 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1131 * appropriate. Be sure callers cover those needs.
1134 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1135 Relation resultRelationDesc,
1136 Index resultRelationIndex,
1137 int instrument_options)
1139 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1140 resultRelInfo->type = T_ResultRelInfo;
1141 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1142 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1143 resultRelInfo->ri_NumIndices = 0;
1144 resultRelInfo->ri_IndexRelationDescs = NULL;
1145 resultRelInfo->ri_IndexRelationInfo = NULL;
1146 /* make a copy so as not to depend on relcache info not changing... */
1147 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1148 if (resultRelInfo->ri_TrigDesc)
1150 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1152 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1153 palloc0(n * sizeof(FmgrInfo));
1154 resultRelInfo->ri_TrigWhenExprs = (List **)
1155 palloc0(n * sizeof(List *));
1156 if (instrument_options)
1157 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1161 resultRelInfo->ri_TrigFunctions = NULL;
1162 resultRelInfo->ri_TrigWhenExprs = NULL;
1163 resultRelInfo->ri_TrigInstrument = NULL;
1165 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1166 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1168 resultRelInfo->ri_FdwRoutine = NULL;
1169 resultRelInfo->ri_FdwState = NULL;
1170 resultRelInfo->ri_ConstraintExprs = NULL;
1171 resultRelInfo->ri_junkFilter = NULL;
1172 resultRelInfo->ri_projectReturning = NULL;
1176 * ExecGetTriggerResultRel
1178 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1179 * triggers are fired on one of the result relations of the query, and so
1180 * we can just return a member of the es_result_relations array. (Note: in
1181 * self-join situations there might be multiple members with the same OID;
1182 * if so it doesn't matter which one we pick.) However, it is sometimes
1183 * necessary to fire triggers on other relations; this happens mainly when an
1184 * RI update trigger queues additional triggers on other relations, which will
1185 * be processed in the context of the outer query. For efficiency's sake,
1186 * we want to have a ResultRelInfo for those triggers too; that can avoid
1187 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1188 * ANALYZE to report the runtimes of such triggers.) So we make additional
1189 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1192 ExecGetTriggerResultRel(EState *estate, Oid relid)
1194 ResultRelInfo *rInfo;
1198 MemoryContext oldcontext;
1200 /* First, search through the query result relations */
1201 rInfo = estate->es_result_relations;
1202 nr = estate->es_num_result_relations;
1205 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1210 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1211 foreach(l, estate->es_trig_target_relations)
1213 rInfo = (ResultRelInfo *) lfirst(l);
1214 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1217 /* Nope, so we need a new one */
1220 * Open the target relation's relcache entry. We assume that an
1221 * appropriate lock is still held by the backend from whenever the trigger
1222 * event got queued, so we need take no new lock here. Also, we need not
1223 * recheck the relkind, so no need for CheckValidResultRel.
1225 rel = heap_open(relid, NoLock);
1228 * Make the new entry in the right context.
1230 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1231 rInfo = makeNode(ResultRelInfo);
1232 InitResultRelInfo(rInfo,
1234 0, /* dummy rangetable index */
1235 estate->es_instrument);
1236 estate->es_trig_target_relations =
1237 lappend(estate->es_trig_target_relations, rInfo);
1238 MemoryContextSwitchTo(oldcontext);
1241 * Currently, we don't need any index information in ResultRelInfos used
1242 * only for triggers, so no need to call ExecOpenIndices.
1249 * ExecContextForcesOids
1251 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1252 * we need to ensure that result tuples have space for an OID iff they are
1253 * going to be stored into a relation that has OIDs. In other contexts
1254 * we are free to choose whether to leave space for OIDs in result tuples
1255 * (we generally don't want to, but we do if a physical-tlist optimization
1256 * is possible). This routine checks the plan context and returns TRUE if the
1257 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1258 * *hasoids is set to the required value.
1260 * One reason this is ugly is that all plan nodes in the plan tree will emit
1261 * tuples with space for an OID, though we really only need the topmost node
1262 * to do so. However, node types like Sort don't project new tuples but just
1263 * return their inputs, and in those cases the requirement propagates down
1264 * to the input node. Eventually we might make this code smart enough to
1265 * recognize how far down the requirement really goes, but for now we just
1266 * make all plan nodes do the same thing if the top level forces the choice.
1268 * We assume that if we are generating tuples for INSERT or UPDATE,
1269 * estate->es_result_relation_info is already set up to describe the target
1270 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1271 * the target relations may have OIDs and some not. We have to make the
1272 * decisions on a per-relation basis as we initialize each of the subplans of
1273 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1274 * while initializing each subplan.
1276 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1277 * descriptor available when this code runs; we have to look aside at the
1278 * flags passed to ExecutorStart().
1281 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1283 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1287 Relation rel = ri->ri_RelationDesc;
1291 *hasoids = rel->rd_rel->relhasoids;
1296 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1301 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1310 /* ----------------------------------------------------------------
1311 * ExecPostprocessPlan
1313 * Give plan nodes a final chance to execute before shutdown
1314 * ----------------------------------------------------------------
1317 ExecPostprocessPlan(EState *estate)
1322 * Make sure nodes run forward.
1324 estate->es_direction = ForwardScanDirection;
1327 * Run any secondary ModifyTable nodes to completion, in case the main
1328 * query did not fetch all rows from them. (We do this to ensure that
1329 * such nodes have predictable results.)
1331 foreach(lc, estate->es_auxmodifytables)
1333 PlanState *ps = (PlanState *) lfirst(lc);
1337 TupleTableSlot *slot;
1339 /* Reset the per-output-tuple exprcontext each time */
1340 ResetPerTupleExprContext(estate);
1342 slot = ExecProcNode(ps);
1344 if (TupIsNull(slot))
1350 /* ----------------------------------------------------------------
1353 * Cleans up the query plan -- closes files and frees up storage
1355 * NOTE: we are no longer very worried about freeing storage per se
1356 * in this code; FreeExecutorState should be guaranteed to release all
1357 * memory that needs to be released. What we are worried about doing
1358 * is closing relations and dropping buffer pins. Thus, for example,
1359 * tuple tables must be cleared or dropped to ensure pins are released.
1360 * ----------------------------------------------------------------
1363 ExecEndPlan(PlanState *planstate, EState *estate)
1365 ResultRelInfo *resultRelInfo;
1370 * shut down the node-type-specific query processing
1372 ExecEndNode(planstate);
1377 foreach(l, estate->es_subplanstates)
1379 PlanState *subplanstate = (PlanState *) lfirst(l);
1381 ExecEndNode(subplanstate);
1385 * destroy the executor's tuple table. Actually we only care about
1386 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1387 * the TupleTableSlots, since the containing memory context is about to go
1390 ExecResetTupleTable(estate->es_tupleTable, false);
1393 * close the result relation(s) if any, but hold locks until xact commit.
1395 resultRelInfo = estate->es_result_relations;
1396 for (i = estate->es_num_result_relations; i > 0; i--)
1398 /* Close indices and then the relation itself */
1399 ExecCloseIndices(resultRelInfo);
1400 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1405 * likewise close any trigger target relations
1407 foreach(l, estate->es_trig_target_relations)
1409 resultRelInfo = (ResultRelInfo *) lfirst(l);
1410 /* Close indices and then the relation itself */
1411 ExecCloseIndices(resultRelInfo);
1412 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1416 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1419 foreach(l, estate->es_rowMarks)
1421 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1424 heap_close(erm->relation, NoLock);
1428 /* ----------------------------------------------------------------
1431 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1432 * moving in the specified direction.
1434 * Runs to completion if numberTuples is 0
1436 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1438 * ----------------------------------------------------------------
1441 ExecutePlan(EState *estate,
1442 PlanState *planstate,
1446 ScanDirection direction,
1449 TupleTableSlot *slot;
1450 long current_tuple_count;
1453 * initialize local variables
1455 current_tuple_count = 0;
1458 * Set the direction.
1460 estate->es_direction = direction;
1463 * Loop until we've processed the proper number of tuples from the plan.
1467 /* Reset the per-output-tuple exprcontext */
1468 ResetPerTupleExprContext(estate);
1471 * Execute the plan and obtain a tuple
1473 slot = ExecProcNode(planstate);
1476 * if the tuple is null, then we assume there is nothing more to
1477 * process so we just end the loop...
1479 if (TupIsNull(slot))
1483 * If we have a junk filter, then project a new tuple with the junk
1486 * Store this new "clean" tuple in the junkfilter's resultSlot.
1487 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1488 * because that tuple slot has the wrong descriptor.)
1490 if (estate->es_junkFilter != NULL)
1491 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1494 * If we are supposed to send the tuple somewhere, do so. (In
1495 * practice, this is probably always the case at this point.)
1498 (*dest->receiveSlot) (slot, dest);
1501 * Count tuples processed, if this is a SELECT. (For other operation
1502 * types, the ModifyTable plan node must count the appropriate
1505 if (operation == CMD_SELECT)
1506 (estate->es_processed)++;
1509 * check our tuple count.. if we've processed the proper number then
1510 * quit, else loop again and process more tuples. Zero numberTuples
1513 current_tuple_count++;
1514 if (numberTuples && numberTuples == current_tuple_count)
1521 * ExecRelCheck --- check that tuple meets constraints for result relation
1523 * Returns NULL if OK, else name of failed check constraint
1526 ExecRelCheck(ResultRelInfo *resultRelInfo,
1527 TupleTableSlot *slot, EState *estate)
1529 Relation rel = resultRelInfo->ri_RelationDesc;
1530 int ncheck = rel->rd_att->constr->num_check;
1531 ConstrCheck *check = rel->rd_att->constr->check;
1532 ExprContext *econtext;
1533 MemoryContext oldContext;
1538 * If first time through for this result relation, build expression
1539 * nodetrees for rel's constraint expressions. Keep them in the per-query
1540 * memory context so they'll survive throughout the query.
1542 if (resultRelInfo->ri_ConstraintExprs == NULL)
1544 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1545 resultRelInfo->ri_ConstraintExprs =
1546 (List **) palloc(ncheck * sizeof(List *));
1547 for (i = 0; i < ncheck; i++)
1549 /* ExecQual wants implicit-AND form */
1550 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1551 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1552 ExecPrepareExpr((Expr *) qual, estate);
1554 MemoryContextSwitchTo(oldContext);
1558 * We will use the EState's per-tuple context for evaluating constraint
1559 * expressions (creating it if it's not already there).
1561 econtext = GetPerTupleExprContext(estate);
1563 /* Arrange for econtext's scan tuple to be the tuple under test */
1564 econtext->ecxt_scantuple = slot;
1566 /* And evaluate the constraints */
1567 for (i = 0; i < ncheck; i++)
1569 qual = resultRelInfo->ri_ConstraintExprs[i];
1572 * NOTE: SQL specifies that a NULL result from a constraint expression
1573 * is not to be treated as a failure. Therefore, tell ExecQual to
1574 * return TRUE for NULL.
1576 if (!ExecQual(qual, econtext, true))
1577 return check[i].ccname;
1580 /* NULL result means no error */
1585 ExecConstraints(ResultRelInfo *resultRelInfo,
1586 TupleTableSlot *slot, EState *estate)
1588 Relation rel = resultRelInfo->ri_RelationDesc;
1589 TupleConstr *constr = rel->rd_att->constr;
1593 if (constr->has_not_null)
1595 int natts = rel->rd_att->natts;
1598 for (attrChk = 1; attrChk <= natts; attrChk++)
1600 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1601 slot_attisnull(slot, attrChk))
1603 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1604 errmsg("null value in column \"%s\" violates not-null constraint",
1605 NameStr(rel->rd_att->attrs[attrChk - 1]->attname)),
1606 errdetail("Failing row contains %s.",
1607 ExecBuildSlotValueDescription(slot, 64)),
1608 errtablecol(rel, attrChk)));
1612 if (constr->num_check > 0)
1616 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1618 (errcode(ERRCODE_CHECK_VIOLATION),
1619 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1620 RelationGetRelationName(rel), failed),
1621 errdetail("Failing row contains %s.",
1622 ExecBuildSlotValueDescription(slot, 64)),
1623 errtableconstraint(rel, failed)));
1628 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1631 ExecWithCheckOptions(ResultRelInfo *resultRelInfo,
1632 TupleTableSlot *slot, EState *estate)
1634 ExprContext *econtext;
1638 * We will use the EState's per-tuple context for evaluating constraint
1639 * expressions (creating it if it's not already there).
1641 econtext = GetPerTupleExprContext(estate);
1643 /* Arrange for econtext's scan tuple to be the tuple under test */
1644 econtext->ecxt_scantuple = slot;
1646 /* Check each of the constraints */
1647 forboth(l1, resultRelInfo->ri_WithCheckOptions,
1648 l2, resultRelInfo->ri_WithCheckOptionExprs)
1650 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1651 ExprState *wcoExpr = (ExprState *) lfirst(l2);
1654 * WITH CHECK OPTION checks are intended to ensure that the new tuple
1655 * is visible in the view. If the view's qual evaluates to NULL, then
1656 * the new tuple won't be included in the view. Therefore we need to
1657 * tell ExecQual to return FALSE for NULL (the opposite of what we do
1658 * above for CHECK constraints).
1660 if (!ExecQual((List *) wcoExpr, econtext, false))
1662 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1663 errmsg("new row violates WITH CHECK OPTION for view \"%s\"",
1665 errdetail("Failing row contains %s.",
1666 ExecBuildSlotValueDescription(slot, 64))));
1671 * ExecBuildSlotValueDescription -- construct a string representing a tuple
1673 * This is intentionally very similar to BuildIndexValueDescription, but
1674 * unlike that function, we truncate long field values. That seems necessary
1675 * here since heap field values could be very long, whereas index entries
1676 * typically aren't so wide.
1679 ExecBuildSlotValueDescription(TupleTableSlot *slot, int maxfieldlen)
1682 TupleDesc tupdesc = slot->tts_tupleDescriptor;
1685 /* Make sure the tuple is fully deconstructed */
1686 slot_getallattrs(slot);
1688 initStringInfo(&buf);
1690 appendStringInfoChar(&buf, '(');
1692 for (i = 0; i < tupdesc->natts; i++)
1697 if (slot->tts_isnull[i])
1704 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1705 &foutoid, &typisvarlena);
1706 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1710 appendStringInfoString(&buf, ", ");
1712 /* truncate if needed */
1713 vallen = strlen(val);
1714 if (vallen <= maxfieldlen)
1715 appendStringInfoString(&buf, val);
1718 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
1719 appendBinaryStringInfo(&buf, val, vallen);
1720 appendStringInfoString(&buf, "...");
1724 appendStringInfoChar(&buf, ')');
1731 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1734 ExecFindRowMark(EState *estate, Index rti)
1738 foreach(lc, estate->es_rowMarks)
1740 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1742 if (erm->rti == rti)
1745 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1746 return NULL; /* keep compiler quiet */
1750 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1752 * Inputs are the underlying ExecRowMark struct and the targetlist of the
1753 * input plan node (not planstate node!). We need the latter to find out
1754 * the column numbers of the resjunk columns.
1757 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1759 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1762 aerm->rowmark = erm;
1764 /* Look up the resjunk columns associated with this rowmark */
1767 Assert(erm->markType != ROW_MARK_COPY);
1769 /* if child rel, need tableoid */
1770 if (erm->rti != erm->prti)
1772 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1773 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1775 if (!AttributeNumberIsValid(aerm->toidAttNo))
1776 elog(ERROR, "could not find junk %s column", resname);
1779 /* always need ctid for real relations */
1780 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1781 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1783 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1784 elog(ERROR, "could not find junk %s column", resname);
1788 Assert(erm->markType == ROW_MARK_COPY);
1790 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1791 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1793 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1794 elog(ERROR, "could not find junk %s column", resname);
1802 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1803 * process the updated version under READ COMMITTED rules.
1805 * See backend/executor/README for some info about how this works.
1810 * Check a modified tuple to see if we want to process its updated version
1811 * under READ COMMITTED rules.
1813 * estate - outer executor state data
1814 * epqstate - state for EvalPlanQual rechecking
1815 * relation - table containing tuple
1816 * rti - rangetable index of table containing tuple
1817 * lockmode - requested tuple lock mode
1818 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1819 * priorXmax - t_xmax from the outdated tuple
1821 * *tid is also an output parameter: it's modified to hold the TID of the
1822 * latest version of the tuple (note this may be changed even on failure)
1824 * Returns a slot containing the new candidate update/delete tuple, or
1825 * NULL if we determine we shouldn't process the row.
1827 * Note: properly, lockmode should be declared as enum LockTupleMode,
1828 * but we use "int" to avoid having to include heapam.h in executor.h.
1831 EvalPlanQual(EState *estate, EPQState *epqstate,
1832 Relation relation, Index rti, int lockmode,
1833 ItemPointer tid, TransactionId priorXmax)
1835 TupleTableSlot *slot;
1836 HeapTuple copyTuple;
1841 * Get and lock the updated version of the row; if fail, return NULL.
1843 copyTuple = EvalPlanQualFetch(estate, relation, lockmode,
1846 if (copyTuple == NULL)
1850 * For UPDATE/DELETE we have to return tid of actual row we're executing
1853 *tid = copyTuple->t_self;
1856 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
1858 EvalPlanQualBegin(epqstate, estate);
1861 * Free old test tuple, if any, and store new tuple where relation's scan
1864 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1867 * Fetch any non-locked source rows
1869 EvalPlanQualFetchRowMarks(epqstate);
1872 * Run the EPQ query. We assume it will return at most one tuple.
1874 slot = EvalPlanQualNext(epqstate);
1877 * If we got a tuple, force the slot to materialize the tuple so that it
1878 * is not dependent on any local state in the EPQ query (in particular,
1879 * it's highly likely that the slot contains references to any pass-by-ref
1880 * datums that may be present in copyTuple). As with the next step, this
1881 * is to guard against early re-use of the EPQ query.
1883 if (!TupIsNull(slot))
1884 (void) ExecMaterializeSlot(slot);
1887 * Clear out the test tuple. This is needed in case the EPQ query is
1888 * re-used to test a tuple for a different relation. (Not clear that can
1889 * really happen, but let's be safe.)
1891 EvalPlanQualSetTuple(epqstate, rti, NULL);
1897 * Fetch a copy of the newest version of an outdated tuple
1899 * estate - executor state data
1900 * relation - table containing tuple
1901 * lockmode - requested tuple lock mode
1902 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1903 * priorXmax - t_xmax from the outdated tuple
1905 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1906 * that there is no newest version (ie, the row was deleted not updated).
1907 * If successful, we have locked the newest tuple version, so caller does not
1908 * need to worry about it changing anymore.
1910 * Note: properly, lockmode should be declared as enum LockTupleMode,
1911 * but we use "int" to avoid having to include heapam.h in executor.h.
1914 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1915 ItemPointer tid, TransactionId priorXmax)
1917 HeapTuple copyTuple = NULL;
1918 HeapTupleData tuple;
1919 SnapshotData SnapshotDirty;
1922 * fetch target tuple
1924 * Loop here to deal with updated or busy tuples
1926 InitDirtySnapshot(SnapshotDirty);
1927 tuple.t_self = *tid;
1932 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1935 HeapUpdateFailureData hufd;
1938 * If xmin isn't what we're expecting, the slot must have been
1939 * recycled and reused for an unrelated tuple. This implies that
1940 * the latest version of the row was deleted, so we need do
1941 * nothing. (Should be safe to examine xmin without getting
1942 * buffer's content lock, since xmin never changes in an existing
1945 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1948 ReleaseBuffer(buffer);
1952 /* otherwise xmin should not be dirty... */
1953 if (TransactionIdIsValid(SnapshotDirty.xmin))
1954 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1957 * If tuple is being updated by other transaction then we have to
1958 * wait for its commit/abort.
1960 if (TransactionIdIsValid(SnapshotDirty.xmax))
1962 ReleaseBuffer(buffer);
1963 XactLockTableWait(SnapshotDirty.xmax);
1964 continue; /* loop back to repeat heap_fetch */
1968 * If tuple was inserted by our own transaction, we have to check
1969 * cmin against es_output_cid: cmin >= current CID means our
1970 * command cannot see the tuple, so we should ignore it. Otherwise
1971 * heap_lock_tuple() will throw an error, and so would any later
1972 * attempt to update or delete the tuple. (We need not check cmax
1973 * because HeapTupleSatisfiesDirty will consider a tuple deleted
1974 * by our transaction dead, regardless of cmax.) Wee just checked
1975 * that priorXmax == xmin, so we can test that variable instead of
1976 * doing HeapTupleHeaderGetXmin again.
1978 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1979 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1981 ReleaseBuffer(buffer);
1986 * This is a live tuple, so now try to lock it.
1988 test = heap_lock_tuple(relation, &tuple,
1989 estate->es_output_cid,
1990 lockmode, false /* wait */ ,
1991 false, &buffer, &hufd);
1992 /* We now have two pins on the buffer, get rid of one */
1993 ReleaseBuffer(buffer);
1997 case HeapTupleSelfUpdated:
2000 * The target tuple was already updated or deleted by the
2001 * current command, or by a later command in the current
2002 * transaction. We *must* ignore the tuple in the former
2003 * case, so as to avoid the "Halloween problem" of
2004 * repeated update attempts. In the latter case it might
2005 * be sensible to fetch the updated tuple instead, but
2006 * doing so would require changing heap_lock_tuple as well
2007 * as heap_update and heap_delete to not complain about
2008 * updating "invisible" tuples, which seems pretty scary.
2009 * So for now, treat the tuple as deleted and do not
2012 ReleaseBuffer(buffer);
2015 case HeapTupleMayBeUpdated:
2016 /* successfully locked */
2019 case HeapTupleUpdated:
2020 ReleaseBuffer(buffer);
2021 if (IsolationUsesXactSnapshot())
2023 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2024 errmsg("could not serialize access due to concurrent update")));
2025 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2027 /* it was updated, so look at the updated version */
2028 tuple.t_self = hufd.ctid;
2029 /* updated row should have xmin matching this xmax */
2030 priorXmax = hufd.xmax;
2033 /* tuple was deleted, so give up */
2037 ReleaseBuffer(buffer);
2038 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2040 return NULL; /* keep compiler quiet */
2044 * We got tuple - now copy it for use by recheck query.
2046 copyTuple = heap_copytuple(&tuple);
2047 ReleaseBuffer(buffer);
2052 * If the referenced slot was actually empty, the latest version of
2053 * the row must have been deleted, so we need do nothing.
2055 if (tuple.t_data == NULL)
2057 ReleaseBuffer(buffer);
2062 * As above, if xmin isn't what we're expecting, do nothing.
2064 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2067 ReleaseBuffer(buffer);
2072 * If we get here, the tuple was found but failed SnapshotDirty.
2073 * Assuming the xmin is either a committed xact or our own xact (as it
2074 * certainly should be if we're trying to modify the tuple), this must
2075 * mean that the row was updated or deleted by either a committed xact
2076 * or our own xact. If it was deleted, we can ignore it; if it was
2077 * updated then chain up to the next version and repeat the whole
2080 * As above, it should be safe to examine xmax and t_ctid without the
2081 * buffer content lock, because they can't be changing.
2083 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2085 /* deleted, so forget about it */
2086 ReleaseBuffer(buffer);
2090 /* updated, so look at the updated row */
2091 tuple.t_self = tuple.t_data->t_ctid;
2092 /* updated row should have xmin matching this xmax */
2093 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2094 ReleaseBuffer(buffer);
2095 /* loop back to fetch next in chain */
2099 * Return the copied tuple
2105 * EvalPlanQualInit -- initialize during creation of a plan state node
2106 * that might need to invoke EPQ processing.
2108 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2109 * with EvalPlanQualSetPlan.
2112 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2113 Plan *subplan, List *auxrowmarks, int epqParam)
2115 /* Mark the EPQ state inactive */
2116 epqstate->estate = NULL;
2117 epqstate->planstate = NULL;
2118 epqstate->origslot = NULL;
2119 /* ... and remember data that EvalPlanQualBegin will need */
2120 epqstate->plan = subplan;
2121 epqstate->arowMarks = auxrowmarks;
2122 epqstate->epqParam = epqParam;
2126 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2128 * We need this so that ModifyTuple can deal with multiple subplans.
2131 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2133 /* If we have a live EPQ query, shut it down */
2134 EvalPlanQualEnd(epqstate);
2135 /* And set/change the plan pointer */
2136 epqstate->plan = subplan;
2137 /* The rowmarks depend on the plan, too */
2138 epqstate->arowMarks = auxrowmarks;
2142 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2144 * NB: passed tuple must be palloc'd; it may get freed later
2147 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2149 EState *estate = epqstate->estate;
2154 * free old test tuple, if any, and store new tuple where relation's scan
2157 if (estate->es_epqTuple[rti - 1] != NULL)
2158 heap_freetuple(estate->es_epqTuple[rti - 1]);
2159 estate->es_epqTuple[rti - 1] = tuple;
2160 estate->es_epqTupleSet[rti - 1] = true;
2164 * Fetch back the current test tuple (if any) for the specified RTI
2167 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2169 EState *estate = epqstate->estate;
2173 return estate->es_epqTuple[rti - 1];
2177 * Fetch the current row values for any non-locked relations that need
2178 * to be scanned by an EvalPlanQual operation. origslot must have been set
2179 * to contain the current result row (top-level row) that we need to recheck.
2182 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2186 Assert(epqstate->origslot != NULL);
2188 foreach(l, epqstate->arowMarks)
2190 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2191 ExecRowMark *erm = aerm->rowmark;
2194 HeapTupleData tuple;
2196 if (RowMarkRequiresRowShareLock(erm->markType))
2197 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2199 /* clear any leftover test tuple for this rel */
2200 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2206 Assert(erm->markType == ROW_MARK_REFERENCE);
2208 /* if child rel, must check whether it produced this row */
2209 if (erm->rti != erm->prti)
2213 datum = ExecGetJunkAttribute(epqstate->origslot,
2216 /* non-locked rels could be on the inside of outer joins */
2219 tableoid = DatumGetObjectId(datum);
2221 if (tableoid != RelationGetRelid(erm->relation))
2223 /* this child is inactive right now */
2228 /* fetch the tuple's ctid */
2229 datum = ExecGetJunkAttribute(epqstate->origslot,
2232 /* non-locked rels could be on the inside of outer joins */
2235 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2237 /* okay, fetch the tuple */
2238 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2240 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2242 /* successful, copy and store tuple */
2243 EvalPlanQualSetTuple(epqstate, erm->rti,
2244 heap_copytuple(&tuple));
2245 ReleaseBuffer(buffer);
2251 Assert(erm->markType == ROW_MARK_COPY);
2253 /* fetch the whole-row Var for the relation */
2254 datum = ExecGetJunkAttribute(epqstate->origslot,
2257 /* non-locked rels could be on the inside of outer joins */
2260 td = DatumGetHeapTupleHeader(datum);
2262 /* build a temporary HeapTuple control structure */
2263 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2264 ItemPointerSetInvalid(&(tuple.t_self));
2265 tuple.t_tableOid = InvalidOid;
2268 /* copy and store tuple */
2269 EvalPlanQualSetTuple(epqstate, erm->rti,
2270 heap_copytuple(&tuple));
2276 * Fetch the next row (if any) from EvalPlanQual testing
2278 * (In practice, there should never be more than one row...)
2281 EvalPlanQualNext(EPQState *epqstate)
2283 MemoryContext oldcontext;
2284 TupleTableSlot *slot;
2286 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2287 slot = ExecProcNode(epqstate->planstate);
2288 MemoryContextSwitchTo(oldcontext);
2294 * Initialize or reset an EvalPlanQual state tree
2297 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2299 EState *estate = epqstate->estate;
2303 /* First time through, so create a child EState */
2304 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2309 * We already have a suitable child EPQ tree, so just reset it.
2311 int rtsize = list_length(parentestate->es_range_table);
2312 PlanState *planstate = epqstate->planstate;
2314 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2316 /* Recopy current values of parent parameters */
2317 if (parentestate->es_plannedstmt->nParamExec > 0)
2319 int i = parentestate->es_plannedstmt->nParamExec;
2323 /* copy value if any, but not execPlan link */
2324 estate->es_param_exec_vals[i].value =
2325 parentestate->es_param_exec_vals[i].value;
2326 estate->es_param_exec_vals[i].isnull =
2327 parentestate->es_param_exec_vals[i].isnull;
2332 * Mark child plan tree as needing rescan at all scan nodes. The
2333 * first ExecProcNode will take care of actually doing the rescan.
2335 planstate->chgParam = bms_add_member(planstate->chgParam,
2336 epqstate->epqParam);
2341 * Start execution of an EvalPlanQual plan tree.
2343 * This is a cut-down version of ExecutorStart(): we copy some state from
2344 * the top-level estate rather than initializing it fresh.
2347 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2351 MemoryContext oldcontext;
2354 rtsize = list_length(parentestate->es_range_table);
2356 epqstate->estate = estate = CreateExecutorState();
2358 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2361 * Child EPQ EStates share the parent's copy of unchanging state such as
2362 * the snapshot, rangetable, result-rel info, and external Param info.
2363 * They need their own copies of local state, including a tuple table,
2364 * es_param_exec_vals, etc.
2366 estate->es_direction = ForwardScanDirection;
2367 estate->es_snapshot = parentestate->es_snapshot;
2368 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2369 estate->es_range_table = parentestate->es_range_table;
2370 estate->es_plannedstmt = parentestate->es_plannedstmt;
2371 estate->es_junkFilter = parentestate->es_junkFilter;
2372 estate->es_output_cid = parentestate->es_output_cid;
2373 estate->es_result_relations = parentestate->es_result_relations;
2374 estate->es_num_result_relations = parentestate->es_num_result_relations;
2375 estate->es_result_relation_info = parentestate->es_result_relation_info;
2376 /* es_trig_target_relations must NOT be copied */
2377 estate->es_rowMarks = parentestate->es_rowMarks;
2378 estate->es_top_eflags = parentestate->es_top_eflags;
2379 estate->es_instrument = parentestate->es_instrument;
2380 /* es_auxmodifytables must NOT be copied */
2383 * The external param list is simply shared from parent. The internal
2384 * param workspace has to be local state, but we copy the initial values
2385 * from the parent, so as to have access to any param values that were
2386 * already set from other parts of the parent's plan tree.
2388 estate->es_param_list_info = parentestate->es_param_list_info;
2389 if (parentestate->es_plannedstmt->nParamExec > 0)
2391 int i = parentestate->es_plannedstmt->nParamExec;
2393 estate->es_param_exec_vals = (ParamExecData *)
2394 palloc0(i * sizeof(ParamExecData));
2397 /* copy value if any, but not execPlan link */
2398 estate->es_param_exec_vals[i].value =
2399 parentestate->es_param_exec_vals[i].value;
2400 estate->es_param_exec_vals[i].isnull =
2401 parentestate->es_param_exec_vals[i].isnull;
2406 * Each EState must have its own es_epqScanDone state, but if we have
2407 * nested EPQ checks they should share es_epqTuple arrays. This allows
2408 * sub-rechecks to inherit the values being examined by an outer recheck.
2410 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2411 if (parentestate->es_epqTuple != NULL)
2413 estate->es_epqTuple = parentestate->es_epqTuple;
2414 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2418 estate->es_epqTuple = (HeapTuple *)
2419 palloc0(rtsize * sizeof(HeapTuple));
2420 estate->es_epqTupleSet = (bool *)
2421 palloc0(rtsize * sizeof(bool));
2425 * Each estate also has its own tuple table.
2427 estate->es_tupleTable = NIL;
2430 * Initialize private state information for each SubPlan. We must do this
2431 * before running ExecInitNode on the main query tree, since
2432 * ExecInitSubPlan expects to be able to find these entries. Some of the
2433 * SubPlans might not be used in the part of the plan tree we intend to
2434 * run, but since it's not easy to tell which, we just initialize them
2437 Assert(estate->es_subplanstates == NIL);
2438 foreach(l, parentestate->es_plannedstmt->subplans)
2440 Plan *subplan = (Plan *) lfirst(l);
2441 PlanState *subplanstate;
2443 subplanstate = ExecInitNode(subplan, estate, 0);
2444 estate->es_subplanstates = lappend(estate->es_subplanstates,
2449 * Initialize the private state information for all the nodes in the part
2450 * of the plan tree we need to run. This opens files, allocates storage
2451 * and leaves us ready to start processing tuples.
2453 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2455 MemoryContextSwitchTo(oldcontext);
2459 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2460 * or if we are done with the current EPQ child.
2462 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2463 * of the normal cleanup, but *not* close result relations (which we are
2464 * just sharing from the outer query). We do, however, have to close any
2465 * trigger target relations that got opened, since those are not shared.
2466 * (There probably shouldn't be any of the latter, but just in case...)
2469 EvalPlanQualEnd(EPQState *epqstate)
2471 EState *estate = epqstate->estate;
2472 MemoryContext oldcontext;
2476 return; /* idle, so nothing to do */
2478 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2480 ExecEndNode(epqstate->planstate);
2482 foreach(l, estate->es_subplanstates)
2484 PlanState *subplanstate = (PlanState *) lfirst(l);
2486 ExecEndNode(subplanstate);
2489 /* throw away the per-estate tuple table */
2490 ExecResetTupleTable(estate->es_tupleTable, false);
2492 /* close any trigger target relations attached to this EState */
2493 foreach(l, estate->es_trig_target_relations)
2495 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2497 /* Close indices and then the relation itself */
2498 ExecCloseIndices(resultRelInfo);
2499 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2502 MemoryContextSwitchTo(oldcontext);
2504 FreeExecutorState(estate);
2506 /* Mark EPQState idle */
2507 epqstate->estate = NULL;
2508 epqstate->planstate = NULL;
2509 epqstate->origslot = NULL;