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/pg_publication.h"
46 #include "commands/matview.h"
47 #include "commands/trigger.h"
48 #include "executor/execdebug.h"
49 #include "foreign/fdwapi.h"
50 #include "mb/pg_wchar.h"
51 #include "miscadmin.h"
52 #include "optimizer/clauses.h"
53 #include "parser/parsetree.h"
54 #include "rewrite/rewriteManip.h"
55 #include "storage/bufmgr.h"
56 #include "storage/lmgr.h"
57 #include "tcop/utility.h"
58 #include "utils/acl.h"
59 #include "utils/lsyscache.h"
60 #include "utils/memutils.h"
61 #include "utils/partcache.h"
62 #include "utils/rls.h"
63 #include "utils/ruleutils.h"
64 #include "utils/snapmgr.h"
65 #include "utils/tqual.h"
68 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
69 ExecutorStart_hook_type ExecutorStart_hook = NULL;
70 ExecutorRun_hook_type ExecutorRun_hook = NULL;
71 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
72 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
74 /* Hook for plugin to get control in ExecCheckRTPerms() */
75 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
77 /* decls for local routines only used within this module */
78 static void InitPlan(QueryDesc *queryDesc, int eflags);
79 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
80 static void ExecPostprocessPlan(EState *estate);
81 static void ExecEndPlan(PlanState *planstate, EState *estate);
82 static void ExecutePlan(EState *estate, PlanState *planstate,
83 bool use_parallel_mode,
87 ScanDirection direction,
90 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
91 static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
92 Bitmapset *modifiedCols,
93 AclMode requiredPerms);
94 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
95 static char *ExecBuildSlotValueDescription(Oid reloid,
98 Bitmapset *modifiedCols,
100 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
104 * Note that GetUpdatedColumns() also exists in commands/trigger.c. There does
105 * not appear to be any good header to put it into, given the structures that
106 * it uses, so we let them be duplicated. Be sure to update both if one needs
107 * to be changed, however.
109 #define GetInsertedColumns(relinfo, estate) \
110 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
111 #define GetUpdatedColumns(relinfo, estate) \
112 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
114 /* end of local decls */
117 /* ----------------------------------------------------------------
120 * This routine must be called at the beginning of any execution of any
123 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
124 * only because some places use QueryDescs for utility commands). The tupDesc
125 * field of the QueryDesc is filled in to describe the tuples that will be
126 * returned, and the internal fields (estate and planstate) are set up.
128 * eflags contains flag bits as described in executor.h.
130 * NB: the CurrentMemoryContext when this is called will become the parent
131 * of the per-query context used for this Executor invocation.
133 * We provide a function hook variable that lets loadable plugins
134 * get control when ExecutorStart is called. Such a plugin would
135 * normally call standard_ExecutorStart().
137 * ----------------------------------------------------------------
140 ExecutorStart(QueryDesc *queryDesc, int eflags)
142 if (ExecutorStart_hook)
143 (*ExecutorStart_hook) (queryDesc, eflags);
145 standard_ExecutorStart(queryDesc, eflags);
149 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
152 MemoryContext oldcontext;
154 /* sanity checks: queryDesc must not be started already */
155 Assert(queryDesc != NULL);
156 Assert(queryDesc->estate == NULL);
159 * If the transaction is read-only, we need to check if any writes are
160 * planned to non-temporary tables. EXPLAIN is considered read-only.
162 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
163 * would require (a) storing the combocid hash in shared memory, rather
164 * than synchronizing it just once at the start of parallelism, and (b) an
165 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
166 * INSERT may have no such troubles, but we forbid it to simplify the
169 * We have lower-level defenses in CommandCounterIncrement and elsewhere
170 * against performing unsafe operations in parallel mode, but this gives a
171 * more user-friendly error message.
173 if ((XactReadOnly || IsInParallelMode()) &&
174 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
175 ExecCheckXactReadOnly(queryDesc->plannedstmt);
178 * Build EState, switch into per-query memory context for startup.
180 estate = CreateExecutorState();
181 queryDesc->estate = estate;
183 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
186 * Fill in external parameters, if any, from queryDesc; and allocate
187 * workspace for internal parameters
189 estate->es_param_list_info = queryDesc->params;
191 if (queryDesc->plannedstmt->paramExecTypes != NIL)
195 nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
196 estate->es_param_exec_vals = (ParamExecData *)
197 palloc0(nParamExec * sizeof(ParamExecData));
200 estate->es_sourceText = queryDesc->sourceText;
203 * Fill in the query environment, if any, from queryDesc.
205 estate->es_queryEnv = queryDesc->queryEnv;
208 * If non-read-only query, set the command ID to mark output tuples with
210 switch (queryDesc->operation)
215 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
218 if (queryDesc->plannedstmt->rowMarks != NIL ||
219 queryDesc->plannedstmt->hasModifyingCTE)
220 estate->es_output_cid = GetCurrentCommandId(true);
223 * A SELECT without modifying CTEs can't possibly queue triggers,
224 * so force skip-triggers mode. This is just a marginal efficiency
225 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
226 * all that expensive, but we might as well do it.
228 if (!queryDesc->plannedstmt->hasModifyingCTE)
229 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
235 estate->es_output_cid = GetCurrentCommandId(true);
239 elog(ERROR, "unrecognized operation code: %d",
240 (int) queryDesc->operation);
245 * Copy other important information into the EState
247 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
248 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
249 estate->es_top_eflags = eflags;
250 estate->es_instrument = queryDesc->instrument_options;
251 estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
254 * Set up an AFTER-trigger statement context, unless told not to, or
255 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
257 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
258 AfterTriggerBeginQuery();
261 * Initialize the plan state tree
263 InitPlan(queryDesc, eflags);
265 MemoryContextSwitchTo(oldcontext);
268 /* ----------------------------------------------------------------
271 * This is the main routine of the executor module. It accepts
272 * the query descriptor from the traffic cop and executes the
275 * ExecutorStart must have been called already.
277 * If direction is NoMovementScanDirection then nothing is done
278 * except to start up/shut down the destination. Otherwise,
279 * we retrieve up to 'count' tuples in the specified direction.
281 * Note: count = 0 is interpreted as no portal limit, i.e., run to
282 * completion. Also note that the count limit is only applied to
283 * retrieved tuples, not for instance to those inserted/updated/deleted
284 * by a ModifyTable plan node.
286 * There is no return value, but output tuples (if any) are sent to
287 * the destination receiver specified in the QueryDesc; and the number
288 * of tuples processed at the top level can be found in
289 * estate->es_processed.
291 * We provide a function hook variable that lets loadable plugins
292 * get control when ExecutorRun is called. Such a plugin would
293 * normally call standard_ExecutorRun().
295 * ----------------------------------------------------------------
298 ExecutorRun(QueryDesc *queryDesc,
299 ScanDirection direction, uint64 count,
302 if (ExecutorRun_hook)
303 (*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
305 standard_ExecutorRun(queryDesc, direction, count, execute_once);
309 standard_ExecutorRun(QueryDesc *queryDesc,
310 ScanDirection direction, uint64 count, bool execute_once)
316 MemoryContext oldcontext;
319 Assert(queryDesc != NULL);
321 estate = queryDesc->estate;
323 Assert(estate != NULL);
324 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
327 * Switch into per-query memory context
329 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
331 /* Allow instrumentation of Executor overall runtime */
332 if (queryDesc->totaltime)
333 InstrStartNode(queryDesc->totaltime);
336 * extract information from the query descriptor and the query feature.
338 operation = queryDesc->operation;
339 dest = queryDesc->dest;
342 * startup tuple receiver, if we will be emitting tuples
344 estate->es_processed = 0;
345 estate->es_lastoid = InvalidOid;
347 sendTuples = (operation == CMD_SELECT ||
348 queryDesc->plannedstmt->hasReturning);
351 dest->rStartup(dest, operation, queryDesc->tupDesc);
356 if (!ScanDirectionIsNoMovement(direction))
358 if (execute_once && queryDesc->already_executed)
359 elog(ERROR, "can't re-execute query flagged for single execution");
360 queryDesc->already_executed = true;
363 queryDesc->planstate,
364 queryDesc->plannedstmt->parallelModeNeeded,
374 * shutdown tuple receiver, if we started it
377 dest->rShutdown(dest);
379 if (queryDesc->totaltime)
380 InstrStopNode(queryDesc->totaltime, estate->es_processed);
382 MemoryContextSwitchTo(oldcontext);
385 /* ----------------------------------------------------------------
388 * This routine must be called after the last ExecutorRun call.
389 * It performs cleanup such as firing AFTER triggers. It is
390 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
391 * include these actions in the total runtime.
393 * We provide a function hook variable that lets loadable plugins
394 * get control when ExecutorFinish is called. Such a plugin would
395 * normally call standard_ExecutorFinish().
397 * ----------------------------------------------------------------
400 ExecutorFinish(QueryDesc *queryDesc)
402 if (ExecutorFinish_hook)
403 (*ExecutorFinish_hook) (queryDesc);
405 standard_ExecutorFinish(queryDesc);
409 standard_ExecutorFinish(QueryDesc *queryDesc)
412 MemoryContext oldcontext;
415 Assert(queryDesc != NULL);
417 estate = queryDesc->estate;
419 Assert(estate != NULL);
420 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
422 /* This should be run once and only once per Executor instance */
423 Assert(!estate->es_finished);
425 /* Switch into per-query memory context */
426 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
428 /* Allow instrumentation of Executor overall runtime */
429 if (queryDesc->totaltime)
430 InstrStartNode(queryDesc->totaltime);
432 /* Run ModifyTable nodes to completion */
433 ExecPostprocessPlan(estate);
435 /* Execute queued AFTER triggers, unless told not to */
436 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
437 AfterTriggerEndQuery(estate);
439 if (queryDesc->totaltime)
440 InstrStopNode(queryDesc->totaltime, 0);
442 MemoryContextSwitchTo(oldcontext);
444 estate->es_finished = true;
447 /* ----------------------------------------------------------------
450 * This routine must be called at the end of execution of any
453 * We provide a function hook variable that lets loadable plugins
454 * get control when ExecutorEnd is called. Such a plugin would
455 * normally call standard_ExecutorEnd().
457 * ----------------------------------------------------------------
460 ExecutorEnd(QueryDesc *queryDesc)
462 if (ExecutorEnd_hook)
463 (*ExecutorEnd_hook) (queryDesc);
465 standard_ExecutorEnd(queryDesc);
469 standard_ExecutorEnd(QueryDesc *queryDesc)
472 MemoryContext oldcontext;
475 Assert(queryDesc != NULL);
477 estate = queryDesc->estate;
479 Assert(estate != NULL);
482 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
483 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
484 * might forget to call it.
486 Assert(estate->es_finished ||
487 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
490 * Switch into per-query memory context to run ExecEndPlan
492 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
494 ExecEndPlan(queryDesc->planstate, estate);
496 /* do away with our snapshots */
497 UnregisterSnapshot(estate->es_snapshot);
498 UnregisterSnapshot(estate->es_crosscheck_snapshot);
501 * Must switch out of context before destroying it
503 MemoryContextSwitchTo(oldcontext);
506 * Release EState and per-query memory context. This should release
507 * everything the executor has allocated.
509 FreeExecutorState(estate);
511 /* Reset queryDesc fields that no longer point to anything */
512 queryDesc->tupDesc = NULL;
513 queryDesc->estate = NULL;
514 queryDesc->planstate = NULL;
515 queryDesc->totaltime = NULL;
518 /* ----------------------------------------------------------------
521 * This routine may be called on an open queryDesc to rewind it
523 * ----------------------------------------------------------------
526 ExecutorRewind(QueryDesc *queryDesc)
529 MemoryContext oldcontext;
532 Assert(queryDesc != NULL);
534 estate = queryDesc->estate;
536 Assert(estate != NULL);
538 /* It's probably not sensible to rescan updating queries */
539 Assert(queryDesc->operation == CMD_SELECT);
542 * Switch into per-query memory context
544 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
549 ExecReScan(queryDesc->planstate);
551 MemoryContextSwitchTo(oldcontext);
557 * Check access permissions for all relations listed in a range table.
559 * Returns true if permissions are adequate. Otherwise, throws an appropriate
560 * error if ereport_on_violation is true, or simply returns false otherwise.
562 * Note that this does NOT address row level security policies (aka: RLS). If
563 * rows will be returned to the user as a result of this permission check
564 * passing, then RLS also needs to be consulted (and check_enable_rls()).
566 * See rewrite/rowsecurity.c.
569 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
574 foreach(l, rangeTable)
576 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
578 result = ExecCheckRTEPerms(rte);
581 Assert(rte->rtekind == RTE_RELATION);
582 if (ereport_on_violation)
583 aclcheck_error(ACLCHECK_NO_PRIV, get_relkind_objtype(get_rel_relkind(rte->relid)),
584 get_rel_name(rte->relid));
589 if (ExecutorCheckPerms_hook)
590 result = (*ExecutorCheckPerms_hook) (rangeTable,
591 ereport_on_violation);
597 * Check access permissions for a single RTE.
600 ExecCheckRTEPerms(RangeTblEntry *rte)
602 AclMode requiredPerms;
604 AclMode remainingPerms;
609 * Only plain-relation RTEs need to be checked here. Function RTEs are
610 * checked when the function is prepared for execution. Join, subquery,
611 * and special RTEs need no checks.
613 if (rte->rtekind != RTE_RELATION)
617 * No work if requiredPerms is empty.
619 requiredPerms = rte->requiredPerms;
620 if (requiredPerms == 0)
626 * userid to check as: current user unless we have a setuid indication.
628 * Note: GetUserId() is presently fast enough that there's no harm in
629 * calling it separately for each RTE. If that stops being true, we could
630 * call it once in ExecCheckRTPerms and pass the userid down from there.
631 * But for now, no need for the extra clutter.
633 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
636 * We must have *all* the requiredPerms bits, but some of the bits can be
637 * satisfied from column-level rather than relation-level permissions.
638 * First, remove any bits that are satisfied by relation permissions.
640 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
641 remainingPerms = requiredPerms & ~relPerms;
642 if (remainingPerms != 0)
647 * If we lack any permissions that exist only as relation permissions,
648 * we can fail straight away.
650 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
654 * Check to see if we have the needed privileges at column level.
656 * Note: failures just report a table-level error; it would be nicer
657 * to report a column-level error if we have some but not all of the
660 if (remainingPerms & ACL_SELECT)
663 * When the query doesn't explicitly reference any columns (for
664 * example, SELECT COUNT(*) FROM table), allow the query if we
665 * have SELECT on any column of the rel, as per SQL spec.
667 if (bms_is_empty(rte->selectedCols))
669 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
670 ACLMASK_ANY) != ACLCHECK_OK)
674 while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
676 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
677 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
679 if (attno == InvalidAttrNumber)
681 /* Whole-row reference, must have priv on all cols */
682 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
683 ACLMASK_ALL) != ACLCHECK_OK)
688 if (pg_attribute_aclcheck(relOid, attno, userid,
689 ACL_SELECT) != ACLCHECK_OK)
696 * Basically the same for the mod columns, for both INSERT and UPDATE
697 * privilege as specified by remainingPerms.
699 if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
705 if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
715 * ExecCheckRTEPermsModified
716 * Check INSERT or UPDATE access permissions for a single RTE (these
717 * are processed uniformly).
720 ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
721 AclMode requiredPerms)
726 * When the query doesn't explicitly update any columns, allow the query
727 * if we have permission on any column of the rel. This is to handle
728 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
730 if (bms_is_empty(modifiedCols))
732 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
733 ACLMASK_ANY) != ACLCHECK_OK)
737 while ((col = bms_next_member(modifiedCols, col)) >= 0)
739 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
740 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
742 if (attno == InvalidAttrNumber)
744 /* whole-row reference can't happen here */
745 elog(ERROR, "whole-row update is not implemented");
749 if (pg_attribute_aclcheck(relOid, attno, userid,
750 requiredPerms) != ACLCHECK_OK)
758 * Check that the query does not imply any writes to non-temp tables;
759 * unless we're in parallel mode, in which case don't even allow writes
762 * Note: in a Hot Standby this would need to reject writes to temp
763 * tables just as we do in parallel mode; but an HS standby can't have created
764 * any temp tables in the first place, so no need to check that.
767 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
772 * Fail if write permissions are requested in parallel mode for table
773 * (temp or non-temp), otherwise fail for any non-temp table.
775 foreach(l, plannedstmt->rtable)
777 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
779 if (rte->rtekind != RTE_RELATION)
782 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
785 if (isTempNamespace(get_rel_namespace(rte->relid)))
788 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
791 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
792 PreventCommandIfParallelMode(CreateCommandTag((Node *) plannedstmt));
796 /* ----------------------------------------------------------------
799 * Initializes the query plan: open files, allocate storage
800 * and start up the rule manager
801 * ----------------------------------------------------------------
804 InitPlan(QueryDesc *queryDesc, int eflags)
806 CmdType operation = queryDesc->operation;
807 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
808 Plan *plan = plannedstmt->planTree;
809 List *rangeTable = plannedstmt->rtable;
810 EState *estate = queryDesc->estate;
811 PlanState *planstate;
817 * Do permissions checks
819 ExecCheckRTPerms(rangeTable, true);
822 * initialize the node's execution state
824 estate->es_range_table = rangeTable;
825 estate->es_plannedstmt = plannedstmt;
828 * initialize result relation stuff, and open/lock the result rels.
830 * We must do this before initializing the plan tree, else we might try to
831 * do a lock upgrade if a result rel is also a source rel.
833 if (plannedstmt->resultRelations)
835 List *resultRelations = plannedstmt->resultRelations;
836 int numResultRelations = list_length(resultRelations);
837 ResultRelInfo *resultRelInfos;
838 ResultRelInfo *resultRelInfo;
840 resultRelInfos = (ResultRelInfo *)
841 palloc(numResultRelations * sizeof(ResultRelInfo));
842 resultRelInfo = resultRelInfos;
843 foreach(l, resultRelations)
845 Index resultRelationIndex = lfirst_int(l);
846 Oid resultRelationOid;
847 Relation resultRelation;
849 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
850 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
852 InitResultRelInfo(resultRelInfo,
856 estate->es_instrument);
859 estate->es_result_relations = resultRelInfos;
860 estate->es_num_result_relations = numResultRelations;
861 /* es_result_relation_info is NULL except when within ModifyTable */
862 estate->es_result_relation_info = NULL;
865 * In the partitioned result relation case, lock the non-leaf result
866 * relations too. A subset of these are the roots of respective
867 * partitioned tables, for which we also allocate ResultRelInfos.
869 estate->es_root_result_relations = NULL;
870 estate->es_num_root_result_relations = 0;
871 if (plannedstmt->nonleafResultRelations)
873 int num_roots = list_length(plannedstmt->rootResultRelations);
876 * Firstly, build ResultRelInfos for all the partitioned table
877 * roots, because we will need them to fire the statement-level
880 resultRelInfos = (ResultRelInfo *)
881 palloc(num_roots * sizeof(ResultRelInfo));
882 resultRelInfo = resultRelInfos;
883 foreach(l, plannedstmt->rootResultRelations)
885 Index resultRelIndex = lfirst_int(l);
887 Relation resultRelDesc;
889 resultRelOid = getrelid(resultRelIndex, rangeTable);
890 resultRelDesc = heap_open(resultRelOid, RowExclusiveLock);
891 InitResultRelInfo(resultRelInfo,
895 estate->es_instrument);
899 estate->es_root_result_relations = resultRelInfos;
900 estate->es_num_root_result_relations = num_roots;
902 /* Simply lock the rest of them. */
903 foreach(l, plannedstmt->nonleafResultRelations)
905 Index resultRelIndex = lfirst_int(l);
907 /* We locked the roots above. */
908 if (!list_member_int(plannedstmt->rootResultRelations,
910 LockRelationOid(getrelid(resultRelIndex, rangeTable),
918 * if no result relation, then set state appropriately
920 estate->es_result_relations = NULL;
921 estate->es_num_result_relations = 0;
922 estate->es_result_relation_info = NULL;
923 estate->es_root_result_relations = NULL;
924 estate->es_num_root_result_relations = 0;
928 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
929 * before we initialize the plan tree, else we'd be risking lock upgrades.
930 * While we are at it, build the ExecRowMark list. Any partitioned child
931 * tables are ignored here (because isParent=true) and will be locked by
932 * the first Append or MergeAppend node that references them. (Note that
933 * the RowMarks corresponding to partitioned child tables are present in
934 * the same list as the rest, i.e., plannedstmt->rowMarks.)
936 estate->es_rowMarks = NIL;
937 foreach(l, plannedstmt->rowMarks)
939 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
944 /* ignore "parent" rowmarks; they are irrelevant at runtime */
948 /* get relation's OID (will produce InvalidOid if subquery) */
949 relid = getrelid(rc->rti, rangeTable);
952 * If you change the conditions under which rel locks are acquired
953 * here, be sure to adjust ExecOpenScanRelation to match.
955 switch (rc->markType)
957 case ROW_MARK_EXCLUSIVE:
958 case ROW_MARK_NOKEYEXCLUSIVE:
960 case ROW_MARK_KEYSHARE:
961 relation = heap_open(relid, RowShareLock);
963 case ROW_MARK_REFERENCE:
964 relation = heap_open(relid, AccessShareLock);
967 /* no physical table access is required */
971 elog(ERROR, "unrecognized markType: %d", rc->markType);
972 relation = NULL; /* keep compiler quiet */
976 /* Check that relation is a legal target for marking */
978 CheckValidRowMarkRel(relation, rc->markType);
980 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
981 erm->relation = relation;
984 erm->prti = rc->prti;
985 erm->rowmarkId = rc->rowmarkId;
986 erm->markType = rc->markType;
987 erm->strength = rc->strength;
988 erm->waitPolicy = rc->waitPolicy;
989 erm->ermActive = false;
990 ItemPointerSetInvalid(&(erm->curCtid));
991 erm->ermExtra = NULL;
992 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
996 * Initialize the executor's tuple table to empty.
998 estate->es_tupleTable = NIL;
999 estate->es_trig_tuple_slot = NULL;
1000 estate->es_trig_oldtup_slot = NULL;
1001 estate->es_trig_newtup_slot = NULL;
1003 /* mark EvalPlanQual not active */
1004 estate->es_epqTuple = NULL;
1005 estate->es_epqTupleSet = NULL;
1006 estate->es_epqScanDone = NULL;
1009 * Initialize private state information for each SubPlan. We must do this
1010 * before running ExecInitNode on the main query tree, since
1011 * ExecInitSubPlan expects to be able to find these entries.
1013 Assert(estate->es_subplanstates == NIL);
1014 i = 1; /* subplan indices count from 1 */
1015 foreach(l, plannedstmt->subplans)
1017 Plan *subplan = (Plan *) lfirst(l);
1018 PlanState *subplanstate;
1022 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
1023 * it is a parameterless subplan (not initplan), we suggest that it be
1024 * prepared to handle REWIND efficiently; otherwise there is no need.
1027 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
1028 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
1029 sp_eflags |= EXEC_FLAG_REWIND;
1031 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
1033 estate->es_subplanstates = lappend(estate->es_subplanstates,
1040 * Initialize the private state information for all the nodes in the query
1041 * tree. This opens files, allocates storage and leaves us ready to start
1042 * processing tuples.
1044 planstate = ExecInitNode(plan, estate, eflags);
1047 * Get the tuple descriptor describing the type of tuples to return.
1049 tupType = ExecGetResultType(planstate);
1052 * Initialize the junk filter if needed. SELECT queries need a filter if
1053 * there are any junk attrs in the top-level tlist.
1055 if (operation == CMD_SELECT)
1057 bool junk_filter_needed = false;
1060 foreach(tlist, plan->targetlist)
1062 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1066 junk_filter_needed = true;
1071 if (junk_filter_needed)
1075 j = ExecInitJunkFilter(planstate->plan->targetlist,
1077 ExecInitExtraTupleSlot(estate, NULL));
1078 estate->es_junkFilter = j;
1080 /* Want to return the cleaned tuple type */
1081 tupType = j->jf_cleanTupType;
1085 queryDesc->tupDesc = tupType;
1086 queryDesc->planstate = planstate;
1090 * Check that a proposed result relation is a legal target for the operation
1092 * Generally the parser and/or planner should have noticed any such mistake
1093 * already, but let's make sure.
1095 * Note: when changing this function, you probably also need to look at
1096 * CheckValidRowMarkRel.
1099 CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
1101 Relation resultRel = resultRelInfo->ri_RelationDesc;
1102 TriggerDesc *trigDesc = resultRel->trigdesc;
1103 FdwRoutine *fdwroutine;
1105 switch (resultRel->rd_rel->relkind)
1107 case RELKIND_RELATION:
1108 case RELKIND_PARTITIONED_TABLE:
1109 CheckCmdReplicaIdentity(resultRel, operation);
1111 case RELKIND_SEQUENCE:
1113 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1114 errmsg("cannot change sequence \"%s\"",
1115 RelationGetRelationName(resultRel))));
1117 case RELKIND_TOASTVALUE:
1119 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1120 errmsg("cannot change TOAST relation \"%s\"",
1121 RelationGetRelationName(resultRel))));
1126 * Okay only if there's a suitable INSTEAD OF trigger. Messages
1127 * here should match rewriteHandler.c's rewriteTargetView, except
1128 * that we omit errdetail because we haven't got the information
1129 * handy (and given that we really shouldn't get here anyway, it's
1130 * not worth great exertion to get).
1135 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1137 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1138 errmsg("cannot insert into view \"%s\"",
1139 RelationGetRelationName(resultRel)),
1140 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1143 if (!trigDesc || !trigDesc->trig_update_instead_row)
1145 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1146 errmsg("cannot update view \"%s\"",
1147 RelationGetRelationName(resultRel)),
1148 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1151 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1153 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1154 errmsg("cannot delete from view \"%s\"",
1155 RelationGetRelationName(resultRel)),
1156 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1159 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1163 case RELKIND_MATVIEW:
1164 if (!MatViewIncrementalMaintenanceIsEnabled())
1166 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1167 errmsg("cannot change materialized view \"%s\"",
1168 RelationGetRelationName(resultRel))));
1170 case RELKIND_FOREIGN_TABLE:
1171 /* Okay only if the FDW supports it */
1172 fdwroutine = resultRelInfo->ri_FdwRoutine;
1176 if (fdwroutine->ExecForeignInsert == NULL)
1178 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1179 errmsg("cannot insert into foreign table \"%s\"",
1180 RelationGetRelationName(resultRel))));
1181 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1182 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1184 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1185 errmsg("foreign table \"%s\" does not allow inserts",
1186 RelationGetRelationName(resultRel))));
1189 if (fdwroutine->ExecForeignUpdate == NULL)
1191 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1192 errmsg("cannot update foreign table \"%s\"",
1193 RelationGetRelationName(resultRel))));
1194 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1195 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1197 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1198 errmsg("foreign table \"%s\" does not allow updates",
1199 RelationGetRelationName(resultRel))));
1202 if (fdwroutine->ExecForeignDelete == NULL)
1204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1205 errmsg("cannot delete from foreign table \"%s\"",
1206 RelationGetRelationName(resultRel))));
1207 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1208 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1210 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1211 errmsg("foreign table \"%s\" does not allow deletes",
1212 RelationGetRelationName(resultRel))));
1215 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1221 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1222 errmsg("cannot change relation \"%s\"",
1223 RelationGetRelationName(resultRel))));
1229 * Check that a proposed rowmark target relation is a legal target
1231 * In most cases parser and/or planner should have noticed this already, but
1232 * they don't cover all cases.
1235 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1237 FdwRoutine *fdwroutine;
1239 switch (rel->rd_rel->relkind)
1241 case RELKIND_RELATION:
1242 case RELKIND_PARTITIONED_TABLE:
1245 case RELKIND_SEQUENCE:
1246 /* Must disallow this because we don't vacuum sequences */
1248 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1249 errmsg("cannot lock rows in sequence \"%s\"",
1250 RelationGetRelationName(rel))));
1252 case RELKIND_TOASTVALUE:
1253 /* We could allow this, but there seems no good reason to */
1255 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1256 errmsg("cannot lock rows in TOAST relation \"%s\"",
1257 RelationGetRelationName(rel))));
1260 /* Should not get here; planner should have expanded the view */
1262 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1263 errmsg("cannot lock rows in view \"%s\"",
1264 RelationGetRelationName(rel))));
1266 case RELKIND_MATVIEW:
1267 /* Allow referencing a matview, but not actual locking clauses */
1268 if (markType != ROW_MARK_REFERENCE)
1270 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1271 errmsg("cannot lock rows in materialized view \"%s\"",
1272 RelationGetRelationName(rel))));
1274 case RELKIND_FOREIGN_TABLE:
1275 /* Okay only if the FDW supports it */
1276 fdwroutine = GetFdwRoutineForRelation(rel, false);
1277 if (fdwroutine->RefetchForeignRow == NULL)
1279 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1280 errmsg("cannot lock rows in foreign table \"%s\"",
1281 RelationGetRelationName(rel))));
1285 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1286 errmsg("cannot lock rows in relation \"%s\"",
1287 RelationGetRelationName(rel))));
1293 * Initialize ResultRelInfo data for one result relation
1295 * Caution: before Postgres 9.1, this function included the relkind checking
1296 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1297 * appropriate. Be sure callers cover those needs.
1300 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1301 Relation resultRelationDesc,
1302 Index resultRelationIndex,
1303 Relation partition_root,
1304 int instrument_options)
1306 List *partition_check = NIL;
1308 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1309 resultRelInfo->type = T_ResultRelInfo;
1310 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1311 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1312 resultRelInfo->ri_NumIndices = 0;
1313 resultRelInfo->ri_IndexRelationDescs = NULL;
1314 resultRelInfo->ri_IndexRelationInfo = NULL;
1315 /* make a copy so as not to depend on relcache info not changing... */
1316 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1317 if (resultRelInfo->ri_TrigDesc)
1319 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1321 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1322 palloc0(n * sizeof(FmgrInfo));
1323 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1324 palloc0(n * sizeof(ExprState *));
1325 if (instrument_options)
1326 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1330 resultRelInfo->ri_TrigFunctions = NULL;
1331 resultRelInfo->ri_TrigWhenExprs = NULL;
1332 resultRelInfo->ri_TrigInstrument = NULL;
1334 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1335 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1337 resultRelInfo->ri_FdwRoutine = NULL;
1339 /* The following fields are set later if needed */
1340 resultRelInfo->ri_FdwState = NULL;
1341 resultRelInfo->ri_usesFdwDirectModify = false;
1342 resultRelInfo->ri_ConstraintExprs = NULL;
1343 resultRelInfo->ri_junkFilter = NULL;
1344 resultRelInfo->ri_projectReturning = NULL;
1345 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1346 resultRelInfo->ri_onConflict = NULL;
1349 * Partition constraint, which also includes the partition constraint of
1350 * all the ancestors that are partitions. Note that it will be checked
1351 * even in the case of tuple-routing where this table is the target leaf
1352 * partition, if there any BR triggers defined on the table. Although
1353 * tuple-routing implicitly preserves the partition constraint of the
1354 * target partition for a given row, the BR triggers may change the row
1355 * such that the constraint is no longer satisfied, which we must fail for
1356 * by checking it explicitly.
1358 * If this is a partitioned table, the partition constraint (if any) of a
1359 * given row will be checked just before performing tuple-routing.
1361 partition_check = RelationGetPartitionQual(resultRelationDesc);
1363 resultRelInfo->ri_PartitionCheck = partition_check;
1364 resultRelInfo->ri_PartitionRoot = partition_root;
1365 resultRelInfo->ri_PartitionReadyForRouting = false;
1369 * ExecGetTriggerResultRel
1371 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1372 * triggers are fired on one of the result relations of the query, and so
1373 * we can just return a member of the es_result_relations array, the
1374 * es_root_result_relations array (if any), or the es_leaf_result_relations
1375 * list (if any). (Note: in self-join situations there might be multiple
1376 * members with the same OID; if so it doesn't matter which one we pick.)
1377 * However, it is sometimes necessary to fire triggers on other relations;
1378 * this happens mainly when an RI update trigger queues additional triggers
1379 * on other relations, which will be processed in the context of the outer
1380 * query. For efficiency's sake, we want to have a ResultRelInfo for those
1381 * triggers too; that can avoid repeated re-opening of the relation. (It
1382 * also provides a way for EXPLAIN ANALYZE to report the runtimes of such
1383 * triggers.) So we make additional ResultRelInfo's as needed, and save them
1384 * in es_trig_target_relations.
1387 ExecGetTriggerResultRel(EState *estate, Oid relid)
1389 ResultRelInfo *rInfo;
1393 MemoryContext oldcontext;
1395 /* First, search through the query result relations */
1396 rInfo = estate->es_result_relations;
1397 nr = estate->es_num_result_relations;
1400 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1405 /* Second, search through the root result relations, if any */
1406 rInfo = estate->es_root_result_relations;
1407 nr = estate->es_num_root_result_relations;
1410 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1417 * Third, search through the result relations that were created during
1418 * tuple routing, if any.
1420 foreach(l, estate->es_tuple_routing_result_relations)
1422 rInfo = (ResultRelInfo *) lfirst(l);
1423 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1426 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1427 foreach(l, estate->es_trig_target_relations)
1429 rInfo = (ResultRelInfo *) lfirst(l);
1430 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1433 /* Nope, so we need a new one */
1436 * Open the target relation's relcache entry. We assume that an
1437 * appropriate lock is still held by the backend from whenever the trigger
1438 * event got queued, so we need take no new lock here. Also, we need not
1439 * recheck the relkind, so no need for CheckValidResultRel.
1441 rel = heap_open(relid, NoLock);
1444 * Make the new entry in the right context.
1446 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1447 rInfo = makeNode(ResultRelInfo);
1448 InitResultRelInfo(rInfo,
1450 0, /* dummy rangetable index */
1452 estate->es_instrument);
1453 estate->es_trig_target_relations =
1454 lappend(estate->es_trig_target_relations, rInfo);
1455 MemoryContextSwitchTo(oldcontext);
1458 * Currently, we don't need any index information in ResultRelInfos used
1459 * only for triggers, so no need to call ExecOpenIndices.
1466 * Close any relations that have been opened by ExecGetTriggerResultRel().
1469 ExecCleanUpTriggerState(EState *estate)
1473 foreach(l, estate->es_trig_target_relations)
1475 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1477 /* Close indices and then the relation itself */
1478 ExecCloseIndices(resultRelInfo);
1479 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1484 * ExecContextForcesOids
1486 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1487 * we need to ensure that result tuples have space for an OID iff they are
1488 * going to be stored into a relation that has OIDs. In other contexts
1489 * we are free to choose whether to leave space for OIDs in result tuples
1490 * (we generally don't want to, but we do if a physical-tlist optimization
1491 * is possible). This routine checks the plan context and returns true if the
1492 * choice is forced, false if the choice is not forced. In the true case,
1493 * *hasoids is set to the required value.
1495 * One reason this is ugly is that all plan nodes in the plan tree will emit
1496 * tuples with space for an OID, though we really only need the topmost node
1497 * to do so. However, node types like Sort don't project new tuples but just
1498 * return their inputs, and in those cases the requirement propagates down
1499 * to the input node. Eventually we might make this code smart enough to
1500 * recognize how far down the requirement really goes, but for now we just
1501 * make all plan nodes do the same thing if the top level forces the choice.
1503 * We assume that if we are generating tuples for INSERT or UPDATE,
1504 * estate->es_result_relation_info is already set up to describe the target
1505 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1506 * the target relations may have OIDs and some not. We have to make the
1507 * decisions on a per-relation basis as we initialize each of the subplans of
1508 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1509 * while initializing each subplan.
1511 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1512 * descriptor available when this code runs; we have to look aside at the
1513 * flags passed to ExecutorStart().
1516 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1518 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1522 Relation rel = ri->ri_RelationDesc;
1526 *hasoids = rel->rd_rel->relhasoids;
1531 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1536 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1545 /* ----------------------------------------------------------------
1546 * ExecPostprocessPlan
1548 * Give plan nodes a final chance to execute before shutdown
1549 * ----------------------------------------------------------------
1552 ExecPostprocessPlan(EState *estate)
1557 * Make sure nodes run forward.
1559 estate->es_direction = ForwardScanDirection;
1562 * Run any secondary ModifyTable nodes to completion, in case the main
1563 * query did not fetch all rows from them. (We do this to ensure that
1564 * such nodes have predictable results.)
1566 foreach(lc, estate->es_auxmodifytables)
1568 PlanState *ps = (PlanState *) lfirst(lc);
1572 TupleTableSlot *slot;
1574 /* Reset the per-output-tuple exprcontext each time */
1575 ResetPerTupleExprContext(estate);
1577 slot = ExecProcNode(ps);
1579 if (TupIsNull(slot))
1585 /* ----------------------------------------------------------------
1588 * Cleans up the query plan -- closes files and frees up storage
1590 * NOTE: we are no longer very worried about freeing storage per se
1591 * in this code; FreeExecutorState should be guaranteed to release all
1592 * memory that needs to be released. What we are worried about doing
1593 * is closing relations and dropping buffer pins. Thus, for example,
1594 * tuple tables must be cleared or dropped to ensure pins are released.
1595 * ----------------------------------------------------------------
1598 ExecEndPlan(PlanState *planstate, EState *estate)
1600 ResultRelInfo *resultRelInfo;
1605 * shut down the node-type-specific query processing
1607 ExecEndNode(planstate);
1612 foreach(l, estate->es_subplanstates)
1614 PlanState *subplanstate = (PlanState *) lfirst(l);
1616 ExecEndNode(subplanstate);
1620 * destroy the executor's tuple table. Actually we only care about
1621 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1622 * the TupleTableSlots, since the containing memory context is about to go
1625 ExecResetTupleTable(estate->es_tupleTable, false);
1628 * close the result relation(s) if any, but hold locks until xact commit.
1630 resultRelInfo = estate->es_result_relations;
1631 for (i = estate->es_num_result_relations; i > 0; i--)
1633 /* Close indices and then the relation itself */
1634 ExecCloseIndices(resultRelInfo);
1635 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1639 /* Close the root target relation(s). */
1640 resultRelInfo = estate->es_root_result_relations;
1641 for (i = estate->es_num_root_result_relations; i > 0; i--)
1643 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1647 /* likewise close any trigger target relations */
1648 ExecCleanUpTriggerState(estate);
1651 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1654 foreach(l, estate->es_rowMarks)
1656 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1659 heap_close(erm->relation, NoLock);
1663 /* ----------------------------------------------------------------
1666 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1667 * moving in the specified direction.
1669 * Runs to completion if numberTuples is 0
1671 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1673 * ----------------------------------------------------------------
1676 ExecutePlan(EState *estate,
1677 PlanState *planstate,
1678 bool use_parallel_mode,
1681 uint64 numberTuples,
1682 ScanDirection direction,
1686 TupleTableSlot *slot;
1687 uint64 current_tuple_count;
1690 * initialize local variables
1692 current_tuple_count = 0;
1695 * Set the direction.
1697 estate->es_direction = direction;
1700 * If the plan might potentially be executed multiple times, we must force
1701 * it to run without parallelism, because we might exit early.
1704 use_parallel_mode = false;
1706 estate->es_use_parallel_mode = use_parallel_mode;
1707 if (use_parallel_mode)
1708 EnterParallelMode();
1711 * Loop until we've processed the proper number of tuples from the plan.
1715 /* Reset the per-output-tuple exprcontext */
1716 ResetPerTupleExprContext(estate);
1719 * Execute the plan and obtain a tuple
1721 slot = ExecProcNode(planstate);
1724 * if the tuple is null, then we assume there is nothing more to
1725 * process so we just end the loop...
1727 if (TupIsNull(slot))
1729 /* Allow nodes to release or shut down resources. */
1730 (void) ExecShutdownNode(planstate);
1735 * If we have a junk filter, then project a new tuple with the junk
1738 * Store this new "clean" tuple in the junkfilter's resultSlot.
1739 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1740 * because that tuple slot has the wrong descriptor.)
1742 if (estate->es_junkFilter != NULL)
1743 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1746 * If we are supposed to send the tuple somewhere, do so. (In
1747 * practice, this is probably always the case at this point.)
1752 * If we are not able to send the tuple, we assume the destination
1753 * has closed and no more tuples can be sent. If that's the case,
1756 if (!dest->receiveSlot(slot, dest))
1761 * Count tuples processed, if this is a SELECT. (For other operation
1762 * types, the ModifyTable plan node must count the appropriate
1765 if (operation == CMD_SELECT)
1766 (estate->es_processed)++;
1769 * check our tuple count.. if we've processed the proper number then
1770 * quit, else loop again and process more tuples. Zero numberTuples
1773 current_tuple_count++;
1774 if (numberTuples && numberTuples == current_tuple_count)
1776 /* Allow nodes to release or shut down resources. */
1777 (void) ExecShutdownNode(planstate);
1782 if (use_parallel_mode)
1788 * ExecRelCheck --- check that tuple meets constraints for result relation
1790 * Returns NULL if OK, else name of failed check constraint
1793 ExecRelCheck(ResultRelInfo *resultRelInfo,
1794 TupleTableSlot *slot, EState *estate)
1796 Relation rel = resultRelInfo->ri_RelationDesc;
1797 int ncheck = rel->rd_att->constr->num_check;
1798 ConstrCheck *check = rel->rd_att->constr->check;
1799 ExprContext *econtext;
1800 MemoryContext oldContext;
1804 * If first time through for this result relation, build expression
1805 * nodetrees for rel's constraint expressions. Keep them in the per-query
1806 * memory context so they'll survive throughout the query.
1808 if (resultRelInfo->ri_ConstraintExprs == NULL)
1810 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1811 resultRelInfo->ri_ConstraintExprs =
1812 (ExprState **) palloc(ncheck * sizeof(ExprState *));
1813 for (i = 0; i < ncheck; i++)
1817 checkconstr = stringToNode(check[i].ccbin);
1818 resultRelInfo->ri_ConstraintExprs[i] =
1819 ExecPrepareExpr(checkconstr, estate);
1821 MemoryContextSwitchTo(oldContext);
1825 * We will use the EState's per-tuple context for evaluating constraint
1826 * expressions (creating it if it's not already there).
1828 econtext = GetPerTupleExprContext(estate);
1830 /* Arrange for econtext's scan tuple to be the tuple under test */
1831 econtext->ecxt_scantuple = slot;
1833 /* And evaluate the constraints */
1834 for (i = 0; i < ncheck; i++)
1836 ExprState *checkconstr = resultRelInfo->ri_ConstraintExprs[i];
1839 * NOTE: SQL specifies that a NULL result from a constraint expression
1840 * is not to be treated as a failure. Therefore, use ExecCheck not
1843 if (!ExecCheck(checkconstr, econtext))
1844 return check[i].ccname;
1847 /* NULL result means no error */
1852 * ExecPartitionCheck --- check that tuple meets the partition constraint.
1854 * Returns true if it meets the partition constraint. If the constraint
1855 * fails and we're asked to emit to error, do so and don't return; otherwise
1859 ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
1860 EState *estate, bool emitError)
1862 ExprContext *econtext;
1866 * If first time through, build expression state tree for the partition
1867 * check expression. Keep it in the per-query memory context so they'll
1868 * survive throughout the query.
1870 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1872 List *qual = resultRelInfo->ri_PartitionCheck;
1874 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1878 * We will use the EState's per-tuple context for evaluating constraint
1879 * expressions (creating it if it's not already there).
1881 econtext = GetPerTupleExprContext(estate);
1883 /* Arrange for econtext's scan tuple to be the tuple under test */
1884 econtext->ecxt_scantuple = slot;
1887 * As in case of the catalogued constraints, we treat a NULL result as
1888 * success here, not a failure.
1890 success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1892 /* if asked to emit error, don't actually return on failure */
1893 if (!success && emitError)
1894 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1900 * ExecPartitionCheckEmitError - Form and emit an error message after a failed
1901 * partition constraint check.
1904 ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
1905 TupleTableSlot *slot,
1908 Relation rel = resultRelInfo->ri_RelationDesc;
1909 Relation orig_rel = rel;
1910 TupleDesc tupdesc = RelationGetDescr(rel);
1912 Bitmapset *modifiedCols;
1913 Bitmapset *insertedCols;
1914 Bitmapset *updatedCols;
1917 * Need to first convert the tuple to the root partitioned table's row
1918 * type. For details, check similar comments in ExecConstraints().
1920 if (resultRelInfo->ri_PartitionRoot)
1922 HeapTuple tuple = ExecFetchSlotTuple(slot);
1923 TupleDesc old_tupdesc = RelationGetDescr(rel);
1924 TupleConversionMap *map;
1926 rel = resultRelInfo->ri_PartitionRoot;
1927 tupdesc = RelationGetDescr(rel);
1929 map = convert_tuples_by_name(old_tupdesc, tupdesc,
1930 gettext_noop("could not convert row type"));
1933 tuple = do_convert_tuple(tuple, map);
1934 ExecSetSlotDescriptor(slot, tupdesc);
1935 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
1939 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1940 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1941 modifiedCols = bms_union(insertedCols, updatedCols);
1942 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1948 (errcode(ERRCODE_CHECK_VIOLATION),
1949 errmsg("new row for relation \"%s\" violates partition constraint",
1950 RelationGetRelationName(orig_rel)),
1951 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0));
1955 * ExecConstraints - check constraints of the tuple in 'slot'
1957 * This checks the traditional NOT NULL and check constraints.
1959 * The partition constraint is *NOT* checked.
1961 * Note: 'slot' contains the tuple to check the constraints of, which may
1962 * have been converted from the original input tuple after tuple routing.
1963 * 'resultRelInfo' is the final result relation, after tuple routing.
1966 ExecConstraints(ResultRelInfo *resultRelInfo,
1967 TupleTableSlot *slot, EState *estate)
1969 Relation rel = resultRelInfo->ri_RelationDesc;
1970 TupleDesc tupdesc = RelationGetDescr(rel);
1971 TupleConstr *constr = tupdesc->constr;
1972 Bitmapset *modifiedCols;
1973 Bitmapset *insertedCols;
1974 Bitmapset *updatedCols;
1976 Assert(constr || resultRelInfo->ri_PartitionCheck);
1978 if (constr && constr->has_not_null)
1980 int natts = tupdesc->natts;
1983 for (attrChk = 1; attrChk <= natts; attrChk++)
1985 Form_pg_attribute att = TupleDescAttr(tupdesc, attrChk - 1);
1987 if (att->attnotnull && slot_attisnull(slot, attrChk))
1990 Relation orig_rel = rel;
1991 TupleDesc orig_tupdesc = RelationGetDescr(rel);
1994 * If the tuple has been routed, it's been converted to the
1995 * partition's rowtype, which might differ from the root
1996 * table's. We must convert it back to the root table's
1997 * rowtype so that val_desc shown error message matches the
2000 if (resultRelInfo->ri_PartitionRoot)
2002 HeapTuple tuple = ExecFetchSlotTuple(slot);
2003 TupleConversionMap *map;
2005 rel = resultRelInfo->ri_PartitionRoot;
2006 tupdesc = RelationGetDescr(rel);
2008 map = convert_tuples_by_name(orig_tupdesc, tupdesc,
2009 gettext_noop("could not convert row type"));
2012 tuple = do_convert_tuple(tuple, map);
2013 ExecSetSlotDescriptor(slot, tupdesc);
2014 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2018 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2019 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2020 modifiedCols = bms_union(insertedCols, updatedCols);
2021 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2028 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2029 errmsg("null value in column \"%s\" violates not-null constraint",
2030 NameStr(att->attname)),
2031 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2032 errtablecol(orig_rel, attrChk)));
2037 if (constr && constr->num_check > 0)
2041 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2044 Relation orig_rel = rel;
2046 /* See the comment above. */
2047 if (resultRelInfo->ri_PartitionRoot)
2049 HeapTuple tuple = ExecFetchSlotTuple(slot);
2050 TupleDesc old_tupdesc = RelationGetDescr(rel);
2051 TupleConversionMap *map;
2053 rel = resultRelInfo->ri_PartitionRoot;
2054 tupdesc = RelationGetDescr(rel);
2056 map = convert_tuples_by_name(old_tupdesc, tupdesc,
2057 gettext_noop("could not convert row type"));
2060 tuple = do_convert_tuple(tuple, map);
2061 ExecSetSlotDescriptor(slot, tupdesc);
2062 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2066 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2067 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2068 modifiedCols = bms_union(insertedCols, updatedCols);
2069 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2075 (errcode(ERRCODE_CHECK_VIOLATION),
2076 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2077 RelationGetRelationName(orig_rel), failed),
2078 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2079 errtableconstraint(orig_rel, failed)));
2085 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
2086 * of the specified kind.
2088 * Note that this needs to be called multiple times to ensure that all kinds of
2089 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
2090 * CHECK OPTION set and from row level security policies). See ExecInsert()
2094 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
2095 TupleTableSlot *slot, EState *estate)
2097 Relation rel = resultRelInfo->ri_RelationDesc;
2098 TupleDesc tupdesc = RelationGetDescr(rel);
2099 ExprContext *econtext;
2104 * We will use the EState's per-tuple context for evaluating constraint
2105 * expressions (creating it if it's not already there).
2107 econtext = GetPerTupleExprContext(estate);
2109 /* Arrange for econtext's scan tuple to be the tuple under test */
2110 econtext->ecxt_scantuple = slot;
2112 /* Check each of the constraints */
2113 forboth(l1, resultRelInfo->ri_WithCheckOptions,
2114 l2, resultRelInfo->ri_WithCheckOptionExprs)
2116 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2117 ExprState *wcoExpr = (ExprState *) lfirst(l2);
2120 * Skip any WCOs which are not the kind we are looking for at this
2123 if (wco->kind != kind)
2127 * WITH CHECK OPTION checks are intended to ensure that the new tuple
2128 * is visible (in the case of a view) or that it passes the
2129 * 'with-check' policy (in the case of row security). If the qual
2130 * evaluates to NULL or FALSE, then the new tuple won't be included in
2131 * the view or doesn't pass the 'with-check' policy for the table.
2133 if (!ExecQual(wcoExpr, econtext))
2136 Bitmapset *modifiedCols;
2137 Bitmapset *insertedCols;
2138 Bitmapset *updatedCols;
2143 * For WITH CHECK OPTIONs coming from views, we might be
2144 * able to provide the details on the row, depending on
2145 * the permissions on the relation (that is, if the user
2146 * could view it directly anyway). For RLS violations, we
2147 * don't include the data since we don't know if the user
2148 * should be able to view the tuple as that depends on the
2151 case WCO_VIEW_CHECK:
2152 /* See the comment in ExecConstraints(). */
2153 if (resultRelInfo->ri_PartitionRoot)
2155 HeapTuple tuple = ExecFetchSlotTuple(slot);
2156 TupleDesc old_tupdesc = RelationGetDescr(rel);
2157 TupleConversionMap *map;
2159 rel = resultRelInfo->ri_PartitionRoot;
2160 tupdesc = RelationGetDescr(rel);
2162 map = convert_tuples_by_name(old_tupdesc, tupdesc,
2163 gettext_noop("could not convert row type"));
2166 tuple = do_convert_tuple(tuple, map);
2167 ExecSetSlotDescriptor(slot, tupdesc);
2168 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2172 insertedCols = GetInsertedColumns(resultRelInfo, estate);
2173 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
2174 modifiedCols = bms_union(insertedCols, updatedCols);
2175 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2182 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2183 errmsg("new row violates check option for view \"%s\"",
2185 val_desc ? errdetail("Failing row contains %s.",
2188 case WCO_RLS_INSERT_CHECK:
2189 case WCO_RLS_UPDATE_CHECK:
2190 if (wco->polname != NULL)
2192 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2193 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2194 wco->polname, wco->relname)));
2197 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2198 errmsg("new row violates row-level security policy for table \"%s\"",
2201 case WCO_RLS_CONFLICT_CHECK:
2202 if (wco->polname != NULL)
2204 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2205 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2206 wco->polname, wco->relname)));
2209 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2210 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2214 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2222 * ExecBuildSlotValueDescription -- construct a string representing a tuple
2224 * This is intentionally very similar to BuildIndexValueDescription, but
2225 * unlike that function, we truncate long field values (to at most maxfieldlen
2226 * bytes). That seems necessary here since heap field values could be very
2227 * long, whereas index entries typically aren't so wide.
2229 * Also, unlike the case with index entries, we need to be prepared to ignore
2230 * dropped columns. We used to use the slot's tuple descriptor to decode the
2231 * data, but the slot's descriptor doesn't identify dropped columns, so we
2232 * now need to be passed the relation's descriptor.
2234 * Note that, like BuildIndexValueDescription, if the user does not have
2235 * permission to view any of the columns involved, a NULL is returned. Unlike
2236 * BuildIndexValueDescription, if the user has access to view a subset of the
2237 * column involved, that subset will be returned with a key identifying which
2241 ExecBuildSlotValueDescription(Oid reloid,
2242 TupleTableSlot *slot,
2244 Bitmapset *modifiedCols,
2248 StringInfoData collist;
2249 bool write_comma = false;
2250 bool write_comma_collist = false;
2252 AclResult aclresult;
2253 bool table_perm = false;
2254 bool any_perm = false;
2257 * Check if RLS is enabled and should be active for the relation; if so,
2258 * then don't return anything. Otherwise, go through normal permission
2261 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2264 initStringInfo(&buf);
2266 appendStringInfoChar(&buf, '(');
2269 * Check if the user has permissions to see the row. Table-level SELECT
2270 * allows access to all columns. If the user does not have table-level
2271 * SELECT then we check each column and include those the user has SELECT
2272 * rights on. Additionally, we always include columns the user provided
2275 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2276 if (aclresult != ACLCHECK_OK)
2278 /* Set up the buffer for the column list */
2279 initStringInfo(&collist);
2280 appendStringInfoChar(&collist, '(');
2283 table_perm = any_perm = true;
2285 /* Make sure the tuple is fully deconstructed */
2286 slot_getallattrs(slot);
2288 for (i = 0; i < tupdesc->natts; i++)
2290 bool column_perm = false;
2293 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2295 /* ignore dropped columns */
2296 if (att->attisdropped)
2302 * No table-level SELECT, so need to make sure they either have
2303 * SELECT rights on the column or that they have provided the data
2304 * for the column. If not, omit this column from the error
2307 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2308 GetUserId(), ACL_SELECT);
2309 if (bms_is_member(att->attnum - FirstLowInvalidHeapAttributeNumber,
2310 modifiedCols) || aclresult == ACLCHECK_OK)
2312 column_perm = any_perm = true;
2314 if (write_comma_collist)
2315 appendStringInfoString(&collist, ", ");
2317 write_comma_collist = true;
2319 appendStringInfoString(&collist, NameStr(att->attname));
2323 if (table_perm || column_perm)
2325 if (slot->tts_isnull[i])
2332 getTypeOutputInfo(att->atttypid,
2333 &foutoid, &typisvarlena);
2334 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2338 appendStringInfoString(&buf, ", ");
2342 /* truncate if needed */
2343 vallen = strlen(val);
2344 if (vallen <= maxfieldlen)
2345 appendStringInfoString(&buf, val);
2348 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2349 appendBinaryStringInfo(&buf, val, vallen);
2350 appendStringInfoString(&buf, "...");
2355 /* If we end up with zero columns being returned, then return NULL. */
2359 appendStringInfoChar(&buf, ')');
2363 appendStringInfoString(&collist, ") = ");
2364 appendStringInfoString(&collist, buf.data);
2366 return collist.data;
2374 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2375 * given ResultRelInfo
2378 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2381 Bitmapset *updatedCols;
2384 * Compute lock mode to use. If columns that are part of the key have not
2385 * been modified, then we can use a weaker lock, allowing for better
2388 updatedCols = GetUpdatedColumns(relinfo, estate);
2389 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2390 INDEX_ATTR_BITMAP_KEY);
2392 if (bms_overlap(keyCols, updatedCols))
2393 return LockTupleExclusive;
2395 return LockTupleNoKeyExclusive;
2399 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2401 * If no such struct, either return NULL or throw error depending on missing_ok
2404 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2408 foreach(lc, estate->es_rowMarks)
2410 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2412 if (erm->rti == rti)
2416 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2421 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2423 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2424 * input plan node (not planstate node!). We need the latter to find out
2425 * the column numbers of the resjunk columns.
2428 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2430 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2433 aerm->rowmark = erm;
2435 /* Look up the resjunk columns associated with this rowmark */
2436 if (erm->markType != ROW_MARK_COPY)
2438 /* need ctid for all methods other than COPY */
2439 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2440 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2442 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2443 elog(ERROR, "could not find junk %s column", resname);
2447 /* need wholerow if COPY */
2448 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2449 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2451 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2452 elog(ERROR, "could not find junk %s column", resname);
2455 /* if child rel, need tableoid */
2456 if (erm->rti != erm->prti)
2458 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2459 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2461 if (!AttributeNumberIsValid(aerm->toidAttNo))
2462 elog(ERROR, "could not find junk %s column", resname);
2470 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2471 * process the updated version under READ COMMITTED rules.
2473 * See backend/executor/README for some info about how this works.
2478 * Check a modified tuple to see if we want to process its updated version
2479 * under READ COMMITTED rules.
2481 * estate - outer executor state data
2482 * epqstate - state for EvalPlanQual rechecking
2483 * relation - table containing tuple
2484 * rti - rangetable index of table containing tuple
2485 * lockmode - requested tuple lock mode
2486 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2487 * priorXmax - t_xmax from the outdated tuple
2489 * *tid is also an output parameter: it's modified to hold the TID of the
2490 * latest version of the tuple (note this may be changed even on failure)
2492 * Returns a slot containing the new candidate update/delete tuple, or
2493 * NULL if we determine we shouldn't process the row.
2495 * Note: properly, lockmode should be declared as enum LockTupleMode,
2496 * but we use "int" to avoid having to include heapam.h in executor.h.
2499 EvalPlanQual(EState *estate, EPQState *epqstate,
2500 Relation relation, Index rti, int lockmode,
2501 ItemPointer tid, TransactionId priorXmax)
2503 TupleTableSlot *slot;
2504 HeapTuple copyTuple;
2509 * Get and lock the updated version of the row; if fail, return NULL.
2511 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2514 if (copyTuple == NULL)
2518 * For UPDATE/DELETE we have to return tid of actual row we're executing
2521 *tid = copyTuple->t_self;
2524 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2526 EvalPlanQualBegin(epqstate, estate);
2529 * Free old test tuple, if any, and store new tuple where relation's scan
2532 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2535 * Fetch any non-locked source rows
2537 EvalPlanQualFetchRowMarks(epqstate);
2540 * Run the EPQ query. We assume it will return at most one tuple.
2542 slot = EvalPlanQualNext(epqstate);
2545 * If we got a tuple, force the slot to materialize the tuple so that it
2546 * is not dependent on any local state in the EPQ query (in particular,
2547 * it's highly likely that the slot contains references to any pass-by-ref
2548 * datums that may be present in copyTuple). As with the next step, this
2549 * is to guard against early re-use of the EPQ query.
2551 if (!TupIsNull(slot))
2552 (void) ExecMaterializeSlot(slot);
2555 * Clear out the test tuple. This is needed in case the EPQ query is
2556 * re-used to test a tuple for a different relation. (Not clear that can
2557 * really happen, but let's be safe.)
2559 EvalPlanQualSetTuple(epqstate, rti, NULL);
2565 * Fetch a copy of the newest version of an outdated tuple
2567 * estate - executor state data
2568 * relation - table containing tuple
2569 * lockmode - requested tuple lock mode
2570 * wait_policy - requested lock wait policy
2571 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2572 * priorXmax - t_xmax from the outdated tuple
2574 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2575 * that there is no newest version (ie, the row was deleted not updated).
2576 * We also return NULL if the tuple is locked and the wait policy is to skip
2579 * If successful, we have locked the newest tuple version, so caller does not
2580 * need to worry about it changing anymore.
2582 * Note: properly, lockmode should be declared as enum LockTupleMode,
2583 * but we use "int" to avoid having to include heapam.h in executor.h.
2586 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2587 LockWaitPolicy wait_policy,
2588 ItemPointer tid, TransactionId priorXmax)
2590 HeapTuple copyTuple = NULL;
2591 HeapTupleData tuple;
2592 SnapshotData SnapshotDirty;
2595 * fetch target tuple
2597 * Loop here to deal with updated or busy tuples
2599 InitDirtySnapshot(SnapshotDirty);
2600 tuple.t_self = *tid;
2605 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2608 HeapUpdateFailureData hufd;
2611 * If xmin isn't what we're expecting, the slot must have been
2612 * recycled and reused for an unrelated tuple. This implies that
2613 * the latest version of the row was deleted, so we need do
2614 * nothing. (Should be safe to examine xmin without getting
2615 * buffer's content lock. We assume reading a TransactionId to be
2616 * atomic, and Xmin never changes in an existing tuple, except to
2617 * invalid or frozen, and neither of those can match priorXmax.)
2619 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2622 ReleaseBuffer(buffer);
2626 /* otherwise xmin should not be dirty... */
2627 if (TransactionIdIsValid(SnapshotDirty.xmin))
2628 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2631 * If tuple is being updated by other transaction then we have to
2632 * wait for its commit/abort, or die trying.
2634 if (TransactionIdIsValid(SnapshotDirty.xmax))
2636 ReleaseBuffer(buffer);
2637 switch (wait_policy)
2640 XactLockTableWait(SnapshotDirty.xmax,
2641 relation, &tuple.t_self,
2645 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2646 return NULL; /* skip instead of waiting */
2649 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2651 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2652 errmsg("could not obtain lock on row in relation \"%s\"",
2653 RelationGetRelationName(relation))));
2656 continue; /* loop back to repeat heap_fetch */
2660 * If tuple was inserted by our own transaction, we have to check
2661 * cmin against es_output_cid: cmin >= current CID means our
2662 * command cannot see the tuple, so we should ignore it. Otherwise
2663 * heap_lock_tuple() will throw an error, and so would any later
2664 * attempt to update or delete the tuple. (We need not check cmax
2665 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2666 * by our transaction dead, regardless of cmax.) We just checked
2667 * that priorXmax == xmin, so we can test that variable instead of
2668 * doing HeapTupleHeaderGetXmin again.
2670 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2671 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2673 ReleaseBuffer(buffer);
2678 * This is a live tuple, so now try to lock it.
2680 test = heap_lock_tuple(relation, &tuple,
2681 estate->es_output_cid,
2682 lockmode, wait_policy,
2683 false, &buffer, &hufd);
2684 /* We now have two pins on the buffer, get rid of one */
2685 ReleaseBuffer(buffer);
2689 case HeapTupleSelfUpdated:
2692 * The target tuple was already updated or deleted by the
2693 * current command, or by a later command in the current
2694 * transaction. We *must* ignore the tuple in the former
2695 * case, so as to avoid the "Halloween problem" of
2696 * repeated update attempts. In the latter case it might
2697 * be sensible to fetch the updated tuple instead, but
2698 * doing so would require changing heap_update and
2699 * heap_delete to not complain about updating "invisible"
2700 * tuples, which seems pretty scary (heap_lock_tuple will
2701 * not complain, but few callers expect
2702 * HeapTupleInvisible, and we're not one of them). So for
2703 * now, treat the tuple as deleted and do not process.
2705 ReleaseBuffer(buffer);
2708 case HeapTupleMayBeUpdated:
2709 /* successfully locked */
2712 case HeapTupleUpdated:
2713 ReleaseBuffer(buffer);
2714 if (IsolationUsesXactSnapshot())
2716 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2717 errmsg("could not serialize access due to concurrent update")));
2718 if (ItemPointerIndicatesMovedPartitions(&hufd.ctid))
2720 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2721 errmsg("tuple to be locked was already moved to another partition due to concurrent update")));
2723 /* Should not encounter speculative tuple on recheck */
2724 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2725 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2727 /* it was updated, so look at the updated version */
2728 tuple.t_self = hufd.ctid;
2729 /* updated row should have xmin matching this xmax */
2730 priorXmax = hufd.xmax;
2733 /* tuple was deleted, so give up */
2736 case HeapTupleWouldBlock:
2737 ReleaseBuffer(buffer);
2740 case HeapTupleInvisible:
2741 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 /* successful, copy tuple */
2990 copyTuple = heap_copytuple(&tuple);
2991 ReleaseBuffer(buffer);
2995 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
3001 Assert(erm->markType == ROW_MARK_COPY);
3003 /* fetch the whole-row Var for the relation */
3004 datum = ExecGetJunkAttribute(epqstate->origslot,
3007 /* non-locked rels could be on the inside of outer joins */
3010 td = DatumGetHeapTupleHeader(datum);
3012 /* build a temporary HeapTuple control structure */
3013 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
3015 /* relation might be a foreign table, if so provide tableoid */
3016 tuple.t_tableOid = erm->relid;
3017 /* also copy t_ctid in case there's valid data there */
3018 tuple.t_self = td->t_ctid;
3020 /* copy and store tuple */
3021 EvalPlanQualSetTuple(epqstate, erm->rti,
3022 heap_copytuple(&tuple));
3028 * Fetch the next row (if any) from EvalPlanQual testing
3030 * (In practice, there should never be more than one row...)
3033 EvalPlanQualNext(EPQState *epqstate)
3035 MemoryContext oldcontext;
3036 TupleTableSlot *slot;
3038 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
3039 slot = ExecProcNode(epqstate->planstate);
3040 MemoryContextSwitchTo(oldcontext);
3046 * Initialize or reset an EvalPlanQual state tree
3049 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
3051 EState *estate = epqstate->estate;
3055 /* First time through, so create a child EState */
3056 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
3061 * We already have a suitable child EPQ tree, so just reset it.
3063 int rtsize = list_length(parentestate->es_range_table);
3064 PlanState *planstate = epqstate->planstate;
3066 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
3068 /* Recopy current values of parent parameters */
3069 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3073 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3077 /* copy value if any, but not execPlan link */
3078 estate->es_param_exec_vals[i].value =
3079 parentestate->es_param_exec_vals[i].value;
3080 estate->es_param_exec_vals[i].isnull =
3081 parentestate->es_param_exec_vals[i].isnull;
3086 * Mark child plan tree as needing rescan at all scan nodes. The
3087 * first ExecProcNode will take care of actually doing the rescan.
3089 planstate->chgParam = bms_add_member(planstate->chgParam,
3090 epqstate->epqParam);
3095 * Start execution of an EvalPlanQual plan tree.
3097 * This is a cut-down version of ExecutorStart(): we copy some state from
3098 * the top-level estate rather than initializing it fresh.
3101 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
3105 MemoryContext oldcontext;
3108 rtsize = list_length(parentestate->es_range_table);
3110 epqstate->estate = estate = CreateExecutorState();
3112 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3115 * Child EPQ EStates share the parent's copy of unchanging state such as
3116 * the snapshot, rangetable, result-rel info, and external Param info.
3117 * They need their own copies of local state, including a tuple table,
3118 * es_param_exec_vals, etc.
3120 * The ResultRelInfo array management is trickier than it looks. We
3121 * create a fresh array for the child but copy all the content from the
3122 * parent. This is because it's okay for the child to share any
3123 * per-relation state the parent has already created --- but if the child
3124 * sets up any ResultRelInfo fields, such as its own junkfilter, that
3125 * state must *not* propagate back to the parent. (For one thing, the
3126 * pointed-to data is in a memory context that won't last long enough.)
3128 estate->es_direction = ForwardScanDirection;
3129 estate->es_snapshot = parentestate->es_snapshot;
3130 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3131 estate->es_range_table = parentestate->es_range_table;
3132 estate->es_plannedstmt = parentestate->es_plannedstmt;
3133 estate->es_junkFilter = parentestate->es_junkFilter;
3134 estate->es_output_cid = parentestate->es_output_cid;
3135 if (parentestate->es_num_result_relations > 0)
3137 int numResultRelations = parentestate->es_num_result_relations;
3138 ResultRelInfo *resultRelInfos;
3140 resultRelInfos = (ResultRelInfo *)
3141 palloc(numResultRelations * sizeof(ResultRelInfo));
3142 memcpy(resultRelInfos, parentestate->es_result_relations,
3143 numResultRelations * sizeof(ResultRelInfo));
3144 estate->es_result_relations = resultRelInfos;
3145 estate->es_num_result_relations = numResultRelations;
3147 /* es_result_relation_info must NOT be copied */
3148 /* es_trig_target_relations must NOT be copied */
3149 estate->es_rowMarks = parentestate->es_rowMarks;
3150 estate->es_top_eflags = parentestate->es_top_eflags;
3151 estate->es_instrument = parentestate->es_instrument;
3152 /* es_auxmodifytables must NOT be copied */
3155 * The external param list is simply shared from parent. The internal
3156 * param workspace has to be local state, but we copy the initial values
3157 * from the parent, so as to have access to any param values that were
3158 * already set from other parts of the parent's plan tree.
3160 estate->es_param_list_info = parentestate->es_param_list_info;
3161 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3165 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3166 estate->es_param_exec_vals = (ParamExecData *)
3167 palloc0(i * sizeof(ParamExecData));
3170 /* copy value if any, but not execPlan link */
3171 estate->es_param_exec_vals[i].value =
3172 parentestate->es_param_exec_vals[i].value;
3173 estate->es_param_exec_vals[i].isnull =
3174 parentestate->es_param_exec_vals[i].isnull;
3179 * Each EState must have its own es_epqScanDone state, but if we have
3180 * nested EPQ checks they should share es_epqTuple arrays. This allows
3181 * sub-rechecks to inherit the values being examined by an outer recheck.
3183 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
3184 if (parentestate->es_epqTuple != NULL)
3186 estate->es_epqTuple = parentestate->es_epqTuple;
3187 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
3191 estate->es_epqTuple = (HeapTuple *)
3192 palloc0(rtsize * sizeof(HeapTuple));
3193 estate->es_epqTupleSet = (bool *)
3194 palloc0(rtsize * sizeof(bool));
3198 * Each estate also has its own tuple table.
3200 estate->es_tupleTable = NIL;
3203 * Initialize private state information for each SubPlan. We must do this
3204 * before running ExecInitNode on the main query tree, since
3205 * ExecInitSubPlan expects to be able to find these entries. Some of the
3206 * SubPlans might not be used in the part of the plan tree we intend to
3207 * run, but since it's not easy to tell which, we just initialize them
3210 Assert(estate->es_subplanstates == NIL);
3211 foreach(l, parentestate->es_plannedstmt->subplans)
3213 Plan *subplan = (Plan *) lfirst(l);
3214 PlanState *subplanstate;
3216 subplanstate = ExecInitNode(subplan, estate, 0);
3217 estate->es_subplanstates = lappend(estate->es_subplanstates,
3222 * Initialize the private state information for all the nodes in the part
3223 * of the plan tree we need to run. This opens files, allocates storage
3224 * and leaves us ready to start processing tuples.
3226 epqstate->planstate = ExecInitNode(planTree, estate, 0);
3228 MemoryContextSwitchTo(oldcontext);
3232 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
3233 * or if we are done with the current EPQ child.
3235 * This is a cut-down version of ExecutorEnd(); basically we want to do most
3236 * of the normal cleanup, but *not* close result relations (which we are
3237 * just sharing from the outer query). We do, however, have to close any
3238 * trigger target relations that got opened, since those are not shared.
3239 * (There probably shouldn't be any of the latter, but just in case...)
3242 EvalPlanQualEnd(EPQState *epqstate)
3244 EState *estate = epqstate->estate;
3245 MemoryContext oldcontext;
3249 return; /* idle, so nothing to do */
3251 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3253 ExecEndNode(epqstate->planstate);
3255 foreach(l, estate->es_subplanstates)
3257 PlanState *subplanstate = (PlanState *) lfirst(l);
3259 ExecEndNode(subplanstate);
3262 /* throw away the per-estate tuple table */
3263 ExecResetTupleTable(estate->es_tupleTable, false);
3265 /* close any trigger target relations attached to this EState */
3266 ExecCleanUpTriggerState(estate);
3268 MemoryContextSwitchTo(oldcontext);
3270 FreeExecutorState(estate);
3272 /* Mark EPQState idle */
3273 epqstate->estate = NULL;
3274 epqstate->planstate = NULL;
3275 epqstate->origslot = NULL;