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-2016, PostgreSQL Global Development Group
30 * Portions Copyright (c) 1994, Regents of the University of California
34 * src/backend/executor/execMain.c
36 *-------------------------------------------------------------------------
40 #include "access/htup_details.h"
41 #include "access/sysattr.h"
42 #include "access/transam.h"
43 #include "access/xact.h"
44 #include "catalog/namespace.h"
45 #include "commands/matview.h"
46 #include "commands/trigger.h"
47 #include "executor/execdebug.h"
48 #include "foreign/fdwapi.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
51 #include "optimizer/clauses.h"
52 #include "parser/parsetree.h"
53 #include "storage/bufmgr.h"
54 #include "storage/lmgr.h"
55 #include "tcop/utility.h"
56 #include "utils/acl.h"
57 #include "utils/lsyscache.h"
58 #include "utils/memutils.h"
59 #include "utils/rls.h"
60 #include "utils/snapmgr.h"
61 #include "utils/tqual.h"
64 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
65 ExecutorStart_hook_type ExecutorStart_hook = NULL;
66 ExecutorRun_hook_type ExecutorRun_hook = NULL;
67 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
68 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
70 /* Hook for plugin to get control in ExecCheckRTPerms() */
71 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
73 /* decls for local routines only used within this module */
74 static void InitPlan(QueryDesc *queryDesc, int eflags);
75 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
76 static void ExecPostprocessPlan(EState *estate);
77 static void ExecEndPlan(PlanState *planstate, EState *estate);
78 static void ExecutePlan(EState *estate, PlanState *planstate,
79 bool use_parallel_mode,
83 ScanDirection direction,
85 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
86 static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
87 Bitmapset *modifiedCols,
88 AclMode requiredPerms);
89 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
90 static char *ExecBuildSlotValueDescription(Oid reloid,
93 Bitmapset *modifiedCols,
95 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
99 * Note that GetUpdatedColumns() also exists in commands/trigger.c. There does
100 * not appear to be any good header to put it into, given the structures that
101 * it uses, so we let them be duplicated. Be sure to update both if one needs
102 * to be changed, however.
104 #define GetInsertedColumns(relinfo, estate) \
105 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
106 #define GetUpdatedColumns(relinfo, estate) \
107 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
109 /* end of local decls */
112 /* ----------------------------------------------------------------
115 * This routine must be called at the beginning of any execution of any
118 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
119 * only because some places use QueryDescs for utility commands). The tupDesc
120 * field of the QueryDesc is filled in to describe the tuples that will be
121 * returned, and the internal fields (estate and planstate) are set up.
123 * eflags contains flag bits as described in executor.h.
125 * NB: the CurrentMemoryContext when this is called will become the parent
126 * of the per-query context used for this Executor invocation.
128 * We provide a function hook variable that lets loadable plugins
129 * get control when ExecutorStart is called. Such a plugin would
130 * normally call standard_ExecutorStart().
132 * ----------------------------------------------------------------
135 ExecutorStart(QueryDesc *queryDesc, int eflags)
137 if (ExecutorStart_hook)
138 (*ExecutorStart_hook) (queryDesc, eflags);
140 standard_ExecutorStart(queryDesc, eflags);
144 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
147 MemoryContext oldcontext;
149 /* sanity checks: queryDesc must not be started already */
150 Assert(queryDesc != NULL);
151 Assert(queryDesc->estate == NULL);
154 * If the transaction is read-only, we need to check if any writes are
155 * planned to non-temporary tables. EXPLAIN is considered read-only.
157 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
158 * would require (a) storing the combocid hash in shared memory, rather
159 * than synchronizing it just once at the start of parallelism, and (b) an
160 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
161 * INSERT may have no such troubles, but we forbid it to simplify the
164 * We have lower-level defenses in CommandCounterIncrement and elsewhere
165 * against performing unsafe operations in parallel mode, but this gives a
166 * more user-friendly error message.
168 if ((XactReadOnly || IsInParallelMode()) &&
169 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
170 ExecCheckXactReadOnly(queryDesc->plannedstmt);
173 * Build EState, switch into per-query memory context for startup.
175 estate = CreateExecutorState();
176 queryDesc->estate = estate;
178 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
181 * Fill in external parameters, if any, from queryDesc; and allocate
182 * workspace for internal parameters
184 estate->es_param_list_info = queryDesc->params;
186 if (queryDesc->plannedstmt->nParamExec > 0)
187 estate->es_param_exec_vals = (ParamExecData *)
188 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
191 * If non-read-only query, set the command ID to mark output tuples with
193 switch (queryDesc->operation)
198 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
201 if (queryDesc->plannedstmt->rowMarks != NIL ||
202 queryDesc->plannedstmt->hasModifyingCTE)
203 estate->es_output_cid = GetCurrentCommandId(true);
206 * A SELECT without modifying CTEs can't possibly queue triggers,
207 * so force skip-triggers mode. This is just a marginal efficiency
208 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
209 * all that expensive, but we might as well do it.
211 if (!queryDesc->plannedstmt->hasModifyingCTE)
212 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
218 estate->es_output_cid = GetCurrentCommandId(true);
222 elog(ERROR, "unrecognized operation code: %d",
223 (int) queryDesc->operation);
228 * Copy other important information into the EState
230 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
231 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
232 estate->es_top_eflags = eflags;
233 estate->es_instrument = queryDesc->instrument_options;
236 * Initialize the plan state tree
238 InitPlan(queryDesc, eflags);
241 * Set up an AFTER-trigger statement context, unless told not to, or
242 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
244 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
245 AfterTriggerBeginQuery();
247 MemoryContextSwitchTo(oldcontext);
250 /* ----------------------------------------------------------------
253 * This is the main routine of the executor module. It accepts
254 * the query descriptor from the traffic cop and executes the
257 * ExecutorStart must have been called already.
259 * If direction is NoMovementScanDirection then nothing is done
260 * except to start up/shut down the destination. Otherwise,
261 * we retrieve up to 'count' tuples in the specified direction.
263 * Note: count = 0 is interpreted as no portal limit, i.e., run to
264 * completion. Also note that the count limit is only applied to
265 * retrieved tuples, not for instance to those inserted/updated/deleted
266 * by a ModifyTable plan node.
268 * There is no return value, but output tuples (if any) are sent to
269 * the destination receiver specified in the QueryDesc; and the number
270 * of tuples processed at the top level can be found in
271 * estate->es_processed.
273 * We provide a function hook variable that lets loadable plugins
274 * get control when ExecutorRun is called. Such a plugin would
275 * normally call standard_ExecutorRun().
277 * ----------------------------------------------------------------
280 ExecutorRun(QueryDesc *queryDesc,
281 ScanDirection direction, uint64 count)
283 if (ExecutorRun_hook)
284 (*ExecutorRun_hook) (queryDesc, direction, count);
286 standard_ExecutorRun(queryDesc, direction, count);
290 standard_ExecutorRun(QueryDesc *queryDesc,
291 ScanDirection direction, uint64 count)
297 MemoryContext oldcontext;
300 Assert(queryDesc != NULL);
302 estate = queryDesc->estate;
304 Assert(estate != NULL);
305 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
308 * Switch into per-query memory context
310 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
312 /* Allow instrumentation of Executor overall runtime */
313 if (queryDesc->totaltime)
314 InstrStartNode(queryDesc->totaltime);
317 * extract information from the query descriptor and the query feature.
319 operation = queryDesc->operation;
320 dest = queryDesc->dest;
323 * startup tuple receiver, if we will be emitting tuples
325 estate->es_processed = 0;
326 estate->es_lastoid = InvalidOid;
328 sendTuples = (operation == CMD_SELECT ||
329 queryDesc->plannedstmt->hasReturning);
332 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
337 if (!ScanDirectionIsNoMovement(direction))
339 queryDesc->planstate,
340 queryDesc->plannedstmt->parallelModeNeeded,
348 * shutdown tuple receiver, if we started it
351 (*dest->rShutdown) (dest);
353 if (queryDesc->totaltime)
354 InstrStopNode(queryDesc->totaltime, estate->es_processed);
356 MemoryContextSwitchTo(oldcontext);
359 /* ----------------------------------------------------------------
362 * This routine must be called after the last ExecutorRun call.
363 * It performs cleanup such as firing AFTER triggers. It is
364 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
365 * include these actions in the total runtime.
367 * We provide a function hook variable that lets loadable plugins
368 * get control when ExecutorFinish is called. Such a plugin would
369 * normally call standard_ExecutorFinish().
371 * ----------------------------------------------------------------
374 ExecutorFinish(QueryDesc *queryDesc)
376 if (ExecutorFinish_hook)
377 (*ExecutorFinish_hook) (queryDesc);
379 standard_ExecutorFinish(queryDesc);
383 standard_ExecutorFinish(QueryDesc *queryDesc)
386 MemoryContext oldcontext;
389 Assert(queryDesc != NULL);
391 estate = queryDesc->estate;
393 Assert(estate != NULL);
394 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
396 /* This should be run once and only once per Executor instance */
397 Assert(!estate->es_finished);
399 /* Switch into per-query memory context */
400 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
402 /* Allow instrumentation of Executor overall runtime */
403 if (queryDesc->totaltime)
404 InstrStartNode(queryDesc->totaltime);
406 /* Run ModifyTable nodes to completion */
407 ExecPostprocessPlan(estate);
409 /* Execute queued AFTER triggers, unless told not to */
410 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
411 AfterTriggerEndQuery(estate);
413 if (queryDesc->totaltime)
414 InstrStopNode(queryDesc->totaltime, 0);
416 MemoryContextSwitchTo(oldcontext);
418 estate->es_finished = true;
421 /* ----------------------------------------------------------------
424 * This routine must be called at the end of execution of any
427 * We provide a function hook variable that lets loadable plugins
428 * get control when ExecutorEnd is called. Such a plugin would
429 * normally call standard_ExecutorEnd().
431 * ----------------------------------------------------------------
434 ExecutorEnd(QueryDesc *queryDesc)
436 if (ExecutorEnd_hook)
437 (*ExecutorEnd_hook) (queryDesc);
439 standard_ExecutorEnd(queryDesc);
443 standard_ExecutorEnd(QueryDesc *queryDesc)
446 MemoryContext oldcontext;
449 Assert(queryDesc != NULL);
451 estate = queryDesc->estate;
453 Assert(estate != NULL);
456 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
457 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
458 * might forget to call it.
460 Assert(estate->es_finished ||
461 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
464 * Switch into per-query memory context to run ExecEndPlan
466 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
468 ExecEndPlan(queryDesc->planstate, estate);
470 /* do away with our snapshots */
471 UnregisterSnapshot(estate->es_snapshot);
472 UnregisterSnapshot(estate->es_crosscheck_snapshot);
475 * Must switch out of context before destroying it
477 MemoryContextSwitchTo(oldcontext);
480 * Release EState and per-query memory context. This should release
481 * everything the executor has allocated.
483 FreeExecutorState(estate);
485 /* Reset queryDesc fields that no longer point to anything */
486 queryDesc->tupDesc = NULL;
487 queryDesc->estate = NULL;
488 queryDesc->planstate = NULL;
489 queryDesc->totaltime = NULL;
492 /* ----------------------------------------------------------------
495 * This routine may be called on an open queryDesc to rewind it
497 * ----------------------------------------------------------------
500 ExecutorRewind(QueryDesc *queryDesc)
503 MemoryContext oldcontext;
506 Assert(queryDesc != NULL);
508 estate = queryDesc->estate;
510 Assert(estate != NULL);
512 /* It's probably not sensible to rescan updating queries */
513 Assert(queryDesc->operation == CMD_SELECT);
516 * Switch into per-query memory context
518 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
523 ExecReScan(queryDesc->planstate);
525 MemoryContextSwitchTo(oldcontext);
531 * Check access permissions for all relations listed in a range table.
533 * Returns true if permissions are adequate. Otherwise, throws an appropriate
534 * error if ereport_on_violation is true, or simply returns false otherwise.
536 * Note that this does NOT address row level security policies (aka: RLS). If
537 * rows will be returned to the user as a result of this permission check
538 * passing, then RLS also needs to be consulted (and check_enable_rls()).
540 * See rewrite/rowsecurity.c.
543 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
548 foreach(l, rangeTable)
550 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
552 result = ExecCheckRTEPerms(rte);
555 Assert(rte->rtekind == RTE_RELATION);
556 if (ereport_on_violation)
557 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
558 get_rel_name(rte->relid));
563 if (ExecutorCheckPerms_hook)
564 result = (*ExecutorCheckPerms_hook) (rangeTable,
565 ereport_on_violation);
571 * Check access permissions for a single RTE.
574 ExecCheckRTEPerms(RangeTblEntry *rte)
576 AclMode requiredPerms;
578 AclMode remainingPerms;
583 * Only plain-relation RTEs need to be checked here. Function RTEs are
584 * checked by init_fcache when the function is prepared for execution.
585 * Join, subquery, and special RTEs need no checks.
587 if (rte->rtekind != RTE_RELATION)
591 * No work if requiredPerms is empty.
593 requiredPerms = rte->requiredPerms;
594 if (requiredPerms == 0)
600 * userid to check as: current user unless we have a setuid indication.
602 * Note: GetUserId() is presently fast enough that there's no harm in
603 * calling it separately for each RTE. If that stops being true, we could
604 * call it once in ExecCheckRTPerms and pass the userid down from there.
605 * But for now, no need for the extra clutter.
607 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
610 * We must have *all* the requiredPerms bits, but some of the bits can be
611 * satisfied from column-level rather than relation-level permissions.
612 * First, remove any bits that are satisfied by relation permissions.
614 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
615 remainingPerms = requiredPerms & ~relPerms;
616 if (remainingPerms != 0)
621 * If we lack any permissions that exist only as relation permissions,
622 * we can fail straight away.
624 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
628 * Check to see if we have the needed privileges at column level.
630 * Note: failures just report a table-level error; it would be nicer
631 * to report a column-level error if we have some but not all of the
634 if (remainingPerms & ACL_SELECT)
637 * When the query doesn't explicitly reference any columns (for
638 * example, SELECT COUNT(*) FROM table), allow the query if we
639 * have SELECT on any column of the rel, as per SQL spec.
641 if (bms_is_empty(rte->selectedCols))
643 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
644 ACLMASK_ANY) != ACLCHECK_OK)
648 while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
650 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
651 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
653 if (attno == InvalidAttrNumber)
655 /* Whole-row reference, must have priv on all cols */
656 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
657 ACLMASK_ALL) != ACLCHECK_OK)
662 if (pg_attribute_aclcheck(relOid, attno, userid,
663 ACL_SELECT) != ACLCHECK_OK)
670 * Basically the same for the mod columns, for both INSERT and UPDATE
671 * privilege as specified by remainingPerms.
673 if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
679 if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
689 * ExecCheckRTEPermsModified
690 * Check INSERT or UPDATE access permissions for a single RTE (these
691 * are processed uniformly).
694 ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
695 AclMode requiredPerms)
700 * When the query doesn't explicitly update any columns, allow the query
701 * if we have permission on any column of the rel. This is to handle
702 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
704 if (bms_is_empty(modifiedCols))
706 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
707 ACLMASK_ANY) != ACLCHECK_OK)
711 while ((col = bms_next_member(modifiedCols, col)) >= 0)
713 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
714 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
716 if (attno == InvalidAttrNumber)
718 /* whole-row reference can't happen here */
719 elog(ERROR, "whole-row update is not implemented");
723 if (pg_attribute_aclcheck(relOid, attno, userid,
724 requiredPerms) != ACLCHECK_OK)
732 * Check that the query does not imply any writes to non-temp tables;
733 * unless we're in parallel mode, in which case don't even allow writes
736 * Note: in a Hot Standby slave this would need to reject writes to temp
737 * tables just as we do in parallel mode; but an HS slave can't have created
738 * any temp tables in the first place, so no need to check that.
741 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
746 * Fail if write permissions are requested in parallel mode for table
747 * (temp or non-temp), otherwise fail for any non-temp table.
749 foreach(l, plannedstmt->rtable)
751 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
753 if (rte->rtekind != RTE_RELATION)
756 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
759 if (isTempNamespace(get_rel_namespace(rte->relid)))
762 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
765 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
766 PreventCommandIfParallelMode(CreateCommandTag((Node *) plannedstmt));
770 /* ----------------------------------------------------------------
773 * Initializes the query plan: open files, allocate storage
774 * and start up the rule manager
775 * ----------------------------------------------------------------
778 InitPlan(QueryDesc *queryDesc, int eflags)
780 CmdType operation = queryDesc->operation;
781 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
782 Plan *plan = plannedstmt->planTree;
783 List *rangeTable = plannedstmt->rtable;
784 EState *estate = queryDesc->estate;
785 PlanState *planstate;
791 * Do permissions checks
793 ExecCheckRTPerms(rangeTable, true);
796 * initialize the node's execution state
798 estate->es_range_table = rangeTable;
799 estate->es_plannedstmt = plannedstmt;
802 * initialize result relation stuff, and open/lock the result rels.
804 * We must do this before initializing the plan tree, else we might try to
805 * do a lock upgrade if a result rel is also a source rel.
807 if (plannedstmt->resultRelations)
809 List *resultRelations = plannedstmt->resultRelations;
810 int numResultRelations = list_length(resultRelations);
811 ResultRelInfo *resultRelInfos;
812 ResultRelInfo *resultRelInfo;
814 resultRelInfos = (ResultRelInfo *)
815 palloc(numResultRelations * sizeof(ResultRelInfo));
816 resultRelInfo = resultRelInfos;
817 foreach(l, resultRelations)
819 Index resultRelationIndex = lfirst_int(l);
820 Oid resultRelationOid;
821 Relation resultRelation;
823 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
824 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
825 InitResultRelInfo(resultRelInfo,
828 estate->es_instrument);
831 estate->es_result_relations = resultRelInfos;
832 estate->es_num_result_relations = numResultRelations;
833 /* es_result_relation_info is NULL except when within ModifyTable */
834 estate->es_result_relation_info = NULL;
839 * if no result relation, then set state appropriately
841 estate->es_result_relations = NULL;
842 estate->es_num_result_relations = 0;
843 estate->es_result_relation_info = NULL;
847 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
848 * before we initialize the plan tree, else we'd be risking lock upgrades.
849 * While we are at it, build the ExecRowMark list.
851 estate->es_rowMarks = NIL;
852 foreach(l, plannedstmt->rowMarks)
854 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
859 /* ignore "parent" rowmarks; they are irrelevant at runtime */
863 /* get relation's OID (will produce InvalidOid if subquery) */
864 relid = getrelid(rc->rti, rangeTable);
867 * If you change the conditions under which rel locks are acquired
868 * here, be sure to adjust ExecOpenScanRelation to match.
870 switch (rc->markType)
872 case ROW_MARK_EXCLUSIVE:
873 case ROW_MARK_NOKEYEXCLUSIVE:
875 case ROW_MARK_KEYSHARE:
876 relation = heap_open(relid, RowShareLock);
878 case ROW_MARK_REFERENCE:
879 relation = heap_open(relid, AccessShareLock);
882 /* no physical table access is required */
886 elog(ERROR, "unrecognized markType: %d", rc->markType);
887 relation = NULL; /* keep compiler quiet */
891 /* Check that relation is a legal target for marking */
893 CheckValidRowMarkRel(relation, rc->markType);
895 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
896 erm->relation = relation;
899 erm->prti = rc->prti;
900 erm->rowmarkId = rc->rowmarkId;
901 erm->markType = rc->markType;
902 erm->strength = rc->strength;
903 erm->waitPolicy = rc->waitPolicy;
904 erm->ermActive = false;
905 ItemPointerSetInvalid(&(erm->curCtid));
906 erm->ermExtra = NULL;
907 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
911 * Initialize the executor's tuple table to empty.
913 estate->es_tupleTable = NIL;
914 estate->es_trig_tuple_slot = NULL;
915 estate->es_trig_oldtup_slot = NULL;
916 estate->es_trig_newtup_slot = NULL;
918 /* mark EvalPlanQual not active */
919 estate->es_epqTuple = NULL;
920 estate->es_epqTupleSet = NULL;
921 estate->es_epqScanDone = NULL;
924 * Initialize private state information for each SubPlan. We must do this
925 * before running ExecInitNode on the main query tree, since
926 * ExecInitSubPlan expects to be able to find these entries.
928 Assert(estate->es_subplanstates == NIL);
929 i = 1; /* subplan indices count from 1 */
930 foreach(l, plannedstmt->subplans)
932 Plan *subplan = (Plan *) lfirst(l);
933 PlanState *subplanstate;
937 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
938 * it is a parameterless subplan (not initplan), we suggest that it be
939 * prepared to handle REWIND efficiently; otherwise there is no need.
942 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
943 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
944 sp_eflags |= EXEC_FLAG_REWIND;
946 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
948 estate->es_subplanstates = lappend(estate->es_subplanstates,
955 * Initialize the private state information for all the nodes in the query
956 * tree. This opens files, allocates storage and leaves us ready to start
959 planstate = ExecInitNode(plan, estate, eflags);
962 * Get the tuple descriptor describing the type of tuples to return.
964 tupType = ExecGetResultType(planstate);
967 * Initialize the junk filter if needed. SELECT queries need a filter if
968 * there are any junk attrs in the top-level tlist.
970 if (operation == CMD_SELECT)
972 bool junk_filter_needed = false;
975 foreach(tlist, plan->targetlist)
977 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
981 junk_filter_needed = true;
986 if (junk_filter_needed)
990 j = ExecInitJunkFilter(planstate->plan->targetlist,
992 ExecInitExtraTupleSlot(estate));
993 estate->es_junkFilter = j;
995 /* Want to return the cleaned tuple type */
996 tupType = j->jf_cleanTupType;
1000 queryDesc->tupDesc = tupType;
1001 queryDesc->planstate = planstate;
1005 * Check that a proposed result relation is a legal target for the operation
1007 * Generally the parser and/or planner should have noticed any such mistake
1008 * already, but let's make sure.
1010 * Note: when changing this function, you probably also need to look at
1011 * CheckValidRowMarkRel.
1014 CheckValidResultRel(Relation resultRel, CmdType operation)
1016 TriggerDesc *trigDesc = resultRel->trigdesc;
1017 FdwRoutine *fdwroutine;
1019 switch (resultRel->rd_rel->relkind)
1021 case RELKIND_RELATION:
1024 case RELKIND_SEQUENCE:
1026 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1027 errmsg("cannot change sequence \"%s\"",
1028 RelationGetRelationName(resultRel))));
1030 case RELKIND_TOASTVALUE:
1032 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1033 errmsg("cannot change TOAST relation \"%s\"",
1034 RelationGetRelationName(resultRel))));
1039 * Okay only if there's a suitable INSTEAD OF trigger. Messages
1040 * here should match rewriteHandler.c's rewriteTargetView, except
1041 * that we omit errdetail because we haven't got the information
1042 * handy (and given that we really shouldn't get here anyway, it's
1043 * not worth great exertion to get).
1048 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1050 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1051 errmsg("cannot insert into view \"%s\"",
1052 RelationGetRelationName(resultRel)),
1053 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1056 if (!trigDesc || !trigDesc->trig_update_instead_row)
1058 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1059 errmsg("cannot update view \"%s\"",
1060 RelationGetRelationName(resultRel)),
1061 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1064 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1066 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1067 errmsg("cannot delete from view \"%s\"",
1068 RelationGetRelationName(resultRel)),
1069 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1072 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1076 case RELKIND_MATVIEW:
1077 if (!MatViewIncrementalMaintenanceIsEnabled())
1079 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1080 errmsg("cannot change materialized view \"%s\"",
1081 RelationGetRelationName(resultRel))));
1083 case RELKIND_FOREIGN_TABLE:
1084 /* Okay only if the FDW supports it */
1085 fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1089 if (fdwroutine->ExecForeignInsert == NULL)
1091 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1092 errmsg("cannot insert into foreign table \"%s\"",
1093 RelationGetRelationName(resultRel))));
1094 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1095 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1097 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1098 errmsg("foreign table \"%s\" does not allow inserts",
1099 RelationGetRelationName(resultRel))));
1102 if (fdwroutine->ExecForeignUpdate == NULL)
1104 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1105 errmsg("cannot update foreign table \"%s\"",
1106 RelationGetRelationName(resultRel))));
1107 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1108 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1110 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1111 errmsg("foreign table \"%s\" does not allow updates",
1112 RelationGetRelationName(resultRel))));
1115 if (fdwroutine->ExecForeignDelete == NULL)
1117 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1118 errmsg("cannot delete from foreign table \"%s\"",
1119 RelationGetRelationName(resultRel))));
1120 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1121 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1123 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1124 errmsg("foreign table \"%s\" does not allow deletes",
1125 RelationGetRelationName(resultRel))));
1128 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1134 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1135 errmsg("cannot change relation \"%s\"",
1136 RelationGetRelationName(resultRel))));
1142 * Check that a proposed rowmark target relation is a legal target
1144 * In most cases parser and/or planner should have noticed this already, but
1145 * they don't cover all cases.
1148 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1150 FdwRoutine *fdwroutine;
1152 switch (rel->rd_rel->relkind)
1154 case RELKIND_RELATION:
1157 case RELKIND_SEQUENCE:
1158 /* Must disallow this because we don't vacuum sequences */
1160 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1161 errmsg("cannot lock rows in sequence \"%s\"",
1162 RelationGetRelationName(rel))));
1164 case RELKIND_TOASTVALUE:
1165 /* We could allow this, but there seems no good reason to */
1167 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1168 errmsg("cannot lock rows in TOAST relation \"%s\"",
1169 RelationGetRelationName(rel))));
1172 /* Should not get here; planner should have expanded the view */
1174 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1175 errmsg("cannot lock rows in view \"%s\"",
1176 RelationGetRelationName(rel))));
1178 case RELKIND_MATVIEW:
1179 /* Allow referencing a matview, but not actual locking clauses */
1180 if (markType != ROW_MARK_REFERENCE)
1182 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1183 errmsg("cannot lock rows in materialized view \"%s\"",
1184 RelationGetRelationName(rel))));
1186 case RELKIND_FOREIGN_TABLE:
1187 /* Okay only if the FDW supports it */
1188 fdwroutine = GetFdwRoutineForRelation(rel, false);
1189 if (fdwroutine->RefetchForeignRow == NULL)
1191 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1192 errmsg("cannot lock rows in foreign table \"%s\"",
1193 RelationGetRelationName(rel))));
1197 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1198 errmsg("cannot lock rows in relation \"%s\"",
1199 RelationGetRelationName(rel))));
1205 * Initialize ResultRelInfo data for one result relation
1207 * Caution: before Postgres 9.1, this function included the relkind checking
1208 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1209 * appropriate. Be sure callers cover those needs.
1212 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1213 Relation resultRelationDesc,
1214 Index resultRelationIndex,
1215 int instrument_options)
1217 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1218 resultRelInfo->type = T_ResultRelInfo;
1219 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1220 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1221 resultRelInfo->ri_NumIndices = 0;
1222 resultRelInfo->ri_IndexRelationDescs = NULL;
1223 resultRelInfo->ri_IndexRelationInfo = NULL;
1224 /* make a copy so as not to depend on relcache info not changing... */
1225 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1226 if (resultRelInfo->ri_TrigDesc)
1228 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1230 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1231 palloc0(n * sizeof(FmgrInfo));
1232 resultRelInfo->ri_TrigWhenExprs = (List **)
1233 palloc0(n * sizeof(List *));
1234 if (instrument_options)
1235 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1239 resultRelInfo->ri_TrigFunctions = NULL;
1240 resultRelInfo->ri_TrigWhenExprs = NULL;
1241 resultRelInfo->ri_TrigInstrument = NULL;
1243 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1244 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1246 resultRelInfo->ri_FdwRoutine = NULL;
1247 resultRelInfo->ri_FdwState = NULL;
1248 resultRelInfo->ri_usesFdwDirectModify = false;
1249 resultRelInfo->ri_ConstraintExprs = NULL;
1250 resultRelInfo->ri_junkFilter = NULL;
1251 resultRelInfo->ri_projectReturning = NULL;
1255 * ExecGetTriggerResultRel
1257 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1258 * triggers are fired on one of the result relations of the query, and so
1259 * we can just return a member of the es_result_relations array. (Note: in
1260 * self-join situations there might be multiple members with the same OID;
1261 * if so it doesn't matter which one we pick.) However, it is sometimes
1262 * necessary to fire triggers on other relations; this happens mainly when an
1263 * RI update trigger queues additional triggers on other relations, which will
1264 * be processed in the context of the outer query. For efficiency's sake,
1265 * we want to have a ResultRelInfo for those triggers too; that can avoid
1266 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1267 * ANALYZE to report the runtimes of such triggers.) So we make additional
1268 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1271 ExecGetTriggerResultRel(EState *estate, Oid relid)
1273 ResultRelInfo *rInfo;
1277 MemoryContext oldcontext;
1279 /* First, search through the query result relations */
1280 rInfo = estate->es_result_relations;
1281 nr = estate->es_num_result_relations;
1284 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1289 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1290 foreach(l, estate->es_trig_target_relations)
1292 rInfo = (ResultRelInfo *) lfirst(l);
1293 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1296 /* Nope, so we need a new one */
1299 * Open the target relation's relcache entry. We assume that an
1300 * appropriate lock is still held by the backend from whenever the trigger
1301 * event got queued, so we need take no new lock here. Also, we need not
1302 * recheck the relkind, so no need for CheckValidResultRel.
1304 rel = heap_open(relid, NoLock);
1307 * Make the new entry in the right context.
1309 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1310 rInfo = makeNode(ResultRelInfo);
1311 InitResultRelInfo(rInfo,
1313 0, /* dummy rangetable index */
1314 estate->es_instrument);
1315 estate->es_trig_target_relations =
1316 lappend(estate->es_trig_target_relations, rInfo);
1317 MemoryContextSwitchTo(oldcontext);
1320 * Currently, we don't need any index information in ResultRelInfos used
1321 * only for triggers, so no need to call ExecOpenIndices.
1328 * ExecContextForcesOids
1330 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1331 * we need to ensure that result tuples have space for an OID iff they are
1332 * going to be stored into a relation that has OIDs. In other contexts
1333 * we are free to choose whether to leave space for OIDs in result tuples
1334 * (we generally don't want to, but we do if a physical-tlist optimization
1335 * is possible). This routine checks the plan context and returns TRUE if the
1336 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1337 * *hasoids is set to the required value.
1339 * One reason this is ugly is that all plan nodes in the plan tree will emit
1340 * tuples with space for an OID, though we really only need the topmost node
1341 * to do so. However, node types like Sort don't project new tuples but just
1342 * return their inputs, and in those cases the requirement propagates down
1343 * to the input node. Eventually we might make this code smart enough to
1344 * recognize how far down the requirement really goes, but for now we just
1345 * make all plan nodes do the same thing if the top level forces the choice.
1347 * We assume that if we are generating tuples for INSERT or UPDATE,
1348 * estate->es_result_relation_info is already set up to describe the target
1349 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1350 * the target relations may have OIDs and some not. We have to make the
1351 * decisions on a per-relation basis as we initialize each of the subplans of
1352 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1353 * while initializing each subplan.
1355 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1356 * descriptor available when this code runs; we have to look aside at the
1357 * flags passed to ExecutorStart().
1360 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1362 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1366 Relation rel = ri->ri_RelationDesc;
1370 *hasoids = rel->rd_rel->relhasoids;
1375 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1380 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1389 /* ----------------------------------------------------------------
1390 * ExecPostprocessPlan
1392 * Give plan nodes a final chance to execute before shutdown
1393 * ----------------------------------------------------------------
1396 ExecPostprocessPlan(EState *estate)
1401 * Make sure nodes run forward.
1403 estate->es_direction = ForwardScanDirection;
1406 * Run any secondary ModifyTable nodes to completion, in case the main
1407 * query did not fetch all rows from them. (We do this to ensure that
1408 * such nodes have predictable results.)
1410 foreach(lc, estate->es_auxmodifytables)
1412 PlanState *ps = (PlanState *) lfirst(lc);
1416 TupleTableSlot *slot;
1418 /* Reset the per-output-tuple exprcontext each time */
1419 ResetPerTupleExprContext(estate);
1421 slot = ExecProcNode(ps);
1423 if (TupIsNull(slot))
1429 /* ----------------------------------------------------------------
1432 * Cleans up the query plan -- closes files and frees up storage
1434 * NOTE: we are no longer very worried about freeing storage per se
1435 * in this code; FreeExecutorState should be guaranteed to release all
1436 * memory that needs to be released. What we are worried about doing
1437 * is closing relations and dropping buffer pins. Thus, for example,
1438 * tuple tables must be cleared or dropped to ensure pins are released.
1439 * ----------------------------------------------------------------
1442 ExecEndPlan(PlanState *planstate, EState *estate)
1444 ResultRelInfo *resultRelInfo;
1449 * shut down the node-type-specific query processing
1451 ExecEndNode(planstate);
1456 foreach(l, estate->es_subplanstates)
1458 PlanState *subplanstate = (PlanState *) lfirst(l);
1460 ExecEndNode(subplanstate);
1464 * destroy the executor's tuple table. Actually we only care about
1465 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1466 * the TupleTableSlots, since the containing memory context is about to go
1469 ExecResetTupleTable(estate->es_tupleTable, false);
1472 * close the result relation(s) if any, but hold locks until xact commit.
1474 resultRelInfo = estate->es_result_relations;
1475 for (i = estate->es_num_result_relations; i > 0; i--)
1477 /* Close indices and then the relation itself */
1478 ExecCloseIndices(resultRelInfo);
1479 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1484 * likewise close any trigger target relations
1486 foreach(l, estate->es_trig_target_relations)
1488 resultRelInfo = (ResultRelInfo *) lfirst(l);
1489 /* Close indices and then the relation itself */
1490 ExecCloseIndices(resultRelInfo);
1491 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1495 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1498 foreach(l, estate->es_rowMarks)
1500 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1503 heap_close(erm->relation, NoLock);
1507 /* ----------------------------------------------------------------
1510 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1511 * moving in the specified direction.
1513 * Runs to completion if numberTuples is 0
1515 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1517 * ----------------------------------------------------------------
1520 ExecutePlan(EState *estate,
1521 PlanState *planstate,
1522 bool use_parallel_mode,
1525 uint64 numberTuples,
1526 ScanDirection direction,
1529 TupleTableSlot *slot;
1530 uint64 current_tuple_count;
1533 * initialize local variables
1535 current_tuple_count = 0;
1538 * Set the direction.
1540 estate->es_direction = direction;
1543 * If a tuple count was supplied or data is being written to relation, we
1544 * must force the plan to run without parallelism, because we might exit
1547 if (numberTuples || dest->mydest == DestIntoRel)
1548 use_parallel_mode = false;
1551 * If a tuple count was supplied, we must force the plan to run without
1552 * parallelism, because we might exit early.
1554 if (use_parallel_mode)
1555 EnterParallelMode();
1558 * Loop until we've processed the proper number of tuples from the plan.
1562 /* Reset the per-output-tuple exprcontext */
1563 ResetPerTupleExprContext(estate);
1566 * Execute the plan and obtain a tuple
1568 slot = ExecProcNode(planstate);
1571 * if the tuple is null, then we assume there is nothing more to
1572 * process so we just end the loop...
1574 if (TupIsNull(slot))
1576 /* Allow nodes to release or shut down resources. */
1577 (void) ExecShutdownNode(planstate);
1582 * If we have a junk filter, then project a new tuple with the junk
1585 * Store this new "clean" tuple in the junkfilter's resultSlot.
1586 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1587 * because that tuple slot has the wrong descriptor.)
1589 if (estate->es_junkFilter != NULL)
1590 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1593 * If we are supposed to send the tuple somewhere, do so. (In
1594 * practice, this is probably always the case at this point.)
1599 * If we are not able to send the tuple, we assume the destination
1600 * has closed and no more tuples can be sent. If that's the case,
1603 if (!((*dest->receiveSlot) (slot, dest)))
1608 * Count tuples processed, if this is a SELECT. (For other operation
1609 * types, the ModifyTable plan node must count the appropriate
1612 if (operation == CMD_SELECT)
1613 (estate->es_processed)++;
1616 * check our tuple count.. if we've processed the proper number then
1617 * quit, else loop again and process more tuples. Zero numberTuples
1620 current_tuple_count++;
1621 if (numberTuples && numberTuples == current_tuple_count)
1625 if (use_parallel_mode)
1631 * ExecRelCheck --- check that tuple meets constraints for result relation
1633 * Returns NULL if OK, else name of failed check constraint
1636 ExecRelCheck(ResultRelInfo *resultRelInfo,
1637 TupleTableSlot *slot, EState *estate)
1639 Relation rel = resultRelInfo->ri_RelationDesc;
1640 int ncheck = rel->rd_att->constr->num_check;
1641 ConstrCheck *check = rel->rd_att->constr->check;
1642 ExprContext *econtext;
1643 MemoryContext oldContext;
1648 * If first time through for this result relation, build expression
1649 * nodetrees for rel's constraint expressions. Keep them in the per-query
1650 * memory context so they'll survive throughout the query.
1652 if (resultRelInfo->ri_ConstraintExprs == NULL)
1654 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1655 resultRelInfo->ri_ConstraintExprs =
1656 (List **) palloc(ncheck * sizeof(List *));
1657 for (i = 0; i < ncheck; i++)
1659 /* ExecQual wants implicit-AND form */
1660 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1661 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1662 ExecPrepareExpr((Expr *) qual, estate);
1664 MemoryContextSwitchTo(oldContext);
1668 * We will use the EState's per-tuple context for evaluating constraint
1669 * expressions (creating it if it's not already there).
1671 econtext = GetPerTupleExprContext(estate);
1673 /* Arrange for econtext's scan tuple to be the tuple under test */
1674 econtext->ecxt_scantuple = slot;
1676 /* And evaluate the constraints */
1677 for (i = 0; i < ncheck; i++)
1679 qual = resultRelInfo->ri_ConstraintExprs[i];
1682 * NOTE: SQL specifies that a NULL result from a constraint expression
1683 * is not to be treated as a failure. Therefore, tell ExecQual to
1684 * return TRUE for NULL.
1686 if (!ExecQual(qual, econtext, true))
1687 return check[i].ccname;
1690 /* NULL result means no error */
1695 ExecConstraints(ResultRelInfo *resultRelInfo,
1696 TupleTableSlot *slot, EState *estate)
1698 Relation rel = resultRelInfo->ri_RelationDesc;
1699 TupleDesc tupdesc = RelationGetDescr(rel);
1700 TupleConstr *constr = tupdesc->constr;
1701 Bitmapset *modifiedCols;
1702 Bitmapset *insertedCols;
1703 Bitmapset *updatedCols;
1707 if (constr->has_not_null)
1709 int natts = tupdesc->natts;
1712 for (attrChk = 1; attrChk <= natts; attrChk++)
1714 if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1715 slot_attisnull(slot, attrChk))
1719 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1720 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1721 modifiedCols = bms_union(insertedCols, updatedCols);
1722 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1729 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1730 errmsg("null value in column \"%s\" violates not-null constraint",
1731 NameStr(tupdesc->attrs[attrChk - 1]->attname)),
1732 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1733 errtablecol(rel, attrChk)));
1738 if (constr->num_check > 0)
1742 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1746 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1747 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1748 modifiedCols = bms_union(insertedCols, updatedCols);
1749 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1755 (errcode(ERRCODE_CHECK_VIOLATION),
1756 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1757 RelationGetRelationName(rel), failed),
1758 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1759 errtableconstraint(rel, failed)));
1765 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1766 * of the specified kind.
1768 * Note that this needs to be called multiple times to ensure that all kinds of
1769 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
1770 * CHECK OPTION set and from row level security policies). See ExecInsert()
1774 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
1775 TupleTableSlot *slot, EState *estate)
1777 Relation rel = resultRelInfo->ri_RelationDesc;
1778 TupleDesc tupdesc = RelationGetDescr(rel);
1779 ExprContext *econtext;
1784 * We will use the EState's per-tuple context for evaluating constraint
1785 * expressions (creating it if it's not already there).
1787 econtext = GetPerTupleExprContext(estate);
1789 /* Arrange for econtext's scan tuple to be the tuple under test */
1790 econtext->ecxt_scantuple = slot;
1792 /* Check each of the constraints */
1793 forboth(l1, resultRelInfo->ri_WithCheckOptions,
1794 l2, resultRelInfo->ri_WithCheckOptionExprs)
1796 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1797 ExprState *wcoExpr = (ExprState *) lfirst(l2);
1800 * Skip any WCOs which are not the kind we are looking for at this
1803 if (wco->kind != kind)
1807 * WITH CHECK OPTION checks are intended to ensure that the new tuple
1808 * is visible (in the case of a view) or that it passes the
1809 * 'with-check' policy (in the case of row security). If the qual
1810 * evaluates to NULL or FALSE, then the new tuple won't be included in
1811 * the view or doesn't pass the 'with-check' policy for the table. We
1812 * need ExecQual to return FALSE for NULL to handle the view case (the
1813 * opposite of what we do above for CHECK constraints).
1815 if (!ExecQual((List *) wcoExpr, econtext, false))
1818 Bitmapset *modifiedCols;
1819 Bitmapset *insertedCols;
1820 Bitmapset *updatedCols;
1825 * For WITH CHECK OPTIONs coming from views, we might be
1826 * able to provide the details on the row, depending on
1827 * the permissions on the relation (that is, if the user
1828 * could view it directly anyway). For RLS violations, we
1829 * don't include the data since we don't know if the user
1830 * should be able to view the tuple as as that depends on
1833 case WCO_VIEW_CHECK:
1834 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1835 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1836 modifiedCols = bms_union(insertedCols, updatedCols);
1837 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1844 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1845 errmsg("new row violates check option for view \"%s\"",
1847 val_desc ? errdetail("Failing row contains %s.",
1850 case WCO_RLS_INSERT_CHECK:
1851 case WCO_RLS_UPDATE_CHECK:
1852 if (wco->polname != NULL)
1854 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1855 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
1856 wco->polname, wco->relname)));
1859 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1860 errmsg("new row violates row-level security policy for table \"%s\"",
1863 case WCO_RLS_CONFLICT_CHECK:
1864 if (wco->polname != NULL)
1866 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1867 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
1868 wco->polname, wco->relname)));
1871 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1872 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
1876 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
1884 * ExecBuildSlotValueDescription -- construct a string representing a tuple
1886 * This is intentionally very similar to BuildIndexValueDescription, but
1887 * unlike that function, we truncate long field values (to at most maxfieldlen
1888 * bytes). That seems necessary here since heap field values could be very
1889 * long, whereas index entries typically aren't so wide.
1891 * Also, unlike the case with index entries, we need to be prepared to ignore
1892 * dropped columns. We used to use the slot's tuple descriptor to decode the
1893 * data, but the slot's descriptor doesn't identify dropped columns, so we
1894 * now need to be passed the relation's descriptor.
1896 * Note that, like BuildIndexValueDescription, if the user does not have
1897 * permission to view any of the columns involved, a NULL is returned. Unlike
1898 * BuildIndexValueDescription, if the user has access to view a subset of the
1899 * column involved, that subset will be returned with a key identifying which
1903 ExecBuildSlotValueDescription(Oid reloid,
1904 TupleTableSlot *slot,
1906 Bitmapset *modifiedCols,
1910 StringInfoData collist;
1911 bool write_comma = false;
1912 bool write_comma_collist = false;
1914 AclResult aclresult;
1915 bool table_perm = false;
1916 bool any_perm = false;
1919 * Check if RLS is enabled and should be active for the relation; if so,
1920 * then don't return anything. Otherwise, go through normal permission
1923 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
1926 initStringInfo(&buf);
1928 appendStringInfoChar(&buf, '(');
1931 * Check if the user has permissions to see the row. Table-level SELECT
1932 * allows access to all columns. If the user does not have table-level
1933 * SELECT then we check each column and include those the user has SELECT
1934 * rights on. Additionally, we always include columns the user provided
1937 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
1938 if (aclresult != ACLCHECK_OK)
1940 /* Set up the buffer for the column list */
1941 initStringInfo(&collist);
1942 appendStringInfoChar(&collist, '(');
1945 table_perm = any_perm = true;
1947 /* Make sure the tuple is fully deconstructed */
1948 slot_getallattrs(slot);
1950 for (i = 0; i < tupdesc->natts; i++)
1952 bool column_perm = false;
1956 /* ignore dropped columns */
1957 if (tupdesc->attrs[i]->attisdropped)
1963 * No table-level SELECT, so need to make sure they either have
1964 * SELECT rights on the column or that they have provided the data
1965 * for the column. If not, omit this column from the error
1968 aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
1969 GetUserId(), ACL_SELECT);
1970 if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
1971 modifiedCols) || aclresult == ACLCHECK_OK)
1973 column_perm = any_perm = true;
1975 if (write_comma_collist)
1976 appendStringInfoString(&collist, ", ");
1978 write_comma_collist = true;
1980 appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
1984 if (table_perm || column_perm)
1986 if (slot->tts_isnull[i])
1993 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1994 &foutoid, &typisvarlena);
1995 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1999 appendStringInfoString(&buf, ", ");
2003 /* truncate if needed */
2004 vallen = strlen(val);
2005 if (vallen <= maxfieldlen)
2006 appendStringInfoString(&buf, val);
2009 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2010 appendBinaryStringInfo(&buf, val, vallen);
2011 appendStringInfoString(&buf, "...");
2016 /* If we end up with zero columns being returned, then return NULL. */
2020 appendStringInfoChar(&buf, ')');
2024 appendStringInfoString(&collist, ") = ");
2025 appendStringInfoString(&collist, buf.data);
2027 return collist.data;
2035 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2036 * given ResultRelInfo
2039 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2042 Bitmapset *updatedCols;
2045 * Compute lock mode to use. If columns that are part of the key have not
2046 * been modified, then we can use a weaker lock, allowing for better
2049 updatedCols = GetUpdatedColumns(relinfo, estate);
2050 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2051 INDEX_ATTR_BITMAP_KEY);
2053 if (bms_overlap(keyCols, updatedCols))
2054 return LockTupleExclusive;
2056 return LockTupleNoKeyExclusive;
2060 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2062 * If no such struct, either return NULL or throw error depending on missing_ok
2065 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2069 foreach(lc, estate->es_rowMarks)
2071 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2073 if (erm->rti == rti)
2077 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2082 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2084 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2085 * input plan node (not planstate node!). We need the latter to find out
2086 * the column numbers of the resjunk columns.
2089 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2091 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2094 aerm->rowmark = erm;
2096 /* Look up the resjunk columns associated with this rowmark */
2097 if (erm->markType != ROW_MARK_COPY)
2099 /* need ctid for all methods other than COPY */
2100 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2101 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2103 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2104 elog(ERROR, "could not find junk %s column", resname);
2108 /* need wholerow if COPY */
2109 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2110 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2112 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2113 elog(ERROR, "could not find junk %s column", resname);
2116 /* if child rel, need tableoid */
2117 if (erm->rti != erm->prti)
2119 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2120 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2122 if (!AttributeNumberIsValid(aerm->toidAttNo))
2123 elog(ERROR, "could not find junk %s column", resname);
2131 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2132 * process the updated version under READ COMMITTED rules.
2134 * See backend/executor/README for some info about how this works.
2139 * Check a modified tuple to see if we want to process its updated version
2140 * under READ COMMITTED rules.
2142 * estate - outer executor state data
2143 * epqstate - state for EvalPlanQual rechecking
2144 * relation - table containing tuple
2145 * rti - rangetable index of table containing tuple
2146 * lockmode - requested tuple lock mode
2147 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2148 * priorXmax - t_xmax from the outdated tuple
2150 * *tid is also an output parameter: it's modified to hold the TID of the
2151 * latest version of the tuple (note this may be changed even on failure)
2153 * Returns a slot containing the new candidate update/delete tuple, or
2154 * NULL if we determine we shouldn't process the row.
2156 * Note: properly, lockmode should be declared as enum LockTupleMode,
2157 * but we use "int" to avoid having to include heapam.h in executor.h.
2160 EvalPlanQual(EState *estate, EPQState *epqstate,
2161 Relation relation, Index rti, int lockmode,
2162 ItemPointer tid, TransactionId priorXmax)
2164 TupleTableSlot *slot;
2165 HeapTuple copyTuple;
2170 * Get and lock the updated version of the row; if fail, return NULL.
2172 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2175 if (copyTuple == NULL)
2179 * For UPDATE/DELETE we have to return tid of actual row we're executing
2182 *tid = copyTuple->t_self;
2185 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2187 EvalPlanQualBegin(epqstate, estate);
2190 * Free old test tuple, if any, and store new tuple where relation's scan
2193 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2196 * Fetch any non-locked source rows
2198 EvalPlanQualFetchRowMarks(epqstate);
2201 * Run the EPQ query. We assume it will return at most one tuple.
2203 slot = EvalPlanQualNext(epqstate);
2206 * If we got a tuple, force the slot to materialize the tuple so that it
2207 * is not dependent on any local state in the EPQ query (in particular,
2208 * it's highly likely that the slot contains references to any pass-by-ref
2209 * datums that may be present in copyTuple). As with the next step, this
2210 * is to guard against early re-use of the EPQ query.
2212 if (!TupIsNull(slot))
2213 (void) ExecMaterializeSlot(slot);
2216 * Clear out the test tuple. This is needed in case the EPQ query is
2217 * re-used to test a tuple for a different relation. (Not clear that can
2218 * really happen, but let's be safe.)
2220 EvalPlanQualSetTuple(epqstate, rti, NULL);
2226 * Fetch a copy of the newest version of an outdated tuple
2228 * estate - executor state data
2229 * relation - table containing tuple
2230 * lockmode - requested tuple lock mode
2231 * wait_policy - requested lock wait policy
2232 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2233 * priorXmax - t_xmax from the outdated tuple
2235 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2236 * that there is no newest version (ie, the row was deleted not updated).
2237 * We also return NULL if the tuple is locked and the wait policy is to skip
2240 * If successful, we have locked the newest tuple version, so caller does not
2241 * need to worry about it changing anymore.
2243 * Note: properly, lockmode should be declared as enum LockTupleMode,
2244 * but we use "int" to avoid having to include heapam.h in executor.h.
2247 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2248 LockWaitPolicy wait_policy,
2249 ItemPointer tid, TransactionId priorXmax)
2251 HeapTuple copyTuple = NULL;
2252 HeapTupleData tuple;
2253 SnapshotData SnapshotDirty;
2256 * fetch target tuple
2258 * Loop here to deal with updated or busy tuples
2260 InitDirtySnapshot(SnapshotDirty);
2261 tuple.t_self = *tid;
2266 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2269 HeapUpdateFailureData hufd;
2272 * If xmin isn't what we're expecting, the slot must have been
2273 * recycled and reused for an unrelated tuple. This implies that
2274 * the latest version of the row was deleted, so we need do
2275 * nothing. (Should be safe to examine xmin without getting
2276 * buffer's content lock. We assume reading a TransactionId to be
2277 * atomic, and Xmin never changes in an existing tuple, except to
2278 * invalid or frozen, and neither of those can match priorXmax.)
2280 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2283 ReleaseBuffer(buffer);
2287 /* otherwise xmin should not be dirty... */
2288 if (TransactionIdIsValid(SnapshotDirty.xmin))
2289 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2292 * If tuple is being updated by other transaction then we have to
2293 * wait for its commit/abort, or die trying.
2295 if (TransactionIdIsValid(SnapshotDirty.xmax))
2297 ReleaseBuffer(buffer);
2298 switch (wait_policy)
2301 XactLockTableWait(SnapshotDirty.xmax,
2302 relation, &tuple.t_self,
2306 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2307 return NULL; /* skip instead of waiting */
2310 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2312 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2313 errmsg("could not obtain lock on row in relation \"%s\"",
2314 RelationGetRelationName(relation))));
2317 continue; /* loop back to repeat heap_fetch */
2321 * If tuple was inserted by our own transaction, we have to check
2322 * cmin against es_output_cid: cmin >= current CID means our
2323 * command cannot see the tuple, so we should ignore it. Otherwise
2324 * heap_lock_tuple() will throw an error, and so would any later
2325 * attempt to update or delete the tuple. (We need not check cmax
2326 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2327 * by our transaction dead, regardless of cmax.) We just checked
2328 * that priorXmax == xmin, so we can test that variable instead of
2329 * doing HeapTupleHeaderGetXmin again.
2331 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2332 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2334 ReleaseBuffer(buffer);
2339 * This is a live tuple, so now try to lock it.
2341 test = heap_lock_tuple(relation, &tuple,
2342 estate->es_output_cid,
2343 lockmode, wait_policy,
2344 false, &buffer, &hufd);
2345 /* We now have two pins on the buffer, get rid of one */
2346 ReleaseBuffer(buffer);
2350 case HeapTupleSelfUpdated:
2353 * The target tuple was already updated or deleted by the
2354 * current command, or by a later command in the current
2355 * transaction. We *must* ignore the tuple in the former
2356 * case, so as to avoid the "Halloween problem" of
2357 * repeated update attempts. In the latter case it might
2358 * be sensible to fetch the updated tuple instead, but
2359 * doing so would require changing heap_update and
2360 * heap_delete to not complain about updating "invisible"
2361 * tuples, which seems pretty scary (heap_lock_tuple will
2362 * not complain, but few callers expect
2363 * HeapTupleInvisible, and we're not one of them). So for
2364 * now, treat the tuple as deleted and do not process.
2366 ReleaseBuffer(buffer);
2369 case HeapTupleMayBeUpdated:
2370 /* successfully locked */
2373 case HeapTupleUpdated:
2374 ReleaseBuffer(buffer);
2375 if (IsolationUsesXactSnapshot())
2377 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2378 errmsg("could not serialize access due to concurrent update")));
2380 /* Should not encounter speculative tuple on recheck */
2381 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2382 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2384 /* it was updated, so look at the updated version */
2385 tuple.t_self = hufd.ctid;
2386 /* updated row should have xmin matching this xmax */
2387 priorXmax = hufd.xmax;
2390 /* tuple was deleted, so give up */
2393 case HeapTupleWouldBlock:
2394 ReleaseBuffer(buffer);
2397 case HeapTupleInvisible:
2398 elog(ERROR, "attempted to lock invisible tuple");
2401 ReleaseBuffer(buffer);
2402 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2404 return NULL; /* keep compiler quiet */
2408 * We got tuple - now copy it for use by recheck query.
2410 copyTuple = heap_copytuple(&tuple);
2411 ReleaseBuffer(buffer);
2416 * If the referenced slot was actually empty, the latest version of
2417 * the row must have been deleted, so we need do nothing.
2419 if (tuple.t_data == NULL)
2421 ReleaseBuffer(buffer);
2426 * As above, if xmin isn't what we're expecting, do nothing.
2428 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2431 ReleaseBuffer(buffer);
2436 * If we get here, the tuple was found but failed SnapshotDirty.
2437 * Assuming the xmin is either a committed xact or our own xact (as it
2438 * certainly should be if we're trying to modify the tuple), this must
2439 * mean that the row was updated or deleted by either a committed xact
2440 * or our own xact. If it was deleted, we can ignore it; if it was
2441 * updated then chain up to the next version and repeat the whole
2444 * As above, it should be safe to examine xmax and t_ctid without the
2445 * buffer content lock, because they can't be changing.
2447 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2449 /* deleted, so forget about it */
2450 ReleaseBuffer(buffer);
2454 /* updated, so look at the updated row */
2455 tuple.t_self = tuple.t_data->t_ctid;
2456 /* updated row should have xmin matching this xmax */
2457 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2458 ReleaseBuffer(buffer);
2459 /* loop back to fetch next in chain */
2463 * Return the copied tuple
2469 * EvalPlanQualInit -- initialize during creation of a plan state node
2470 * that might need to invoke EPQ processing.
2472 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2473 * with EvalPlanQualSetPlan.
2476 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2477 Plan *subplan, List *auxrowmarks, int epqParam)
2479 /* Mark the EPQ state inactive */
2480 epqstate->estate = NULL;
2481 epqstate->planstate = NULL;
2482 epqstate->origslot = NULL;
2483 /* ... and remember data that EvalPlanQualBegin will need */
2484 epqstate->plan = subplan;
2485 epqstate->arowMarks = auxrowmarks;
2486 epqstate->epqParam = epqParam;
2490 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2492 * We need this so that ModifyTable can deal with multiple subplans.
2495 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2497 /* If we have a live EPQ query, shut it down */
2498 EvalPlanQualEnd(epqstate);
2499 /* And set/change the plan pointer */
2500 epqstate->plan = subplan;
2501 /* The rowmarks depend on the plan, too */
2502 epqstate->arowMarks = auxrowmarks;
2506 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2508 * NB: passed tuple must be palloc'd; it may get freed later
2511 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2513 EState *estate = epqstate->estate;
2518 * free old test tuple, if any, and store new tuple where relation's scan
2521 if (estate->es_epqTuple[rti - 1] != NULL)
2522 heap_freetuple(estate->es_epqTuple[rti - 1]);
2523 estate->es_epqTuple[rti - 1] = tuple;
2524 estate->es_epqTupleSet[rti - 1] = true;
2528 * Fetch back the current test tuple (if any) for the specified RTI
2531 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2533 EState *estate = epqstate->estate;
2537 return estate->es_epqTuple[rti - 1];
2541 * Fetch the current row values for any non-locked relations that need
2542 * to be scanned by an EvalPlanQual operation. origslot must have been set
2543 * to contain the current result row (top-level row) that we need to recheck.
2546 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2550 Assert(epqstate->origslot != NULL);
2552 foreach(l, epqstate->arowMarks)
2554 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2555 ExecRowMark *erm = aerm->rowmark;
2558 HeapTupleData tuple;
2560 if (RowMarkRequiresRowShareLock(erm->markType))
2561 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2563 /* clear any leftover test tuple for this rel */
2564 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2566 /* if child rel, must check whether it produced this row */
2567 if (erm->rti != erm->prti)
2571 datum = ExecGetJunkAttribute(epqstate->origslot,
2574 /* non-locked rels could be on the inside of outer joins */
2577 tableoid = DatumGetObjectId(datum);
2579 Assert(OidIsValid(erm->relid));
2580 if (tableoid != erm->relid)
2582 /* this child is inactive right now */
2587 if (erm->markType == ROW_MARK_REFERENCE)
2589 HeapTuple copyTuple;
2591 Assert(erm->relation != NULL);
2593 /* fetch the tuple's ctid */
2594 datum = ExecGetJunkAttribute(epqstate->origslot,
2597 /* non-locked rels could be on the inside of outer joins */
2601 /* fetch requests on foreign tables must be passed to their FDW */
2602 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2604 FdwRoutine *fdwroutine;
2605 bool updated = false;
2607 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2608 /* this should have been checked already, but let's be safe */
2609 if (fdwroutine->RefetchForeignRow == NULL)
2611 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2612 errmsg("cannot lock rows in foreign table \"%s\"",
2613 RelationGetRelationName(erm->relation))));
2614 copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2618 if (copyTuple == NULL)
2619 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2622 * Ideally we'd insist on updated == false here, but that
2623 * assumes that FDWs can track that exactly, which they might
2624 * not be able to. So just ignore the flag.
2629 /* ordinary table, fetch the tuple */
2632 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2633 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2635 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2637 /* successful, copy tuple */
2638 copyTuple = heap_copytuple(&tuple);
2639 ReleaseBuffer(buffer);
2643 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2649 Assert(erm->markType == ROW_MARK_COPY);
2651 /* fetch the whole-row Var for the relation */
2652 datum = ExecGetJunkAttribute(epqstate->origslot,
2655 /* non-locked rels could be on the inside of outer joins */
2658 td = DatumGetHeapTupleHeader(datum);
2660 /* build a temporary HeapTuple control structure */
2661 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2663 /* relation might be a foreign table, if so provide tableoid */
2664 tuple.t_tableOid = erm->relid;
2665 /* also copy t_ctid in case there's valid data there */
2666 tuple.t_self = td->t_ctid;
2668 /* copy and store tuple */
2669 EvalPlanQualSetTuple(epqstate, erm->rti,
2670 heap_copytuple(&tuple));
2676 * Fetch the next row (if any) from EvalPlanQual testing
2678 * (In practice, there should never be more than one row...)
2681 EvalPlanQualNext(EPQState *epqstate)
2683 MemoryContext oldcontext;
2684 TupleTableSlot *slot;
2686 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2687 slot = ExecProcNode(epqstate->planstate);
2688 MemoryContextSwitchTo(oldcontext);
2694 * Initialize or reset an EvalPlanQual state tree
2697 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2699 EState *estate = epqstate->estate;
2703 /* First time through, so create a child EState */
2704 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2709 * We already have a suitable child EPQ tree, so just reset it.
2711 int rtsize = list_length(parentestate->es_range_table);
2712 PlanState *planstate = epqstate->planstate;
2714 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2716 /* Recopy current values of parent parameters */
2717 if (parentestate->es_plannedstmt->nParamExec > 0)
2719 int i = parentestate->es_plannedstmt->nParamExec;
2723 /* copy value if any, but not execPlan link */
2724 estate->es_param_exec_vals[i].value =
2725 parentestate->es_param_exec_vals[i].value;
2726 estate->es_param_exec_vals[i].isnull =
2727 parentestate->es_param_exec_vals[i].isnull;
2732 * Mark child plan tree as needing rescan at all scan nodes. The
2733 * first ExecProcNode will take care of actually doing the rescan.
2735 planstate->chgParam = bms_add_member(planstate->chgParam,
2736 epqstate->epqParam);
2741 * Start execution of an EvalPlanQual plan tree.
2743 * This is a cut-down version of ExecutorStart(): we copy some state from
2744 * the top-level estate rather than initializing it fresh.
2747 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2751 MemoryContext oldcontext;
2754 rtsize = list_length(parentestate->es_range_table);
2756 epqstate->estate = estate = CreateExecutorState();
2758 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2761 * Child EPQ EStates share the parent's copy of unchanging state such as
2762 * the snapshot, rangetable, result-rel info, and external Param info.
2763 * They need their own copies of local state, including a tuple table,
2764 * es_param_exec_vals, etc.
2766 * The ResultRelInfo array management is trickier than it looks. We
2767 * create a fresh array for the child but copy all the content from the
2768 * parent. This is because it's okay for the child to share any
2769 * per-relation state the parent has already created --- but if the child
2770 * sets up any ResultRelInfo fields, such as its own junkfilter, that
2771 * state must *not* propagate back to the parent. (For one thing, the
2772 * pointed-to data is in a memory context that won't last long enough.)
2774 estate->es_direction = ForwardScanDirection;
2775 estate->es_snapshot = parentestate->es_snapshot;
2776 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2777 estate->es_range_table = parentestate->es_range_table;
2778 estate->es_plannedstmt = parentestate->es_plannedstmt;
2779 estate->es_junkFilter = parentestate->es_junkFilter;
2780 estate->es_output_cid = parentestate->es_output_cid;
2781 if (parentestate->es_num_result_relations > 0)
2783 int numResultRelations = parentestate->es_num_result_relations;
2784 ResultRelInfo *resultRelInfos;
2786 resultRelInfos = (ResultRelInfo *)
2787 palloc(numResultRelations * sizeof(ResultRelInfo));
2788 memcpy(resultRelInfos, parentestate->es_result_relations,
2789 numResultRelations * sizeof(ResultRelInfo));
2790 estate->es_result_relations = resultRelInfos;
2791 estate->es_num_result_relations = numResultRelations;
2793 /* es_result_relation_info must NOT be copied */
2794 /* es_trig_target_relations must NOT be copied */
2795 estate->es_rowMarks = parentestate->es_rowMarks;
2796 estate->es_top_eflags = parentestate->es_top_eflags;
2797 estate->es_instrument = parentestate->es_instrument;
2798 /* es_auxmodifytables must NOT be copied */
2801 * The external param list is simply shared from parent. The internal
2802 * param workspace has to be local state, but we copy the initial values
2803 * from the parent, so as to have access to any param values that were
2804 * already set from other parts of the parent's plan tree.
2806 estate->es_param_list_info = parentestate->es_param_list_info;
2807 if (parentestate->es_plannedstmt->nParamExec > 0)
2809 int i = parentestate->es_plannedstmt->nParamExec;
2811 estate->es_param_exec_vals = (ParamExecData *)
2812 palloc0(i * sizeof(ParamExecData));
2815 /* copy value if any, but not execPlan link */
2816 estate->es_param_exec_vals[i].value =
2817 parentestate->es_param_exec_vals[i].value;
2818 estate->es_param_exec_vals[i].isnull =
2819 parentestate->es_param_exec_vals[i].isnull;
2824 * Each EState must have its own es_epqScanDone state, but if we have
2825 * nested EPQ checks they should share es_epqTuple arrays. This allows
2826 * sub-rechecks to inherit the values being examined by an outer recheck.
2828 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2829 if (parentestate->es_epqTuple != NULL)
2831 estate->es_epqTuple = parentestate->es_epqTuple;
2832 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2836 estate->es_epqTuple = (HeapTuple *)
2837 palloc0(rtsize * sizeof(HeapTuple));
2838 estate->es_epqTupleSet = (bool *)
2839 palloc0(rtsize * sizeof(bool));
2843 * Each estate also has its own tuple table.
2845 estate->es_tupleTable = NIL;
2848 * Initialize private state information for each SubPlan. We must do this
2849 * before running ExecInitNode on the main query tree, since
2850 * ExecInitSubPlan expects to be able to find these entries. Some of the
2851 * SubPlans might not be used in the part of the plan tree we intend to
2852 * run, but since it's not easy to tell which, we just initialize them
2855 Assert(estate->es_subplanstates == NIL);
2856 foreach(l, parentestate->es_plannedstmt->subplans)
2858 Plan *subplan = (Plan *) lfirst(l);
2859 PlanState *subplanstate;
2861 subplanstate = ExecInitNode(subplan, estate, 0);
2862 estate->es_subplanstates = lappend(estate->es_subplanstates,
2867 * Initialize the private state information for all the nodes in the part
2868 * of the plan tree we need to run. This opens files, allocates storage
2869 * and leaves us ready to start processing tuples.
2871 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2873 MemoryContextSwitchTo(oldcontext);
2877 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2878 * or if we are done with the current EPQ child.
2880 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2881 * of the normal cleanup, but *not* close result relations (which we are
2882 * just sharing from the outer query). We do, however, have to close any
2883 * trigger target relations that got opened, since those are not shared.
2884 * (There probably shouldn't be any of the latter, but just in case...)
2887 EvalPlanQualEnd(EPQState *epqstate)
2889 EState *estate = epqstate->estate;
2890 MemoryContext oldcontext;
2894 return; /* idle, so nothing to do */
2896 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2898 ExecEndNode(epqstate->planstate);
2900 foreach(l, estate->es_subplanstates)
2902 PlanState *subplanstate = (PlanState *) lfirst(l);
2904 ExecEndNode(subplanstate);
2907 /* throw away the per-estate tuple table */
2908 ExecResetTupleTable(estate->es_tupleTable, false);
2910 /* close any trigger target relations attached to this EState */
2911 foreach(l, estate->es_trig_target_relations)
2913 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2915 /* Close indices and then the relation itself */
2916 ExecCloseIndices(resultRelInfo);
2917 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2920 MemoryContextSwitchTo(oldcontext);
2922 FreeExecutorState(estate);
2924 /* Mark EPQState idle */
2925 epqstate->estate = NULL;
2926 epqstate->planstate = NULL;
2927 epqstate->origslot = NULL;