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-2018, 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 "catalog/partition.h"
46 #include "catalog/pg_publication.h"
47 #include "commands/matview.h"
48 #include "commands/trigger.h"
49 #include "executor/execdebug.h"
50 #include "foreign/fdwapi.h"
52 #include "mb/pg_wchar.h"
53 #include "miscadmin.h"
54 #include "optimizer/clauses.h"
55 #include "parser/parsetree.h"
56 #include "rewrite/rewriteManip.h"
57 #include "storage/bufmgr.h"
58 #include "storage/lmgr.h"
59 #include "tcop/utility.h"
60 #include "utils/acl.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/rls.h"
64 #include "utils/ruleutils.h"
65 #include "utils/snapmgr.h"
66 #include "utils/tqual.h"
69 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
70 ExecutorStart_hook_type ExecutorStart_hook = NULL;
71 ExecutorRun_hook_type ExecutorRun_hook = NULL;
72 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
73 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
75 /* Hook for plugin to get control in ExecCheckRTPerms() */
76 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
78 /* decls for local routines only used within this module */
79 static void InitPlan(QueryDesc *queryDesc, int eflags);
80 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
81 static void ExecPostprocessPlan(EState *estate);
82 static void ExecEndPlan(PlanState *planstate, EState *estate);
83 static void ExecutePlan(EState *estate, PlanState *planstate,
84 bool use_parallel_mode,
88 ScanDirection direction,
91 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
92 static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
93 Bitmapset *modifiedCols,
94 AclMode requiredPerms);
95 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
96 static char *ExecBuildSlotValueDescription(Oid reloid,
99 Bitmapset *modifiedCols,
101 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
105 * Note that GetUpdatedColumns() also exists in commands/trigger.c. There does
106 * not appear to be any good header to put it into, given the structures that
107 * it uses, so we let them be duplicated. Be sure to update both if one needs
108 * to be changed, however.
110 #define GetInsertedColumns(relinfo, estate) \
111 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
112 #define GetUpdatedColumns(relinfo, estate) \
113 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
115 /* end of local decls */
118 /* ----------------------------------------------------------------
121 * This routine must be called at the beginning of any execution of any
124 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
125 * only because some places use QueryDescs for utility commands). The tupDesc
126 * field of the QueryDesc is filled in to describe the tuples that will be
127 * returned, and the internal fields (estate and planstate) are set up.
129 * eflags contains flag bits as described in executor.h.
131 * NB: the CurrentMemoryContext when this is called will become the parent
132 * of the per-query context used for this Executor invocation.
134 * We provide a function hook variable that lets loadable plugins
135 * get control when ExecutorStart is called. Such a plugin would
136 * normally call standard_ExecutorStart().
138 * ----------------------------------------------------------------
141 ExecutorStart(QueryDesc *queryDesc, int eflags)
143 if (ExecutorStart_hook)
144 (*ExecutorStart_hook) (queryDesc, eflags);
146 standard_ExecutorStart(queryDesc, eflags);
150 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
153 MemoryContext oldcontext;
155 /* sanity checks: queryDesc must not be started already */
156 Assert(queryDesc != NULL);
157 Assert(queryDesc->estate == NULL);
160 * If the transaction is read-only, we need to check if any writes are
161 * planned to non-temporary tables. EXPLAIN is considered read-only.
163 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
164 * would require (a) storing the combocid hash in shared memory, rather
165 * than synchronizing it just once at the start of parallelism, and (b) an
166 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
167 * INSERT may have no such troubles, but we forbid it to simplify the
170 * We have lower-level defenses in CommandCounterIncrement and elsewhere
171 * against performing unsafe operations in parallel mode, but this gives a
172 * more user-friendly error message.
174 if ((XactReadOnly || IsInParallelMode()) &&
175 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
176 ExecCheckXactReadOnly(queryDesc->plannedstmt);
179 * Build EState, switch into per-query memory context for startup.
181 estate = CreateExecutorState();
182 queryDesc->estate = estate;
184 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
187 * Fill in external parameters, if any, from queryDesc; and allocate
188 * workspace for internal parameters
190 estate->es_param_list_info = queryDesc->params;
192 if (queryDesc->plannedstmt->paramExecTypes != NIL)
196 nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
197 estate->es_param_exec_vals = (ParamExecData *)
198 palloc0(nParamExec * sizeof(ParamExecData));
201 estate->es_sourceText = queryDesc->sourceText;
204 * Fill in the query environment, if any, from queryDesc.
206 estate->es_queryEnv = queryDesc->queryEnv;
209 * If non-read-only query, set the command ID to mark output tuples with
211 switch (queryDesc->operation)
216 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
219 if (queryDesc->plannedstmt->rowMarks != NIL ||
220 queryDesc->plannedstmt->hasModifyingCTE)
221 estate->es_output_cid = GetCurrentCommandId(true);
224 * A SELECT without modifying CTEs can't possibly queue triggers,
225 * so force skip-triggers mode. This is just a marginal efficiency
226 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
227 * all that expensive, but we might as well do it.
229 if (!queryDesc->plannedstmt->hasModifyingCTE)
230 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
236 estate->es_output_cid = GetCurrentCommandId(true);
240 elog(ERROR, "unrecognized operation code: %d",
241 (int) queryDesc->operation);
246 * Copy other important information into the EState
248 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
249 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
250 estate->es_top_eflags = eflags;
251 estate->es_instrument = queryDesc->instrument_options;
252 estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
255 * Set up an AFTER-trigger statement context, unless told not to, or
256 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
258 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
259 AfterTriggerBeginQuery();
262 * Initialize the plan state tree
264 InitPlan(queryDesc, eflags);
266 MemoryContextSwitchTo(oldcontext);
269 /* ----------------------------------------------------------------
272 * This is the main routine of the executor module. It accepts
273 * the query descriptor from the traffic cop and executes the
276 * ExecutorStart must have been called already.
278 * If direction is NoMovementScanDirection then nothing is done
279 * except to start up/shut down the destination. Otherwise,
280 * we retrieve up to 'count' tuples in the specified direction.
282 * Note: count = 0 is interpreted as no portal limit, i.e., run to
283 * completion. Also note that the count limit is only applied to
284 * retrieved tuples, not for instance to those inserted/updated/deleted
285 * by a ModifyTable plan node.
287 * There is no return value, but output tuples (if any) are sent to
288 * the destination receiver specified in the QueryDesc; and the number
289 * of tuples processed at the top level can be found in
290 * estate->es_processed.
292 * We provide a function hook variable that lets loadable plugins
293 * get control when ExecutorRun is called. Such a plugin would
294 * normally call standard_ExecutorRun().
296 * ----------------------------------------------------------------
299 ExecutorRun(QueryDesc *queryDesc,
300 ScanDirection direction, uint64 count,
303 if (ExecutorRun_hook)
304 (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
306 standard_ExecutorRun(queryDesc, direction, count, execute_once);
310 standard_ExecutorRun(QueryDesc *queryDesc,
311 ScanDirection direction, uint64 count, bool execute_once)
317 MemoryContext oldcontext;
320 Assert(queryDesc != NULL);
322 estate = queryDesc->estate;
324 Assert(estate != NULL);
325 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
328 * Switch into per-query memory context
330 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
332 /* Allow instrumentation of Executor overall runtime */
333 if (queryDesc->totaltime)
334 InstrStartNode(queryDesc->totaltime);
337 * extract information from the query descriptor and the query feature.
339 operation = queryDesc->operation;
340 dest = queryDesc->dest;
343 * startup tuple receiver, if we will be emitting tuples
345 estate->es_processed = 0;
346 estate->es_lastoid = InvalidOid;
348 sendTuples = (operation == CMD_SELECT ||
349 queryDesc->plannedstmt->hasReturning);
352 dest->rStartup(dest, operation, queryDesc->tupDesc);
357 if (!ScanDirectionIsNoMovement(direction))
359 if (execute_once && queryDesc->already_executed)
360 elog(ERROR, "can't re-execute query flagged for single execution");
361 queryDesc->already_executed = true;
364 queryDesc->planstate,
365 queryDesc->plannedstmt->parallelModeNeeded,
375 * shutdown tuple receiver, if we started it
378 dest->rShutdown(dest);
380 if (queryDesc->totaltime)
381 InstrStopNode(queryDesc->totaltime, estate->es_processed);
383 MemoryContextSwitchTo(oldcontext);
386 /* ----------------------------------------------------------------
389 * This routine must be called after the last ExecutorRun call.
390 * It performs cleanup such as firing AFTER triggers. It is
391 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
392 * include these actions in the total runtime.
394 * We provide a function hook variable that lets loadable plugins
395 * get control when ExecutorFinish is called. Such a plugin would
396 * normally call standard_ExecutorFinish().
398 * ----------------------------------------------------------------
401 ExecutorFinish(QueryDesc *queryDesc)
403 if (ExecutorFinish_hook)
404 (*ExecutorFinish_hook) (queryDesc);
406 standard_ExecutorFinish(queryDesc);
410 standard_ExecutorFinish(QueryDesc *queryDesc)
413 MemoryContext oldcontext;
416 Assert(queryDesc != NULL);
418 estate = queryDesc->estate;
420 Assert(estate != NULL);
421 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
423 /* This should be run once and only once per Executor instance */
424 Assert(!estate->es_finished);
426 /* Switch into per-query memory context */
427 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
429 /* Allow instrumentation of Executor overall runtime */
430 if (queryDesc->totaltime)
431 InstrStartNode(queryDesc->totaltime);
433 /* Run ModifyTable nodes to completion */
434 ExecPostprocessPlan(estate);
436 /* Execute queued AFTER triggers, unless told not to */
437 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
438 AfterTriggerEndQuery(estate);
440 if (queryDesc->totaltime)
441 InstrStopNode(queryDesc->totaltime, 0);
443 MemoryContextSwitchTo(oldcontext);
445 estate->es_finished = true;
448 /* ----------------------------------------------------------------
451 * This routine must be called at the end of execution of any
454 * We provide a function hook variable that lets loadable plugins
455 * get control when ExecutorEnd is called. Such a plugin would
456 * normally call standard_ExecutorEnd().
458 * ----------------------------------------------------------------
461 ExecutorEnd(QueryDesc *queryDesc)
463 if (ExecutorEnd_hook)
464 (*ExecutorEnd_hook) (queryDesc);
466 standard_ExecutorEnd(queryDesc);
470 standard_ExecutorEnd(QueryDesc *queryDesc)
473 MemoryContext oldcontext;
476 Assert(queryDesc != NULL);
478 estate = queryDesc->estate;
480 Assert(estate != NULL);
483 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
484 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
485 * might forget to call it.
487 Assert(estate->es_finished ||
488 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
491 * Switch into per-query memory context to run ExecEndPlan
493 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
495 ExecEndPlan(queryDesc->planstate, estate);
497 /* do away with our snapshots */
498 UnregisterSnapshot(estate->es_snapshot);
499 UnregisterSnapshot(estate->es_crosscheck_snapshot);
501 /* release JIT context, if allocated */
503 jit_release_context(estate->es_jit);
506 * Must switch out of context before destroying it
508 MemoryContextSwitchTo(oldcontext);
511 * Release EState and per-query memory context. This should release
512 * everything the executor has allocated.
514 FreeExecutorState(estate);
516 /* Reset queryDesc fields that no longer point to anything */
517 queryDesc->tupDesc = NULL;
518 queryDesc->estate = NULL;
519 queryDesc->planstate = NULL;
520 queryDesc->totaltime = NULL;
523 /* ----------------------------------------------------------------
526 * This routine may be called on an open queryDesc to rewind it
528 * ----------------------------------------------------------------
531 ExecutorRewind(QueryDesc *queryDesc)
534 MemoryContext oldcontext;
537 Assert(queryDesc != NULL);
539 estate = queryDesc->estate;
541 Assert(estate != NULL);
543 /* It's probably not sensible to rescan updating queries */
544 Assert(queryDesc->operation == CMD_SELECT);
547 * Switch into per-query memory context
549 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
554 ExecReScan(queryDesc->planstate);
556 MemoryContextSwitchTo(oldcontext);
562 * Check access permissions for all relations listed in a range table.
564 * Returns true if permissions are adequate. Otherwise, throws an appropriate
565 * error if ereport_on_violation is true, or simply returns false otherwise.
567 * Note that this does NOT address row level security policies (aka: RLS). If
568 * rows will be returned to the user as a result of this permission check
569 * passing, then RLS also needs to be consulted (and check_enable_rls()).
571 * See rewrite/rowsecurity.c.
574 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
579 foreach(l, rangeTable)
581 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
583 result = ExecCheckRTEPerms(rte);
586 Assert(rte->rtekind == RTE_RELATION);
587 if (ereport_on_violation)
588 aclcheck_error(ACLCHECK_NO_PRIV, get_relkind_objtype(get_rel_relkind(rte->relid)),
589 get_rel_name(rte->relid));
594 if (ExecutorCheckPerms_hook)
595 result = (*ExecutorCheckPerms_hook) (rangeTable,
596 ereport_on_violation);
602 * Check access permissions for a single RTE.
605 ExecCheckRTEPerms(RangeTblEntry *rte)
607 AclMode requiredPerms;
609 AclMode remainingPerms;
614 * Only plain-relation RTEs need to be checked here. Function RTEs are
615 * checked when the function is prepared for execution. Join, subquery,
616 * and special RTEs need no checks.
618 if (rte->rtekind != RTE_RELATION)
622 * No work if requiredPerms is empty.
624 requiredPerms = rte->requiredPerms;
625 if (requiredPerms == 0)
631 * userid to check as: current user unless we have a setuid indication.
633 * Note: GetUserId() is presently fast enough that there's no harm in
634 * calling it separately for each RTE. If that stops being true, we could
635 * call it once in ExecCheckRTPerms and pass the userid down from there.
636 * But for now, no need for the extra clutter.
638 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
641 * We must have *all* the requiredPerms bits, but some of the bits can be
642 * satisfied from column-level rather than relation-level permissions.
643 * First, remove any bits that are satisfied by relation permissions.
645 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
646 remainingPerms = requiredPerms & ~relPerms;
647 if (remainingPerms != 0)
652 * If we lack any permissions that exist only as relation permissions,
653 * we can fail straight away.
655 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
659 * Check to see if we have the needed privileges at column level.
661 * Note: failures just report a table-level error; it would be nicer
662 * to report a column-level error if we have some but not all of the
665 if (remainingPerms & ACL_SELECT)
668 * When the query doesn't explicitly reference any columns (for
669 * example, SELECT COUNT(*) FROM table), allow the query if we
670 * have SELECT on any column of the rel, as per SQL spec.
672 if (bms_is_empty(rte->selectedCols))
674 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
675 ACLMASK_ANY) != ACLCHECK_OK)
679 while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
681 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
682 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
684 if (attno == InvalidAttrNumber)
686 /* Whole-row reference, must have priv on all cols */
687 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
688 ACLMASK_ALL) != ACLCHECK_OK)
693 if (pg_attribute_aclcheck(relOid, attno, userid,
694 ACL_SELECT) != ACLCHECK_OK)
701 * Basically the same for the mod columns, for both INSERT and UPDATE
702 * privilege as specified by remainingPerms.
704 if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
710 if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
720 * ExecCheckRTEPermsModified
721 * Check INSERT or UPDATE access permissions for a single RTE (these
722 * are processed uniformly).
725 ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
726 AclMode requiredPerms)
731 * When the query doesn't explicitly update any columns, allow the query
732 * if we have permission on any column of the rel. This is to handle
733 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
735 if (bms_is_empty(modifiedCols))
737 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
738 ACLMASK_ANY) != ACLCHECK_OK)
742 while ((col = bms_next_member(modifiedCols, col)) >= 0)
744 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
745 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
747 if (attno == InvalidAttrNumber)
749 /* whole-row reference can't happen here */
750 elog(ERROR, "whole-row update is not implemented");
754 if (pg_attribute_aclcheck(relOid, attno, userid,
755 requiredPerms) != ACLCHECK_OK)
763 * Check that the query does not imply any writes to non-temp tables;
764 * unless we're in parallel mode, in which case don't even allow writes
767 * Note: in a Hot Standby this would need to reject writes to temp
768 * tables just as we do in parallel mode; but an HS standby can't have created
769 * any temp tables in the first place, so no need to check that.
772 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
777 * Fail if write permissions are requested in parallel mode for table
778 * (temp or non-temp), otherwise fail for any non-temp table.
780 foreach(l, plannedstmt->rtable)
782 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
784 if (rte->rtekind != RTE_RELATION)
787 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
790 if (isTempNamespace(get_rel_namespace(rte->relid)))
793 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
796 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
797 PreventCommandIfParallelMode(CreateCommandTag((Node *) plannedstmt));
801 /* ----------------------------------------------------------------
804 * Initializes the query plan: open files, allocate storage
805 * and start up the rule manager
806 * ----------------------------------------------------------------
809 InitPlan(QueryDesc *queryDesc, int eflags)
811 CmdType operation = queryDesc->operation;
812 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
813 Plan *plan = plannedstmt->planTree;
814 List *rangeTable = plannedstmt->rtable;
815 EState *estate = queryDesc->estate;
816 PlanState *planstate;
822 * Do permissions checks
824 ExecCheckRTPerms(rangeTable, true);
827 * initialize the node's execution state
829 estate->es_range_table = rangeTable;
830 estate->es_plannedstmt = plannedstmt;
833 * initialize result relation stuff, and open/lock the result rels.
835 * We must do this before initializing the plan tree, else we might try to
836 * do a lock upgrade if a result rel is also a source rel.
838 if (plannedstmt->resultRelations)
840 List *resultRelations = plannedstmt->resultRelations;
841 int numResultRelations = list_length(resultRelations);
842 ResultRelInfo *resultRelInfos;
843 ResultRelInfo *resultRelInfo;
845 resultRelInfos = (ResultRelInfo *)
846 palloc(numResultRelations * sizeof(ResultRelInfo));
847 resultRelInfo = resultRelInfos;
848 foreach(l, resultRelations)
850 Index resultRelationIndex = lfirst_int(l);
851 Oid resultRelationOid;
852 Relation resultRelation;
854 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
855 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
857 InitResultRelInfo(resultRelInfo,
861 estate->es_instrument);
864 estate->es_result_relations = resultRelInfos;
865 estate->es_num_result_relations = numResultRelations;
866 /* es_result_relation_info is NULL except when within ModifyTable */
867 estate->es_result_relation_info = NULL;
870 * In the partitioned result relation case, lock the non-leaf result
871 * relations too. A subset of these are the roots of respective
872 * partitioned tables, for which we also allocate ResulRelInfos.
874 estate->es_root_result_relations = NULL;
875 estate->es_num_root_result_relations = 0;
876 if (plannedstmt->nonleafResultRelations)
878 int num_roots = list_length(plannedstmt->rootResultRelations);
881 * Firstly, build ResultRelInfos for all the partitioned table
882 * roots, because we will need them to fire the statement-level
885 resultRelInfos = (ResultRelInfo *)
886 palloc(num_roots * sizeof(ResultRelInfo));
887 resultRelInfo = resultRelInfos;
888 foreach(l, plannedstmt->rootResultRelations)
890 Index resultRelIndex = lfirst_int(l);
892 Relation resultRelDesc;
894 resultRelOid = getrelid(resultRelIndex, rangeTable);
895 resultRelDesc = heap_open(resultRelOid, RowExclusiveLock);
896 InitResultRelInfo(resultRelInfo,
900 estate->es_instrument);
904 estate->es_root_result_relations = resultRelInfos;
905 estate->es_num_root_result_relations = num_roots;
907 /* Simply lock the rest of them. */
908 foreach(l, plannedstmt->nonleafResultRelations)
910 Index resultRelIndex = lfirst_int(l);
912 /* We locked the roots above. */
913 if (!list_member_int(plannedstmt->rootResultRelations,
915 LockRelationOid(getrelid(resultRelIndex, rangeTable),
923 * if no result relation, then set state appropriately
925 estate->es_result_relations = NULL;
926 estate->es_num_result_relations = 0;
927 estate->es_result_relation_info = NULL;
928 estate->es_root_result_relations = NULL;
929 estate->es_num_root_result_relations = 0;
933 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
934 * before we initialize the plan tree, else we'd be risking lock upgrades.
935 * While we are at it, build the ExecRowMark list. Any partitioned child
936 * tables are ignored here (because isParent=true) and will be locked by
937 * the first Append or MergeAppend node that references them. (Note that
938 * the RowMarks corresponding to partitioned child tables are present in
939 * the same list as the rest, i.e., plannedstmt->rowMarks.)
941 estate->es_rowMarks = NIL;
942 foreach(l, plannedstmt->rowMarks)
944 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
949 /* ignore "parent" rowmarks; they are irrelevant at runtime */
953 /* get relation's OID (will produce InvalidOid if subquery) */
954 relid = getrelid(rc->rti, rangeTable);
957 * If you change the conditions under which rel locks are acquired
958 * here, be sure to adjust ExecOpenScanRelation to match.
960 switch (rc->markType)
962 case ROW_MARK_EXCLUSIVE:
963 case ROW_MARK_NOKEYEXCLUSIVE:
965 case ROW_MARK_KEYSHARE:
966 relation = heap_open(relid, RowShareLock);
968 case ROW_MARK_REFERENCE:
969 relation = heap_open(relid, AccessShareLock);
972 /* no physical table access is required */
976 elog(ERROR, "unrecognized markType: %d", rc->markType);
977 relation = NULL; /* keep compiler quiet */
981 /* Check that relation is a legal target for marking */
983 CheckValidRowMarkRel(relation, rc->markType);
985 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
986 erm->relation = relation;
989 erm->prti = rc->prti;
990 erm->rowmarkId = rc->rowmarkId;
991 erm->markType = rc->markType;
992 erm->strength = rc->strength;
993 erm->waitPolicy = rc->waitPolicy;
994 erm->ermActive = false;
995 ItemPointerSetInvalid(&(erm->curCtid));
996 erm->ermExtra = NULL;
997 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
1001 * Initialize the executor's tuple table to empty.
1003 estate->es_tupleTable = NIL;
1004 estate->es_trig_tuple_slot = NULL;
1005 estate->es_trig_oldtup_slot = NULL;
1006 estate->es_trig_newtup_slot = NULL;
1008 /* mark EvalPlanQual not active */
1009 estate->es_epqTuple = NULL;
1010 estate->es_epqTupleSet = NULL;
1011 estate->es_epqScanDone = NULL;
1014 * Initialize private state information for each SubPlan. We must do this
1015 * before running ExecInitNode on the main query tree, since
1016 * ExecInitSubPlan expects to be able to find these entries.
1018 Assert(estate->es_subplanstates == NIL);
1019 i = 1; /* subplan indices count from 1 */
1020 foreach(l, plannedstmt->subplans)
1022 Plan *subplan = (Plan *) lfirst(l);
1023 PlanState *subplanstate;
1027 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
1028 * it is a parameterless subplan (not initplan), we suggest that it be
1029 * prepared to handle REWIND efficiently; otherwise there is no need.
1032 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
1033 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
1034 sp_eflags |= EXEC_FLAG_REWIND;
1036 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
1038 estate->es_subplanstates = lappend(estate->es_subplanstates,
1045 * Initialize the private state information for all the nodes in the query
1046 * tree. This opens files, allocates storage and leaves us ready to start
1047 * processing tuples.
1049 planstate = ExecInitNode(plan, estate, eflags);
1052 * Get the tuple descriptor describing the type of tuples to return.
1054 tupType = ExecGetResultType(planstate);
1057 * Initialize the junk filter if needed. SELECT queries need a filter if
1058 * there are any junk attrs in the top-level tlist.
1060 if (operation == CMD_SELECT)
1062 bool junk_filter_needed = false;
1065 foreach(tlist, plan->targetlist)
1067 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1071 junk_filter_needed = true;
1076 if (junk_filter_needed)
1080 j = ExecInitJunkFilter(planstate->plan->targetlist,
1082 ExecInitExtraTupleSlot(estate, NULL));
1083 estate->es_junkFilter = j;
1085 /* Want to return the cleaned tuple type */
1086 tupType = j->jf_cleanTupType;
1090 queryDesc->tupDesc = tupType;
1091 queryDesc->planstate = planstate;
1095 * Check that a proposed result relation is a legal target for the operation
1097 * Generally the parser and/or planner should have noticed any such mistake
1098 * already, but let's make sure.
1100 * Note: when changing this function, you probably also need to look at
1101 * CheckValidRowMarkRel.
1104 CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
1106 Relation resultRel = resultRelInfo->ri_RelationDesc;
1107 TriggerDesc *trigDesc = resultRel->trigdesc;
1108 FdwRoutine *fdwroutine;
1110 switch (resultRel->rd_rel->relkind)
1112 case RELKIND_RELATION:
1113 case RELKIND_PARTITIONED_TABLE:
1114 CheckCmdReplicaIdentity(resultRel, operation);
1116 case RELKIND_SEQUENCE:
1118 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1119 errmsg("cannot change sequence \"%s\"",
1120 RelationGetRelationName(resultRel))));
1122 case RELKIND_TOASTVALUE:
1124 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1125 errmsg("cannot change TOAST relation \"%s\"",
1126 RelationGetRelationName(resultRel))));
1131 * Okay only if there's a suitable INSTEAD OF trigger. Messages
1132 * here should match rewriteHandler.c's rewriteTargetView, except
1133 * that we omit errdetail because we haven't got the information
1134 * handy (and given that we really shouldn't get here anyway, it's
1135 * not worth great exertion to get).
1140 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1142 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1143 errmsg("cannot insert into view \"%s\"",
1144 RelationGetRelationName(resultRel)),
1145 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1148 if (!trigDesc || !trigDesc->trig_update_instead_row)
1150 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1151 errmsg("cannot update view \"%s\"",
1152 RelationGetRelationName(resultRel)),
1153 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1156 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1158 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1159 errmsg("cannot delete from view \"%s\"",
1160 RelationGetRelationName(resultRel)),
1161 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1164 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1168 case RELKIND_MATVIEW:
1169 if (!MatViewIncrementalMaintenanceIsEnabled())
1171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1172 errmsg("cannot change materialized view \"%s\"",
1173 RelationGetRelationName(resultRel))));
1175 case RELKIND_FOREIGN_TABLE:
1176 /* Okay only if the FDW supports it */
1177 fdwroutine = resultRelInfo->ri_FdwRoutine;
1181 if (fdwroutine->ExecForeignInsert == NULL)
1183 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1184 errmsg("cannot insert into foreign table \"%s\"",
1185 RelationGetRelationName(resultRel))));
1186 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1187 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1189 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1190 errmsg("foreign table \"%s\" does not allow inserts",
1191 RelationGetRelationName(resultRel))));
1194 if (fdwroutine->ExecForeignUpdate == NULL)
1196 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1197 errmsg("cannot update foreign table \"%s\"",
1198 RelationGetRelationName(resultRel))));
1199 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1200 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1202 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1203 errmsg("foreign table \"%s\" does not allow updates",
1204 RelationGetRelationName(resultRel))));
1207 if (fdwroutine->ExecForeignDelete == NULL)
1209 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1210 errmsg("cannot delete from foreign table \"%s\"",
1211 RelationGetRelationName(resultRel))));
1212 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1213 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1215 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1216 errmsg("foreign table \"%s\" does not allow deletes",
1217 RelationGetRelationName(resultRel))));
1220 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1226 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1227 errmsg("cannot change relation \"%s\"",
1228 RelationGetRelationName(resultRel))));
1234 * Check that a proposed rowmark target relation is a legal target
1236 * In most cases parser and/or planner should have noticed this already, but
1237 * they don't cover all cases.
1240 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1242 FdwRoutine *fdwroutine;
1244 switch (rel->rd_rel->relkind)
1246 case RELKIND_RELATION:
1247 case RELKIND_PARTITIONED_TABLE:
1250 case RELKIND_SEQUENCE:
1251 /* Must disallow this because we don't vacuum sequences */
1253 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1254 errmsg("cannot lock rows in sequence \"%s\"",
1255 RelationGetRelationName(rel))));
1257 case RELKIND_TOASTVALUE:
1258 /* We could allow this, but there seems no good reason to */
1260 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1261 errmsg("cannot lock rows in TOAST relation \"%s\"",
1262 RelationGetRelationName(rel))));
1265 /* Should not get here; planner should have expanded the view */
1267 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1268 errmsg("cannot lock rows in view \"%s\"",
1269 RelationGetRelationName(rel))));
1271 case RELKIND_MATVIEW:
1272 /* Allow referencing a matview, but not actual locking clauses */
1273 if (markType != ROW_MARK_REFERENCE)
1275 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1276 errmsg("cannot lock rows in materialized view \"%s\"",
1277 RelationGetRelationName(rel))));
1279 case RELKIND_FOREIGN_TABLE:
1280 /* Okay only if the FDW supports it */
1281 fdwroutine = GetFdwRoutineForRelation(rel, false);
1282 if (fdwroutine->RefetchForeignRow == NULL)
1284 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1285 errmsg("cannot lock rows in foreign table \"%s\"",
1286 RelationGetRelationName(rel))));
1290 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1291 errmsg("cannot lock rows in relation \"%s\"",
1292 RelationGetRelationName(rel))));
1298 * Initialize ResultRelInfo data for one result relation
1300 * Caution: before Postgres 9.1, this function included the relkind checking
1301 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1302 * appropriate. Be sure callers cover those needs.
1305 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1306 Relation resultRelationDesc,
1307 Index resultRelationIndex,
1308 Relation partition_root,
1309 int instrument_options)
1311 List *partition_check = NIL;
1313 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1314 resultRelInfo->type = T_ResultRelInfo;
1315 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1316 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1317 resultRelInfo->ri_NumIndices = 0;
1318 resultRelInfo->ri_IndexRelationDescs = NULL;
1319 resultRelInfo->ri_IndexRelationInfo = NULL;
1320 /* make a copy so as not to depend on relcache info not changing... */
1321 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1322 if (resultRelInfo->ri_TrigDesc)
1324 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1326 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1327 palloc0(n * sizeof(FmgrInfo));
1328 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1329 palloc0(n * sizeof(ExprState *));
1330 if (instrument_options)
1331 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1335 resultRelInfo->ri_TrigFunctions = NULL;
1336 resultRelInfo->ri_TrigWhenExprs = NULL;
1337 resultRelInfo->ri_TrigInstrument = NULL;
1339 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1340 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1342 resultRelInfo->ri_FdwRoutine = NULL;
1344 /* The following fields are set later if needed */
1345 resultRelInfo->ri_FdwState = NULL;
1346 resultRelInfo->ri_usesFdwDirectModify = false;
1347 resultRelInfo->ri_ConstraintExprs = NULL;
1348 resultRelInfo->ri_junkFilter = NULL;
1349 resultRelInfo->ri_projectReturning = NULL;
1350 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1351 resultRelInfo->ri_onConflict = NULL;
1354 * Partition constraint, which also includes the partition constraint of
1355 * all the ancestors that are partitions. Note that it will be checked
1356 * even in the case of tuple-routing where this table is the target leaf
1357 * partition, if there any BR triggers defined on the table. Although
1358 * tuple-routing implicitly preserves the partition constraint of the
1359 * target partition for a given row, the BR triggers may change the row
1360 * such that the constraint is no longer satisfied, which we must fail for
1361 * by checking it explicitly.
1363 * If this is a partitioned table, the partition constraint (if any) of a
1364 * given row will be checked just before performing tuple-routing.
1366 partition_check = RelationGetPartitionQual(resultRelationDesc);
1368 resultRelInfo->ri_PartitionCheck = partition_check;
1369 resultRelInfo->ri_PartitionRoot = partition_root;
1370 resultRelInfo->ri_PartitionReadyForRouting = false;
1374 * ExecGetTriggerResultRel
1376 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1377 * triggers are fired on one of the result relations of the query, and so
1378 * we can just return a member of the es_result_relations array, the
1379 * es_root_result_relations array (if any), or the es_leaf_result_relations
1380 * list (if any). (Note: in self-join situations there might be multiple
1381 * members with the same OID; if so it doesn't matter which one we pick.)
1382 * However, it is sometimes necessary to fire triggers on other relations;
1383 * this happens mainly when an RI update trigger queues additional triggers
1384 * on other relations, which will be processed in the context of the outer
1385 * query. For efficiency's sake, we want to have a ResultRelInfo for those
1386 * triggers too; that can avoid repeated re-opening of the relation. (It
1387 * also provides a way for EXPLAIN ANALYZE to report the runtimes of such
1388 * triggers.) So we make additional ResultRelInfo's as needed, and save them
1389 * in es_trig_target_relations.
1392 ExecGetTriggerResultRel(EState *estate, Oid relid)
1394 ResultRelInfo *rInfo;
1398 MemoryContext oldcontext;
1400 /* First, search through the query result relations */
1401 rInfo = estate->es_result_relations;
1402 nr = estate->es_num_result_relations;
1405 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1410 /* Second, search through the root result relations, if any */
1411 rInfo = estate->es_root_result_relations;
1412 nr = estate->es_num_root_result_relations;
1415 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1421 * Third, search through the result relations that were created during
1422 * tuple routing, if any.
1424 foreach(l, estate->es_tuple_routing_result_relations)
1426 rInfo = (ResultRelInfo *) lfirst(l);
1427 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1430 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1431 foreach(l, estate->es_trig_target_relations)
1433 rInfo = (ResultRelInfo *) lfirst(l);
1434 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1437 /* Nope, so we need a new one */
1440 * Open the target relation's relcache entry. We assume that an
1441 * appropriate lock is still held by the backend from whenever the trigger
1442 * event got queued, so we need take no new lock here. Also, we need not
1443 * recheck the relkind, so no need for CheckValidResultRel.
1445 rel = heap_open(relid, NoLock);
1448 * Make the new entry in the right context.
1450 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1451 rInfo = makeNode(ResultRelInfo);
1452 InitResultRelInfo(rInfo,
1454 0, /* dummy rangetable index */
1456 estate->es_instrument);
1457 estate->es_trig_target_relations =
1458 lappend(estate->es_trig_target_relations, rInfo);
1459 MemoryContextSwitchTo(oldcontext);
1462 * Currently, we don't need any index information in ResultRelInfos used
1463 * only for triggers, so no need to call ExecOpenIndices.
1470 * Close any relations that have been opened by ExecGetTriggerResultRel().
1473 ExecCleanUpTriggerState(EState *estate)
1477 foreach(l, estate->es_trig_target_relations)
1479 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1481 /* Close indices and then the relation itself */
1482 ExecCloseIndices(resultRelInfo);
1483 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1488 * ExecContextForcesOids
1490 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1491 * we need to ensure that result tuples have space for an OID iff they are
1492 * going to be stored into a relation that has OIDs. In other contexts
1493 * we are free to choose whether to leave space for OIDs in result tuples
1494 * (we generally don't want to, but we do if a physical-tlist optimization
1495 * is possible). This routine checks the plan context and returns true if the
1496 * choice is forced, false if the choice is not forced. In the true case,
1497 * *hasoids is set to the required value.
1499 * One reason this is ugly is that all plan nodes in the plan tree will emit
1500 * tuples with space for an OID, though we really only need the topmost node
1501 * to do so. However, node types like Sort don't project new tuples but just
1502 * return their inputs, and in those cases the requirement propagates down
1503 * to the input node. Eventually we might make this code smart enough to
1504 * recognize how far down the requirement really goes, but for now we just
1505 * make all plan nodes do the same thing if the top level forces the choice.
1507 * We assume that if we are generating tuples for INSERT or UPDATE,
1508 * estate->es_result_relation_info is already set up to describe the target
1509 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1510 * the target relations may have OIDs and some not. We have to make the
1511 * decisions on a per-relation basis as we initialize each of the subplans of
1512 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1513 * while initializing each subplan.
1515 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1516 * descriptor available when this code runs; we have to look aside at the
1517 * flags passed to ExecutorStart().
1520 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1522 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1526 Relation rel = ri->ri_RelationDesc;
1530 *hasoids = rel->rd_rel->relhasoids;
1535 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1540 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1549 /* ----------------------------------------------------------------
1550 * ExecPostprocessPlan
1552 * Give plan nodes a final chance to execute before shutdown
1553 * ----------------------------------------------------------------
1556 ExecPostprocessPlan(EState *estate)
1561 * Make sure nodes run forward.
1563 estate->es_direction = ForwardScanDirection;
1566 * Run any secondary ModifyTable nodes to completion, in case the main
1567 * query did not fetch all rows from them. (We do this to ensure that
1568 * such nodes have predictable results.)
1570 foreach(lc, estate->es_auxmodifytables)
1572 PlanState *ps = (PlanState *) lfirst(lc);
1576 TupleTableSlot *slot;
1578 /* Reset the per-output-tuple exprcontext each time */
1579 ResetPerTupleExprContext(estate);
1581 slot = ExecProcNode(ps);
1583 if (TupIsNull(slot))
1589 /* ----------------------------------------------------------------
1592 * Cleans up the query plan -- closes files and frees up storage
1594 * NOTE: we are no longer very worried about freeing storage per se
1595 * in this code; FreeExecutorState should be guaranteed to release all
1596 * memory that needs to be released. What we are worried about doing
1597 * is closing relations and dropping buffer pins. Thus, for example,
1598 * tuple tables must be cleared or dropped to ensure pins are released.
1599 * ----------------------------------------------------------------
1602 ExecEndPlan(PlanState *planstate, EState *estate)
1604 ResultRelInfo *resultRelInfo;
1609 * shut down the node-type-specific query processing
1611 ExecEndNode(planstate);
1616 foreach(l, estate->es_subplanstates)
1618 PlanState *subplanstate = (PlanState *) lfirst(l);
1620 ExecEndNode(subplanstate);
1624 * destroy the executor's tuple table. Actually we only care about
1625 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1626 * the TupleTableSlots, since the containing memory context is about to go
1629 ExecResetTupleTable(estate->es_tupleTable, false);
1632 * close the result relation(s) if any, but hold locks until xact commit.
1634 resultRelInfo = estate->es_result_relations;
1635 for (i = estate->es_num_result_relations; i > 0; i--)
1637 /* Close indices and then the relation itself */
1638 ExecCloseIndices(resultRelInfo);
1639 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1643 /* Close the root target relation(s). */
1644 resultRelInfo = estate->es_root_result_relations;
1645 for (i = estate->es_num_root_result_relations; i > 0; i--)
1647 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1651 /* likewise close any trigger target relations */
1652 ExecCleanUpTriggerState(estate);
1655 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1658 foreach(l, estate->es_rowMarks)
1660 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1663 heap_close(erm->relation, NoLock);
1667 /* ----------------------------------------------------------------
1670 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1671 * moving in the specified direction.
1673 * Runs to completion if numberTuples is 0
1675 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1677 * ----------------------------------------------------------------
1680 ExecutePlan(EState *estate,
1681 PlanState *planstate,
1682 bool use_parallel_mode,
1685 uint64 numberTuples,
1686 ScanDirection direction,
1690 TupleTableSlot *slot;
1691 uint64 current_tuple_count;
1694 * initialize local variables
1696 current_tuple_count = 0;
1699 * Set the direction.
1701 estate->es_direction = direction;
1704 * If the plan might potentially be executed multiple times, we must force
1705 * it to run without parallelism, because we might exit early.
1708 use_parallel_mode = false;
1710 estate->es_use_parallel_mode = use_parallel_mode;
1711 if (use_parallel_mode)
1712 EnterParallelMode();
1715 * Loop until we've processed the proper number of tuples from the plan.
1719 /* Reset the per-output-tuple exprcontext */
1720 ResetPerTupleExprContext(estate);
1723 * Execute the plan and obtain a tuple
1725 slot = ExecProcNode(planstate);
1728 * if the tuple is null, then we assume there is nothing more to
1729 * process so we just end the loop...
1731 if (TupIsNull(slot))
1733 /* Allow nodes to release or shut down resources. */
1734 (void) ExecShutdownNode(planstate);
1739 * If we have a junk filter, then project a new tuple with the junk
1742 * Store this new "clean" tuple in the junkfilter's resultSlot.
1743 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1744 * because that tuple slot has the wrong descriptor.)
1746 if (estate->es_junkFilter != NULL)
1747 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1750 * If we are supposed to send the tuple somewhere, do so. (In
1751 * practice, this is probably always the case at this point.)
1756 * If we are not able to send the tuple, we assume the destination
1757 * has closed and no more tuples can be sent. If that's the case,
1760 if (!dest->receiveSlot(slot, dest))
1765 * Count tuples processed, if this is a SELECT. (For other operation
1766 * types, the ModifyTable plan node must count the appropriate
1769 if (operation == CMD_SELECT)
1770 (estate->es_processed)++;
1773 * check our tuple count.. if we've processed the proper number then
1774 * quit, else loop again and process more tuples. Zero numberTuples
1777 current_tuple_count++;
1778 if (numberTuples && numberTuples == current_tuple_count)
1780 /* Allow nodes to release or shut down resources. */
1781 (void) ExecShutdownNode(planstate);
1786 if (use_parallel_mode)
1792 * ExecRelCheck --- check that tuple meets constraints for result relation
1794 * Returns NULL if OK, else name of failed check constraint
1797 ExecRelCheck(ResultRelInfo *resultRelInfo,
1798 TupleTableSlot *slot, EState *estate)
1800 Relation rel = resultRelInfo->ri_RelationDesc;
1801 int ncheck = rel->rd_att->constr->num_check;
1802 ConstrCheck *check = rel->rd_att->constr->check;
1803 ExprContext *econtext;
1804 MemoryContext oldContext;
1808 * If first time through for this result relation, build expression
1809 * nodetrees for rel's constraint expressions. Keep them in the per-query
1810 * memory context so they'll survive throughout the query.
1812 if (resultRelInfo->ri_ConstraintExprs == NULL)
1814 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1815 resultRelInfo->ri_ConstraintExprs =
1816 (ExprState **) palloc(ncheck * sizeof(ExprState *));
1817 for (i = 0; i < ncheck; i++)
1821 checkconstr = stringToNode(check[i].ccbin);
1822 resultRelInfo->ri_ConstraintExprs[i] =
1823 ExecPrepareExpr(checkconstr, estate);
1825 MemoryContextSwitchTo(oldContext);
1829 * We will use the EState's per-tuple context for evaluating constraint
1830 * expressions (creating it if it's not already there).
1832 econtext = GetPerTupleExprContext(estate);
1834 /* Arrange for econtext's scan tuple to be the tuple under test */
1835 econtext->ecxt_scantuple = slot;
1837 /* And evaluate the constraints */
1838 for (i = 0; i < ncheck; i++)
1840 ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1843 * NOTE: SQL specifies that a NULL result from a constraint expression
1844 * is not to be treated as a failure. Therefore, use ExecCheck not
1847 if (!ExecCheck(checkconstr, econtext))
1848 return check[i].ccname;
1851 /* NULL result means no error */
1856 * ExecPartitionCheck --- check that tuple meets the partition constraint.
1858 * Exported in executor.h for outside use.
1859 * Returns true if it meets the partition constraint, else returns false.
1862 ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
1865 ExprContext *econtext;
1868 * If first time through, build expression state tree for the partition
1869 * check expression. Keep it in the per-query memory context so they'll
1870 * survive throughout the query.
1872 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1874 List *qual = resultRelInfo->ri_PartitionCheck;
1876 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1880 * We will use the EState's per-tuple context for evaluating constraint
1881 * expressions (creating it if it's not already there).
1883 econtext = GetPerTupleExprContext(estate);
1885 /* Arrange for econtext's scan tuple to be the tuple under test */
1886 econtext->ecxt_scantuple = slot;
1889 * As in case of the catalogued constraints, we treat a NULL result as
1890 * success here, not a failure.
1892 return ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1896 * ExecPartitionCheckEmitError - Form and emit an error message after a failed
1897 * partition constraint check.
1900 ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
1901 TupleTableSlot *slot,
1904 Relation rel = resultRelInfo->ri_RelationDesc;
1905 Relation orig_rel = rel;
1906 TupleDesc tupdesc = RelationGetDescr(rel);
1908 Bitmapset *modifiedCols;
1909 Bitmapset *insertedCols;
1910 Bitmapset *updatedCols;
1913 * Need to first convert the tuple to the root partitioned table's row
1914 * type. For details, check similar comments in ExecConstraints().
1916 if (resultRelInfo->ri_PartitionRoot)
1918 HeapTuple tuple = ExecFetchSlotTuple(slot);
1919 TupleDesc old_tupdesc = RelationGetDescr(rel);
1920 TupleConversionMap *map;
1922 rel = resultRelInfo->ri_PartitionRoot;
1923 tupdesc = RelationGetDescr(rel);
1925 map = convert_tuples_by_name(old_tupdesc, tupdesc,
1926 gettext_noop("could not convert row type"));
1929 tuple = do_convert_tuple(tuple, map);
1930 ExecSetSlotDescriptor(slot, tupdesc);
1931 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1935 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1936 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1937 modifiedCols = bms_union(insertedCols, updatedCols);
1938 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1944 (errcode(ERRCODE_CHECK_VIOLATION),
1945 errmsg("new row for relation \"%s\" violates partition constraint",
1946 RelationGetRelationName(orig_rel)),
1947 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1951 * ExecConstraints - check constraints of the tuple in 'slot'
1953 * This checks the traditional NOT NULL and check constraints, and if
1954 * requested, checks the partition constraint.
1956 * Note: 'slot' contains the tuple to check the constraints of, which may
1957 * have been converted from the original input tuple after tuple routing.
1958 * 'resultRelInfo' is the original result relation, before tuple routing.
1961 ExecConstraints(ResultRelInfo *resultRelInfo,
1962 TupleTableSlot *slot, EState *estate,
1963 bool check_partition_constraint)
1965 Relation rel = resultRelInfo->ri_RelationDesc;
1966 TupleDesc tupdesc = RelationGetDescr(rel);
1967 TupleConstr *constr = tupdesc->constr;
1968 Bitmapset *modifiedCols;
1969 Bitmapset *insertedCols;
1970 Bitmapset *updatedCols;
1972 Assert(constr || resultRelInfo->ri_PartitionCheck);
1974 if (constr && constr->has_not_null)
1976 int natts = tupdesc->natts;
1979 for (attrChk = 1; attrChk <= natts; attrChk++)
1981 Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1983 if (att->attnotnull && slot_attisnull(slot, attrChk))
1986 Relation orig_rel = rel;
1987 TupleDesc orig_tupdesc = RelationGetDescr(rel);
1990 * If the tuple has been routed, it's been converted to the
1991 * partition's rowtype, which might differ from the root
1992 * table's. We must convert it back to the root table's
1993 * rowtype so that val_desc shown error message matches the
1996 if (resultRelInfo->ri_PartitionRoot)
1998 HeapTuple tuple = ExecFetchSlotTuple(slot);
1999 TupleConversionMap *map;
2001 rel = resultRelInfo->ri_PartitionRoot;
2002 tupdesc = RelationGetDescr(rel);
2004 map = convert_tuples_by_name(orig_tupdesc, tupdesc,
2005 gettext_noop("could not convert row type"));
2008 tuple = do_convert_tuple(tuple, map);
2009 ExecSetSlotDescriptor(slot, tupdesc);
2010 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2014 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2015 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2016 modifiedCols = bms_union(insertedCols, updatedCols);
2017 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2024 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2025 errmsg("null value in column \"%s\" violates not-null constraint",
2026 NameStr(att->attname)),
2027 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2028 errtablecol(orig_rel, attrChk)));
2033 if (constr && constr->num_check > 0)
2037 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2040 Relation orig_rel = rel;
2042 /* See the comment above. */
2043 if (resultRelInfo->ri_PartitionRoot)
2045 HeapTuple tuple = ExecFetchSlotTuple(slot);
2046 TupleDesc old_tupdesc = RelationGetDescr(rel);
2047 TupleConversionMap *map;
2049 rel = resultRelInfo->ri_PartitionRoot;
2050 tupdesc = RelationGetDescr(rel);
2052 map = convert_tuples_by_name(old_tupdesc, tupdesc,
2053 gettext_noop("could not convert row type"));
2056 tuple = do_convert_tuple(tuple, map);
2057 ExecSetSlotDescriptor(slot, tupdesc);
2058 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2062 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2063 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2064 modifiedCols = bms_union(insertedCols, updatedCols);
2065 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2071 (errcode(ERRCODE_CHECK_VIOLATION),
2072 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2073 RelationGetRelationName(orig_rel), failed),
2074 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2075 errtableconstraint(orig_rel, failed)));
2079 if (check_partition_constraint && resultRelInfo->ri_PartitionCheck &&
2080 !ExecPartitionCheck(resultRelInfo, slot, estate))
2081 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
2086 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
2087 * of the specified kind.
2089 * Note that this needs to be called multiple times to ensure that all kinds of
2090 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
2091 * CHECK OPTION set and from row level security policies). See ExecInsert()
2095 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
2096 TupleTableSlot *slot, EState *estate)
2098 Relation rel = resultRelInfo->ri_RelationDesc;
2099 TupleDesc tupdesc = RelationGetDescr(rel);
2100 ExprContext *econtext;
2105 * We will use the EState's per-tuple context for evaluating constraint
2106 * expressions (creating it if it's not already there).
2108 econtext = GetPerTupleExprContext(estate);
2110 /* Arrange for econtext's scan tuple to be the tuple under test */
2111 econtext->ecxt_scantuple = slot;
2113 /* Check each of the constraints */
2114 forboth(l1, resultRelInfo->ri_WithCheckOptions,
2115 l2, resultRelInfo->ri_WithCheckOptionExprs)
2117 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2118 ExprState *wcoExpr = (ExprState *) lfirst(l2);
2121 * Skip any WCOs which are not the kind we are looking for at this
2124 if (wco->kind != kind)
2128 * WITH CHECK OPTION checks are intended to ensure that the new tuple
2129 * is visible (in the case of a view) or that it passes the
2130 * 'with-check' policy (in the case of row security). If the qual
2131 * evaluates to NULL or FALSE, then the new tuple won't be included in
2132 * the view or doesn't pass the 'with-check' policy for the table.
2134 if (!ExecQual(wcoExpr, econtext))
2137 Bitmapset *modifiedCols;
2138 Bitmapset *insertedCols;
2139 Bitmapset *updatedCols;
2144 * For WITH CHECK OPTIONs coming from views, we might be
2145 * able to provide the details on the row, depending on
2146 * the permissions on the relation (that is, if the user
2147 * could view it directly anyway). For RLS violations, we
2148 * don't include the data since we don't know if the user
2149 * should be able to view the tuple as that depends on the
2152 case WCO_VIEW_CHECK:
2153 /* See the comment in ExecConstraints(). */
2154 if (resultRelInfo->ri_PartitionRoot)
2156 HeapTuple tuple = ExecFetchSlotTuple(slot);
2157 TupleDesc old_tupdesc = RelationGetDescr(rel);
2158 TupleConversionMap *map;
2160 rel = resultRelInfo->ri_PartitionRoot;
2161 tupdesc = RelationGetDescr(rel);
2163 map = convert_tuples_by_name(old_tupdesc, tupdesc,
2164 gettext_noop("could not convert row type"));
2167 tuple = do_convert_tuple(tuple, map);
2168 ExecSetSlotDescriptor(slot, tupdesc);
2169 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2173 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2174 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2175 modifiedCols = bms_union(insertedCols, updatedCols);
2176 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2183 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2184 errmsg("new row violates check option for view \"%s\"",
2186 val_desc ? errdetail("Failing row contains %s.",
2189 case WCO_RLS_INSERT_CHECK:
2190 case WCO_RLS_UPDATE_CHECK:
2191 if (wco->polname != NULL)
2193 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2194 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2195 wco->polname, wco->relname)));
2198 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2199 errmsg("new row violates row-level security policy for table \"%s\"",
2202 case WCO_RLS_CONFLICT_CHECK:
2203 if (wco->polname != NULL)
2205 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2206 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2207 wco->polname, wco->relname)));
2210 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2211 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2215 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2223 * ExecBuildSlotValueDescription -- construct a string representing a tuple
2225 * This is intentionally very similar to BuildIndexValueDescription, but
2226 * unlike that function, we truncate long field values (to at most maxfieldlen
2227 * bytes). That seems necessary here since heap field values could be very
2228 * long, whereas index entries typically aren't so wide.
2230 * Also, unlike the case with index entries, we need to be prepared to ignore
2231 * dropped columns. We used to use the slot's tuple descriptor to decode the
2232 * data, but the slot's descriptor doesn't identify dropped columns, so we
2233 * now need to be passed the relation's descriptor.
2235 * Note that, like BuildIndexValueDescription, if the user does not have
2236 * permission to view any of the columns involved, a NULL is returned. Unlike
2237 * BuildIndexValueDescription, if the user has access to view a subset of the
2238 * column involved, that subset will be returned with a key identifying which
2242 ExecBuildSlotValueDescription(Oid reloid,
2243 TupleTableSlot *slot,
2245 Bitmapset *modifiedCols,
2249 StringInfoData collist;
2250 bool write_comma = false;
2251 bool write_comma_collist = false;
2253 AclResult aclresult;
2254 bool table_perm = false;
2255 bool any_perm = false;
2258 * Check if RLS is enabled and should be active for the relation; if so,
2259 * then don't return anything. Otherwise, go through normal permission
2262 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2265 initStringInfo(&buf);
2267 appendStringInfoChar(&buf, '(');
2270 * Check if the user has permissions to see the row. Table-level SELECT
2271 * allows access to all columns. If the user does not have table-level
2272 * SELECT then we check each column and include those the user has SELECT
2273 * rights on. Additionally, we always include columns the user provided
2276 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2277 if (aclresult != ACLCHECK_OK)
2279 /* Set up the buffer for the column list */
2280 initStringInfo(&collist);
2281 appendStringInfoChar(&collist, '(');
2284 table_perm = any_perm = true;
2286 /* Make sure the tuple is fully deconstructed */
2287 slot_getallattrs(slot);
2289 for (i = 0; i < tupdesc->natts; i++)
2291 bool column_perm = false;
2294 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2296 /* ignore dropped columns */
2297 if (att->attisdropped)
2303 * No table-level SELECT, so need to make sure they either have
2304 * SELECT rights on the column or that they have provided the data
2305 * for the column. If not, omit this column from the error
2308 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2309 GetUserId(), ACL_SELECT);
2310 if (bms_is_member(att->attnum - FirstLowInvalidHeapAttributeNumber,
2311 modifiedCols) || aclresult == ACLCHECK_OK)
2313 column_perm = any_perm = true;
2315 if (write_comma_collist)
2316 appendStringInfoString(&collist, ", ");
2318 write_comma_collist = true;
2320 appendStringInfoString(&collist, NameStr(att->attname));
2324 if (table_perm || column_perm)
2326 if (slot->tts_isnull[i])
2333 getTypeOutputInfo(att->atttypid,
2334 &foutoid, &typisvarlena);
2335 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2339 appendStringInfoString(&buf, ", ");
2343 /* truncate if needed */
2344 vallen = strlen(val);
2345 if (vallen <= maxfieldlen)
2346 appendStringInfoString(&buf, val);
2349 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2350 appendBinaryStringInfo(&buf, val, vallen);
2351 appendStringInfoString(&buf, "...");
2356 /* If we end up with zero columns being returned, then return NULL. */
2360 appendStringInfoChar(&buf, ')');
2364 appendStringInfoString(&collist, ") = ");
2365 appendStringInfoString(&collist, buf.data);
2367 return collist.data;
2375 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2376 * given ResultRelInfo
2379 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2382 Bitmapset *updatedCols;
2385 * Compute lock mode to use. If columns that are part of the key have not
2386 * been modified, then we can use a weaker lock, allowing for better
2389 updatedCols = GetUpdatedColumns(relinfo, estate);
2390 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2391 INDEX_ATTR_BITMAP_KEY);
2393 if (bms_overlap(keyCols, updatedCols))
2394 return LockTupleExclusive;
2396 return LockTupleNoKeyExclusive;
2400 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2402 * If no such struct, either return NULL or throw error depending on missing_ok
2405 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2409 foreach(lc, estate->es_rowMarks)
2411 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2413 if (erm->rti == rti)
2417 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2422 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2424 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2425 * input plan node (not planstate node!). We need the latter to find out
2426 * the column numbers of the resjunk columns.
2429 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2431 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2434 aerm->rowmark = erm;
2436 /* Look up the resjunk columns associated with this rowmark */
2437 if (erm->markType != ROW_MARK_COPY)
2439 /* need ctid for all methods other than COPY */
2440 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2441 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2443 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2444 elog(ERROR, "could not find junk %s column", resname);
2448 /* need wholerow if COPY */
2449 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2450 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2452 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2453 elog(ERROR, "could not find junk %s column", resname);
2456 /* if child rel, need tableoid */
2457 if (erm->rti != erm->prti)
2459 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2460 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2462 if (!AttributeNumberIsValid(aerm->toidAttNo))
2463 elog(ERROR, "could not find junk %s column", resname);
2471 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2472 * process the updated version under READ COMMITTED rules.
2474 * See backend/executor/README for some info about how this works.
2479 * Check a modified tuple to see if we want to process its updated version
2480 * under READ COMMITTED rules.
2482 * estate - outer executor state data
2483 * epqstate - state for EvalPlanQual rechecking
2484 * relation - table containing tuple
2485 * rti - rangetable index of table containing tuple
2486 * lockmode - requested tuple lock mode
2487 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2488 * priorXmax - t_xmax from the outdated tuple
2490 * *tid is also an output parameter: it's modified to hold the TID of the
2491 * latest version of the tuple (note this may be changed even on failure)
2493 * Returns a slot containing the new candidate update/delete tuple, or
2494 * NULL if we determine we shouldn't process the row.
2496 * Note: properly, lockmode should be declared as enum LockTupleMode,
2497 * but we use "int" to avoid having to include heapam.h in executor.h.
2500 EvalPlanQual(EState *estate, EPQState *epqstate,
2501 Relation relation, Index rti, int lockmode,
2502 ItemPointer tid, TransactionId priorXmax)
2504 TupleTableSlot *slot;
2505 HeapTuple copyTuple;
2510 * Get and lock the updated version of the row; if fail, return NULL.
2512 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2515 if (copyTuple == NULL)
2519 * For UPDATE/DELETE we have to return tid of actual row we're executing
2522 *tid = copyTuple->t_self;
2525 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2527 EvalPlanQualBegin(epqstate, estate);
2530 * Free old test tuple, if any, and store new tuple where relation's scan
2533 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2536 * Fetch any non-locked source rows
2538 EvalPlanQualFetchRowMarks(epqstate);
2541 * Run the EPQ query. We assume it will return at most one tuple.
2543 slot = EvalPlanQualNext(epqstate);
2546 * If we got a tuple, force the slot to materialize the tuple so that it
2547 * is not dependent on any local state in the EPQ query (in particular,
2548 * it's highly likely that the slot contains references to any pass-by-ref
2549 * datums that may be present in copyTuple). As with the next step, this
2550 * is to guard against early re-use of the EPQ query.
2552 if (!TupIsNull(slot))
2553 (void) ExecMaterializeSlot(slot);
2556 * Clear out the test tuple. This is needed in case the EPQ query is
2557 * re-used to test a tuple for a different relation. (Not clear that can
2558 * really happen, but let's be safe.)
2560 EvalPlanQualSetTuple(epqstate, rti, NULL);
2566 * Fetch a copy of the newest version of an outdated tuple
2568 * estate - executor state data
2569 * relation - table containing tuple
2570 * lockmode - requested tuple lock mode
2571 * wait_policy - requested lock wait policy
2572 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2573 * priorXmax - t_xmax from the outdated tuple
2575 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2576 * that there is no newest version (ie, the row was deleted not updated).
2577 * We also return NULL if the tuple is locked and the wait policy is to skip
2580 * If successful, we have locked the newest tuple version, so caller does not
2581 * need to worry about it changing anymore.
2583 * Note: properly, lockmode should be declared as enum LockTupleMode,
2584 * but we use "int" to avoid having to include heapam.h in executor.h.
2587 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2588 LockWaitPolicy wait_policy,
2589 ItemPointer tid, TransactionId priorXmax)
2591 HeapTuple copyTuple = NULL;
2592 HeapTupleData tuple;
2593 SnapshotData SnapshotDirty;
2596 * fetch target tuple
2598 * Loop here to deal with updated or busy tuples
2600 InitDirtySnapshot(SnapshotDirty);
2601 tuple.t_self = *tid;
2606 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2609 HeapUpdateFailureData hufd;
2612 * If xmin isn't what we're expecting, the slot must have been
2613 * recycled and reused for an unrelated tuple. This implies that
2614 * the latest version of the row was deleted, so we need do
2615 * nothing. (Should be safe to examine xmin without getting
2616 * buffer's content lock. We assume reading a TransactionId to be
2617 * atomic, and Xmin never changes in an existing tuple, except to
2618 * invalid or frozen, and neither of those can match priorXmax.)
2620 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2623 ReleaseBuffer(buffer);
2627 /* otherwise xmin should not be dirty... */
2628 if (TransactionIdIsValid(SnapshotDirty.xmin))
2629 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2632 * If tuple is being updated by other transaction then we have to
2633 * wait for its commit/abort, or die trying.
2635 if (TransactionIdIsValid(SnapshotDirty.xmax))
2637 ReleaseBuffer(buffer);
2638 switch (wait_policy)
2641 XactLockTableWait(SnapshotDirty.xmax,
2642 relation, &tuple.t_self,
2646 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2647 return NULL; /* skip instead of waiting */
2650 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2652 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2653 errmsg("could not obtain lock on row in relation \"%s\"",
2654 RelationGetRelationName(relation))));
2657 continue; /* loop back to repeat heap_fetch */
2661 * If tuple was inserted by our own transaction, we have to check
2662 * cmin against es_output_cid: cmin >= current CID means our
2663 * command cannot see the tuple, so we should ignore it. Otherwise
2664 * heap_lock_tuple() will throw an error, and so would any later
2665 * attempt to update or delete the tuple. (We need not check cmax
2666 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2667 * by our transaction dead, regardless of cmax.) We just checked
2668 * that priorXmax == xmin, so we can test that variable instead of
2669 * doing HeapTupleHeaderGetXmin again.
2671 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2672 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2674 ReleaseBuffer(buffer);
2679 * This is a live tuple, so now try to lock it.
2681 test = heap_lock_tuple(relation, &tuple,
2682 estate->es_output_cid,
2683 lockmode, wait_policy,
2684 false, &buffer, &hufd);
2685 /* We now have two pins on the buffer, get rid of one */
2686 ReleaseBuffer(buffer);
2690 case HeapTupleSelfUpdated:
2693 * The target tuple was already updated or deleted by the
2694 * current command, or by a later command in the current
2695 * transaction. We *must* ignore the tuple in the former
2696 * case, so as to avoid the "Halloween problem" of
2697 * repeated update attempts. In the latter case it might
2698 * be sensible to fetch the updated tuple instead, but
2699 * doing so would require changing heap_update and
2700 * heap_delete to not complain about updating "invisible"
2701 * tuples, which seems pretty scary (heap_lock_tuple will
2702 * not complain, but few callers expect
2703 * HeapTupleInvisible, and we're not one of them). So for
2704 * now, treat the tuple as deleted and do not process.
2706 ReleaseBuffer(buffer);
2709 case HeapTupleMayBeUpdated:
2710 /* successfully locked */
2713 case HeapTupleUpdated:
2714 ReleaseBuffer(buffer);
2715 if (IsolationUsesXactSnapshot())
2717 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2718 errmsg("could not serialize access due to concurrent update")));
2719 if (ItemPointerIndicatesMovedPartitions(&hufd.ctid))
2721 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2722 errmsg("tuple to be locked was already moved to another partition due to concurrent update")));
2724 /* Should not encounter speculative tuple on recheck */
2725 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2726 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2728 /* it was updated, so look at the updated version */
2729 tuple.t_self = hufd.ctid;
2730 /* updated row should have xmin matching this xmax */
2731 priorXmax = hufd.xmax;
2734 /* tuple was deleted, so give up */
2737 case HeapTupleWouldBlock:
2738 ReleaseBuffer(buffer);
2741 case HeapTupleInvisible:
2742 elog(ERROR, "attempted to lock invisible tuple");
2745 ReleaseBuffer(buffer);
2746 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2748 return NULL; /* keep compiler quiet */
2752 * We got tuple - now copy it for use by recheck query.
2754 copyTuple = heap_copytuple(&tuple);
2755 ReleaseBuffer(buffer);
2760 * If the referenced slot was actually empty, the latest version of
2761 * the row must have been deleted, so we need do nothing.
2763 if (tuple.t_data == NULL)
2765 ReleaseBuffer(buffer);
2770 * As above, if xmin isn't what we're expecting, do nothing.
2772 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2775 ReleaseBuffer(buffer);
2780 * If we get here, the tuple was found but failed SnapshotDirty.
2781 * Assuming the xmin is either a committed xact or our own xact (as it
2782 * certainly should be if we're trying to modify the tuple), this must
2783 * mean that the row was updated or deleted by either a committed xact
2784 * or our own xact. If it was deleted, we can ignore it; if it was
2785 * updated then chain up to the next version and repeat the whole
2788 * As above, it should be safe to examine xmax and t_ctid without the
2789 * buffer content lock, because they can't be changing.
2792 /* check whether next version would be in a different partition */
2793 if (HeapTupleHeaderIndicatesMovedPartitions(tuple.t_data))
2795 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2796 errmsg("tuple to be locked was already moved to another partition due to concurrent update")));
2798 /* check whether tuple has been deleted */
2799 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2801 /* deleted, so forget about it */
2802 ReleaseBuffer(buffer);
2806 /* updated, so look at the updated row */
2807 tuple.t_self = tuple.t_data->t_ctid;
2808 /* updated row should have xmin matching this xmax */
2809 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2810 ReleaseBuffer(buffer);
2811 /* loop back to fetch next in chain */
2815 * Return the copied tuple
2821 * EvalPlanQualInit -- initialize during creation of a plan state node
2822 * that might need to invoke EPQ processing.
2824 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2825 * with EvalPlanQualSetPlan.
2828 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2829 Plan *subplan, List *auxrowmarks, int epqParam)
2831 /* Mark the EPQ state inactive */
2832 epqstate->estate = NULL;
2833 epqstate->planstate = NULL;
2834 epqstate->origslot = NULL;
2835 /* ... and remember data that EvalPlanQualBegin will need */
2836 epqstate->plan = subplan;
2837 epqstate->arowMarks = auxrowmarks;
2838 epqstate->epqParam = epqParam;
2842 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2844 * We need this so that ModifyTable can deal with multiple subplans.
2847 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2849 /* If we have a live EPQ query, shut it down */
2850 EvalPlanQualEnd(epqstate);
2851 /* And set/change the plan pointer */
2852 epqstate->plan = subplan;
2853 /* The rowmarks depend on the plan, too */
2854 epqstate->arowMarks = auxrowmarks;
2858 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2860 * NB: passed tuple must be palloc'd; it may get freed later
2863 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2865 EState *estate = epqstate->estate;
2870 * free old test tuple, if any, and store new tuple where relation's scan
2873 if (estate->es_epqTuple[rti - 1] != NULL)
2874 heap_freetuple(estate->es_epqTuple[rti - 1]);
2875 estate->es_epqTuple[rti - 1] = tuple;
2876 estate->es_epqTupleSet[rti - 1] = true;
2880 * Fetch back the current test tuple (if any) for the specified RTI
2883 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2885 EState *estate = epqstate->estate;
2889 return estate->es_epqTuple[rti - 1];
2893 * Fetch the current row values for any non-locked relations that need
2894 * to be scanned by an EvalPlanQual operation. origslot must have been set
2895 * to contain the current result row (top-level row) that we need to recheck.
2898 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2902 Assert(epqstate->origslot != NULL);
2904 foreach(l, epqstate->arowMarks)
2906 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2907 ExecRowMark *erm = aerm->rowmark;
2910 HeapTupleData tuple;
2912 if (RowMarkRequiresRowShareLock(erm->markType))
2913 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2915 /* clear any leftover test tuple for this rel */
2916 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2918 /* if child rel, must check whether it produced this row */
2919 if (erm->rti != erm->prti)
2923 datum = ExecGetJunkAttribute(epqstate->origslot,
2926 /* non-locked rels could be on the inside of outer joins */
2929 tableoid = DatumGetObjectId(datum);
2931 Assert(OidIsValid(erm->relid));
2932 if (tableoid != erm->relid)
2934 /* this child is inactive right now */
2939 if (erm->markType == ROW_MARK_REFERENCE)
2941 HeapTuple copyTuple;
2943 Assert(erm->relation != NULL);
2945 /* fetch the tuple's ctid */
2946 datum = ExecGetJunkAttribute(epqstate->origslot,
2949 /* non-locked rels could be on the inside of outer joins */
2953 /* fetch requests on foreign tables must be passed to their FDW */
2954 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2956 FdwRoutine *fdwroutine;
2957 bool updated = false;
2959 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2960 /* this should have been checked already, but let's be safe */
2961 if (fdwroutine->RefetchForeignRow == NULL)
2963 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2964 errmsg("cannot lock rows in foreign table \"%s\"",
2965 RelationGetRelationName(erm->relation))));
2966 copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2970 if (copyTuple == NULL)
2971 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2974 * Ideally we'd insist on updated == false here, but that
2975 * assumes that FDWs can track that exactly, which they might
2976 * not be able to. So just ignore the flag.
2981 /* ordinary table, fetch the tuple */
2984 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2985 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2987 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2989 if (HeapTupleHeaderGetNatts(tuple.t_data) <
2990 RelationGetDescr(erm->relation)->natts)
2992 copyTuple = heap_expand_tuple(&tuple,
2993 RelationGetDescr(erm->relation));
2997 /* successful, copy tuple */
2998 copyTuple = heap_copytuple(&tuple);
3000 ReleaseBuffer(buffer);
3004 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
3010 Assert(erm->markType == ROW_MARK_COPY);
3012 /* fetch the whole-row Var for the relation */
3013 datum = ExecGetJunkAttribute(epqstate->origslot,
3016 /* non-locked rels could be on the inside of outer joins */
3019 td = DatumGetHeapTupleHeader(datum);
3021 /* build a temporary HeapTuple control structure */
3022 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
3024 /* relation might be a foreign table, if so provide tableoid */
3025 tuple.t_tableOid = erm->relid;
3026 /* also copy t_ctid in case there's valid data there */
3027 tuple.t_self = td->t_ctid;
3029 /* copy and store tuple */
3030 EvalPlanQualSetTuple(epqstate, erm->rti,
3031 heap_copytuple(&tuple));
3037 * Fetch the next row (if any) from EvalPlanQual testing
3039 * (In practice, there should never be more than one row...)
3042 EvalPlanQualNext(EPQState *epqstate)
3044 MemoryContext oldcontext;
3045 TupleTableSlot *slot;
3047 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
3048 slot = ExecProcNode(epqstate->planstate);
3049 MemoryContextSwitchTo(oldcontext);
3055 * Initialize or reset an EvalPlanQual state tree
3058 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
3060 EState *estate = epqstate->estate;
3064 /* First time through, so create a child EState */
3065 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
3070 * We already have a suitable child EPQ tree, so just reset it.
3072 int rtsize = list_length(parentestate->es_range_table);
3073 PlanState *planstate = epqstate->planstate;
3075 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
3077 /* Recopy current values of parent parameters */
3078 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3082 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3086 /* copy value if any, but not execPlan link */
3087 estate->es_param_exec_vals[i].value =
3088 parentestate->es_param_exec_vals[i].value;
3089 estate->es_param_exec_vals[i].isnull =
3090 parentestate->es_param_exec_vals[i].isnull;
3095 * Mark child plan tree as needing rescan at all scan nodes. The
3096 * first ExecProcNode will take care of actually doing the rescan.
3098 planstate->chgParam = bms_add_member(planstate->chgParam,
3099 epqstate->epqParam);
3104 * Start execution of an EvalPlanQual plan tree.
3106 * This is a cut-down version of ExecutorStart(): we copy some state from
3107 * the top-level estate rather than initializing it fresh.
3110 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
3114 MemoryContext oldcontext;
3117 rtsize = list_length(parentestate->es_range_table);
3119 epqstate->estate = estate = CreateExecutorState();
3121 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3124 * Child EPQ EStates share the parent's copy of unchanging state such as
3125 * the snapshot, rangetable, result-rel info, and external Param info.
3126 * They need their own copies of local state, including a tuple table,
3127 * es_param_exec_vals, etc.
3129 * The ResultRelInfo array management is trickier than it looks. We
3130 * create a fresh array for the child but copy all the content from the
3131 * parent. This is because it's okay for the child to share any
3132 * per-relation state the parent has already created --- but if the child
3133 * sets up any ResultRelInfo fields, such as its own junkfilter, that
3134 * state must *not* propagate back to the parent. (For one thing, the
3135 * pointed-to data is in a memory context that won't last long enough.)
3137 estate->es_direction = ForwardScanDirection;
3138 estate->es_snapshot = parentestate->es_snapshot;
3139 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3140 estate->es_range_table = parentestate->es_range_table;
3141 estate->es_plannedstmt = parentestate->es_plannedstmt;
3142 estate->es_junkFilter = parentestate->es_junkFilter;
3143 estate->es_output_cid = parentestate->es_output_cid;
3144 if (parentestate->es_num_result_relations > 0)
3146 int numResultRelations = parentestate->es_num_result_relations;
3147 ResultRelInfo *resultRelInfos;
3149 resultRelInfos = (ResultRelInfo *)
3150 palloc(numResultRelations * sizeof(ResultRelInfo));
3151 memcpy(resultRelInfos, parentestate->es_result_relations,
3152 numResultRelations * sizeof(ResultRelInfo));
3153 estate->es_result_relations = resultRelInfos;
3154 estate->es_num_result_relations = numResultRelations;
3156 /* es_result_relation_info must NOT be copied */
3157 /* es_trig_target_relations must NOT be copied */
3158 estate->es_rowMarks = parentestate->es_rowMarks;
3159 estate->es_top_eflags = parentestate->es_top_eflags;
3160 estate->es_instrument = parentestate->es_instrument;
3161 /* es_auxmodifytables must NOT be copied */
3164 * The external param list is simply shared from parent. The internal
3165 * param workspace has to be local state, but we copy the initial values
3166 * from the parent, so as to have access to any param values that were
3167 * already set from other parts of the parent's plan tree.
3169 estate->es_param_list_info = parentestate->es_param_list_info;
3170 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3174 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3175 estate->es_param_exec_vals = (ParamExecData *)
3176 palloc0(i * sizeof(ParamExecData));
3179 /* copy value if any, but not execPlan link */
3180 estate->es_param_exec_vals[i].value =
3181 parentestate->es_param_exec_vals[i].value;
3182 estate->es_param_exec_vals[i].isnull =
3183 parentestate->es_param_exec_vals[i].isnull;
3188 * Each EState must have its own es_epqScanDone state, but if we have
3189 * nested EPQ checks they should share es_epqTuple arrays. This allows
3190 * sub-rechecks to inherit the values being examined by an outer recheck.
3192 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3193 if (parentestate->es_epqTuple != NULL)
3195 estate->es_epqTuple = parentestate->es_epqTuple;
3196 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3200 estate->es_epqTuple = (HeapTuple *)
3201 palloc0(rtsize * sizeof(HeapTuple));
3202 estate->es_epqTupleSet = (bool *)
3203 palloc0(rtsize * sizeof(bool));
3207 * Each estate also has its own tuple table.
3209 estate->es_tupleTable = NIL;
3212 * Initialize private state information for each SubPlan. We must do this
3213 * before running ExecInitNode on the main query tree, since
3214 * ExecInitSubPlan expects to be able to find these entries. Some of the
3215 * SubPlans might not be used in the part of the plan tree we intend to
3216 * run, but since it's not easy to tell which, we just initialize them
3219 Assert(estate->es_subplanstates == NIL);
3220 foreach(l, parentestate->es_plannedstmt->subplans)
3222 Plan *subplan = (Plan *) lfirst(l);
3223 PlanState *subplanstate;
3225 subplanstate = ExecInitNode(subplan, estate, 0);
3226 estate->es_subplanstates = lappend(estate->es_subplanstates,
3231 * Initialize the private state information for all the nodes in the part
3232 * of the plan tree we need to run. This opens files, allocates storage
3233 * and leaves us ready to start processing tuples.
3235 epqstate->planstate = ExecInitNode(planTree, estate, 0);
3237 MemoryContextSwitchTo(oldcontext);
3241 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
3242 * or if we are done with the current EPQ child.
3244 * This is a cut-down version of ExecutorEnd(); basically we want to do most
3245 * of the normal cleanup, but *not* close result relations (which we are
3246 * just sharing from the outer query). We do, however, have to close any
3247 * trigger target relations that got opened, since those are not shared.
3248 * (There probably shouldn't be any of the latter, but just in case...)
3251 EvalPlanQualEnd(EPQState *epqstate)
3253 EState *estate = epqstate->estate;
3254 MemoryContext oldcontext;
3258 return; /* idle, so nothing to do */
3260 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3262 ExecEndNode(epqstate->planstate);
3264 foreach(l, estate->es_subplanstates)
3266 PlanState *subplanstate = (PlanState *) lfirst(l);
3268 ExecEndNode(subplanstate);
3271 /* throw away the per-estate tuple table */
3272 ExecResetTupleTable(estate->es_tupleTable, false);
3274 /* close any trigger target relations attached to this EState */
3275 ExecCleanUpTriggerState(estate);
3277 MemoryContextSwitchTo(oldcontext);
3279 FreeExecutorState(estate);
3281 /* Mark EPQState idle */
3282 epqstate->estate = NULL;
3283 epqstate->planstate = NULL;
3284 epqstate->origslot = NULL;