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-2015, 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, long 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, long 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_ConstraintExprs = NULL;
1249 resultRelInfo->ri_junkFilter = NULL;
1250 resultRelInfo->ri_projectReturning = NULL;
1254 * ExecGetTriggerResultRel
1256 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1257 * triggers are fired on one of the result relations of the query, and so
1258 * we can just return a member of the es_result_relations array. (Note: in
1259 * self-join situations there might be multiple members with the same OID;
1260 * if so it doesn't matter which one we pick.) However, it is sometimes
1261 * necessary to fire triggers on other relations; this happens mainly when an
1262 * RI update trigger queues additional triggers on other relations, which will
1263 * be processed in the context of the outer query. For efficiency's sake,
1264 * we want to have a ResultRelInfo for those triggers too; that can avoid
1265 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1266 * ANALYZE to report the runtimes of such triggers.) So we make additional
1267 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1270 ExecGetTriggerResultRel(EState *estate, Oid relid)
1272 ResultRelInfo *rInfo;
1276 MemoryContext oldcontext;
1278 /* First, search through the query result relations */
1279 rInfo = estate->es_result_relations;
1280 nr = estate->es_num_result_relations;
1283 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1288 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1289 foreach(l, estate->es_trig_target_relations)
1291 rInfo = (ResultRelInfo *) lfirst(l);
1292 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1295 /* Nope, so we need a new one */
1298 * Open the target relation's relcache entry. We assume that an
1299 * appropriate lock is still held by the backend from whenever the trigger
1300 * event got queued, so we need take no new lock here. Also, we need not
1301 * recheck the relkind, so no need for CheckValidResultRel.
1303 rel = heap_open(relid, NoLock);
1306 * Make the new entry in the right context.
1308 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1309 rInfo = makeNode(ResultRelInfo);
1310 InitResultRelInfo(rInfo,
1312 0, /* dummy rangetable index */
1313 estate->es_instrument);
1314 estate->es_trig_target_relations =
1315 lappend(estate->es_trig_target_relations, rInfo);
1316 MemoryContextSwitchTo(oldcontext);
1319 * Currently, we don't need any index information in ResultRelInfos used
1320 * only for triggers, so no need to call ExecOpenIndices.
1327 * ExecContextForcesOids
1329 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1330 * we need to ensure that result tuples have space for an OID iff they are
1331 * going to be stored into a relation that has OIDs. In other contexts
1332 * we are free to choose whether to leave space for OIDs in result tuples
1333 * (we generally don't want to, but we do if a physical-tlist optimization
1334 * is possible). This routine checks the plan context and returns TRUE if the
1335 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1336 * *hasoids is set to the required value.
1338 * One reason this is ugly is that all plan nodes in the plan tree will emit
1339 * tuples with space for an OID, though we really only need the topmost node
1340 * to do so. However, node types like Sort don't project new tuples but just
1341 * return their inputs, and in those cases the requirement propagates down
1342 * to the input node. Eventually we might make this code smart enough to
1343 * recognize how far down the requirement really goes, but for now we just
1344 * make all plan nodes do the same thing if the top level forces the choice.
1346 * We assume that if we are generating tuples for INSERT or UPDATE,
1347 * estate->es_result_relation_info is already set up to describe the target
1348 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1349 * the target relations may have OIDs and some not. We have to make the
1350 * decisions on a per-relation basis as we initialize each of the subplans of
1351 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1352 * while initializing each subplan.
1354 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1355 * descriptor available when this code runs; we have to look aside at the
1356 * flags passed to ExecutorStart().
1359 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1361 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1365 Relation rel = ri->ri_RelationDesc;
1369 *hasoids = rel->rd_rel->relhasoids;
1374 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1379 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1388 /* ----------------------------------------------------------------
1389 * ExecPostprocessPlan
1391 * Give plan nodes a final chance to execute before shutdown
1392 * ----------------------------------------------------------------
1395 ExecPostprocessPlan(EState *estate)
1400 * Make sure nodes run forward.
1402 estate->es_direction = ForwardScanDirection;
1405 * Run any secondary ModifyTable nodes to completion, in case the main
1406 * query did not fetch all rows from them. (We do this to ensure that
1407 * such nodes have predictable results.)
1409 foreach(lc, estate->es_auxmodifytables)
1411 PlanState *ps = (PlanState *) lfirst(lc);
1415 TupleTableSlot *slot;
1417 /* Reset the per-output-tuple exprcontext each time */
1418 ResetPerTupleExprContext(estate);
1420 slot = ExecProcNode(ps);
1422 if (TupIsNull(slot))
1428 /* ----------------------------------------------------------------
1431 * Cleans up the query plan -- closes files and frees up storage
1433 * NOTE: we are no longer very worried about freeing storage per se
1434 * in this code; FreeExecutorState should be guaranteed to release all
1435 * memory that needs to be released. What we are worried about doing
1436 * is closing relations and dropping buffer pins. Thus, for example,
1437 * tuple tables must be cleared or dropped to ensure pins are released.
1438 * ----------------------------------------------------------------
1441 ExecEndPlan(PlanState *planstate, EState *estate)
1443 ResultRelInfo *resultRelInfo;
1448 * shut down the node-type-specific query processing
1450 ExecEndNode(planstate);
1455 foreach(l, estate->es_subplanstates)
1457 PlanState *subplanstate = (PlanState *) lfirst(l);
1459 ExecEndNode(subplanstate);
1463 * destroy the executor's tuple table. Actually we only care about
1464 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1465 * the TupleTableSlots, since the containing memory context is about to go
1468 ExecResetTupleTable(estate->es_tupleTable, false);
1471 * close the result relation(s) if any, but hold locks until xact commit.
1473 resultRelInfo = estate->es_result_relations;
1474 for (i = estate->es_num_result_relations; i > 0; i--)
1476 /* Close indices and then the relation itself */
1477 ExecCloseIndices(resultRelInfo);
1478 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1483 * likewise close any trigger target relations
1485 foreach(l, estate->es_trig_target_relations)
1487 resultRelInfo = (ResultRelInfo *) lfirst(l);
1488 /* Close indices and then the relation itself */
1489 ExecCloseIndices(resultRelInfo);
1490 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1494 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1497 foreach(l, estate->es_rowMarks)
1499 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1502 heap_close(erm->relation, NoLock);
1506 /* ----------------------------------------------------------------
1509 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1510 * moving in the specified direction.
1512 * Runs to completion if numberTuples is 0
1514 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1516 * ----------------------------------------------------------------
1519 ExecutePlan(EState *estate,
1520 PlanState *planstate,
1521 bool use_parallel_mode,
1525 ScanDirection direction,
1528 TupleTableSlot *slot;
1529 long current_tuple_count;
1532 * initialize local variables
1534 current_tuple_count = 0;
1537 * Set the direction.
1539 estate->es_direction = direction;
1542 * If a tuple count was supplied, we must force the plan to run without
1543 * parallelism, because we might exit early.
1545 if (numberTuples != 0)
1546 use_parallel_mode = false;
1549 * If a tuple count was supplied, we must force the plan to run without
1550 * parallelism, because we might exit early.
1552 if (use_parallel_mode)
1553 EnterParallelMode();
1556 * Loop until we've processed the proper number of tuples from the plan.
1560 /* Reset the per-output-tuple exprcontext */
1561 ResetPerTupleExprContext(estate);
1564 * Execute the plan and obtain a tuple
1566 slot = ExecProcNode(planstate);
1569 * if the tuple is null, then we assume there is nothing more to
1570 * process so we just end the loop...
1572 if (TupIsNull(slot))
1574 /* Allow nodes to release or shut down resources. */
1575 (void) ExecShutdownNode(planstate);
1580 * If we have a junk filter, then project a new tuple with the junk
1583 * Store this new "clean" tuple in the junkfilter's resultSlot.
1584 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1585 * because that tuple slot has the wrong descriptor.)
1587 if (estate->es_junkFilter != NULL)
1588 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1591 * If we are supposed to send the tuple somewhere, do so. (In
1592 * practice, this is probably always the case at this point.)
1595 (*dest->receiveSlot) (slot, dest);
1598 * Count tuples processed, if this is a SELECT. (For other operation
1599 * types, the ModifyTable plan node must count the appropriate
1602 if (operation == CMD_SELECT)
1603 (estate->es_processed)++;
1606 * check our tuple count.. if we've processed the proper number then
1607 * quit, else loop again and process more tuples. Zero numberTuples
1610 current_tuple_count++;
1611 if (numberTuples && numberTuples == current_tuple_count)
1615 if (use_parallel_mode)
1621 * ExecRelCheck --- check that tuple meets constraints for result relation
1623 * Returns NULL if OK, else name of failed check constraint
1626 ExecRelCheck(ResultRelInfo *resultRelInfo,
1627 TupleTableSlot *slot, EState *estate)
1629 Relation rel = resultRelInfo->ri_RelationDesc;
1630 int ncheck = rel->rd_att->constr->num_check;
1631 ConstrCheck *check = rel->rd_att->constr->check;
1632 ExprContext *econtext;
1633 MemoryContext oldContext;
1638 * If first time through for this result relation, build expression
1639 * nodetrees for rel's constraint expressions. Keep them in the per-query
1640 * memory context so they'll survive throughout the query.
1642 if (resultRelInfo->ri_ConstraintExprs == NULL)
1644 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1645 resultRelInfo->ri_ConstraintExprs =
1646 (List **) palloc(ncheck * sizeof(List *));
1647 for (i = 0; i < ncheck; i++)
1649 /* ExecQual wants implicit-AND form */
1650 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1651 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1652 ExecPrepareExpr((Expr *) qual, estate);
1654 MemoryContextSwitchTo(oldContext);
1658 * We will use the EState's per-tuple context for evaluating constraint
1659 * expressions (creating it if it's not already there).
1661 econtext = GetPerTupleExprContext(estate);
1663 /* Arrange for econtext's scan tuple to be the tuple under test */
1664 econtext->ecxt_scantuple = slot;
1666 /* And evaluate the constraints */
1667 for (i = 0; i < ncheck; i++)
1669 qual = resultRelInfo->ri_ConstraintExprs[i];
1672 * NOTE: SQL specifies that a NULL result from a constraint expression
1673 * is not to be treated as a failure. Therefore, tell ExecQual to
1674 * return TRUE for NULL.
1676 if (!ExecQual(qual, econtext, true))
1677 return check[i].ccname;
1680 /* NULL result means no error */
1685 ExecConstraints(ResultRelInfo *resultRelInfo,
1686 TupleTableSlot *slot, EState *estate)
1688 Relation rel = resultRelInfo->ri_RelationDesc;
1689 TupleDesc tupdesc = RelationGetDescr(rel);
1690 TupleConstr *constr = tupdesc->constr;
1691 Bitmapset *modifiedCols;
1692 Bitmapset *insertedCols;
1693 Bitmapset *updatedCols;
1697 if (constr->has_not_null)
1699 int natts = tupdesc->natts;
1702 for (attrChk = 1; attrChk <= natts; attrChk++)
1704 if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1705 slot_attisnull(slot, attrChk))
1709 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1710 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1711 modifiedCols = bms_union(insertedCols, updatedCols);
1712 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1719 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1720 errmsg("null value in column \"%s\" violates not-null constraint",
1721 NameStr(tupdesc->attrs[attrChk - 1]->attname)),
1722 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1723 errtablecol(rel, attrChk)));
1728 if (constr->num_check > 0)
1732 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1736 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1737 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1738 modifiedCols = bms_union(insertedCols, updatedCols);
1739 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1745 (errcode(ERRCODE_CHECK_VIOLATION),
1746 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1747 RelationGetRelationName(rel), failed),
1748 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1749 errtableconstraint(rel, failed)));
1755 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1756 * of the specified kind.
1758 * Note that this needs to be called multiple times to ensure that all kinds of
1759 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
1760 * CHECK OPTION set and from row level security policies). See ExecInsert()
1764 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
1765 TupleTableSlot *slot, EState *estate)
1767 Relation rel = resultRelInfo->ri_RelationDesc;
1768 TupleDesc tupdesc = RelationGetDescr(rel);
1769 ExprContext *econtext;
1774 * We will use the EState's per-tuple context for evaluating constraint
1775 * expressions (creating it if it's not already there).
1777 econtext = GetPerTupleExprContext(estate);
1779 /* Arrange for econtext's scan tuple to be the tuple under test */
1780 econtext->ecxt_scantuple = slot;
1782 /* Check each of the constraints */
1783 forboth(l1, resultRelInfo->ri_WithCheckOptions,
1784 l2, resultRelInfo->ri_WithCheckOptionExprs)
1786 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1787 ExprState *wcoExpr = (ExprState *) lfirst(l2);
1790 * Skip any WCOs which are not the kind we are looking for at this
1793 if (wco->kind != kind)
1797 * WITH CHECK OPTION checks are intended to ensure that the new tuple
1798 * is visible (in the case of a view) or that it passes the
1799 * 'with-check' policy (in the case of row security). If the qual
1800 * evaluates to NULL or FALSE, then the new tuple won't be included in
1801 * the view or doesn't pass the 'with-check' policy for the table. We
1802 * need ExecQual to return FALSE for NULL to handle the view case (the
1803 * opposite of what we do above for CHECK constraints).
1805 if (!ExecQual((List *) wcoExpr, econtext, false))
1808 Bitmapset *modifiedCols;
1809 Bitmapset *insertedCols;
1810 Bitmapset *updatedCols;
1815 * For WITH CHECK OPTIONs coming from views, we might be
1816 * able to provide the details on the row, depending on
1817 * the permissions on the relation (that is, if the user
1818 * could view it directly anyway). For RLS violations, we
1819 * don't include the data since we don't know if the user
1820 * should be able to view the tuple as as that depends on
1823 case WCO_VIEW_CHECK:
1824 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1825 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1826 modifiedCols = bms_union(insertedCols, updatedCols);
1827 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1834 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1835 errmsg("new row violates WITH CHECK OPTION for \"%s\"",
1837 val_desc ? errdetail("Failing row contains %s.",
1840 case WCO_RLS_INSERT_CHECK:
1841 case WCO_RLS_UPDATE_CHECK:
1842 if (wco->polname != NULL)
1844 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1845 errmsg("new row violates row level security policy \"%s\" for \"%s\"",
1846 wco->polname, wco->relname)));
1849 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1850 errmsg("new row violates row level security policy for \"%s\"",
1853 case WCO_RLS_CONFLICT_CHECK:
1854 if (wco->polname != NULL)
1856 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1857 errmsg("new row violates row level security policy \"%s\" (USING expression) for \"%s\"",
1858 wco->polname, wco->relname)));
1861 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1862 errmsg("new row violates row level security policy (USING expression) for \"%s\"",
1866 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
1874 * ExecBuildSlotValueDescription -- construct a string representing a tuple
1876 * This is intentionally very similar to BuildIndexValueDescription, but
1877 * unlike that function, we truncate long field values (to at most maxfieldlen
1878 * bytes). That seems necessary here since heap field values could be very
1879 * long, whereas index entries typically aren't so wide.
1881 * Also, unlike the case with index entries, we need to be prepared to ignore
1882 * dropped columns. We used to use the slot's tuple descriptor to decode the
1883 * data, but the slot's descriptor doesn't identify dropped columns, so we
1884 * now need to be passed the relation's descriptor.
1886 * Note that, like BuildIndexValueDescription, if the user does not have
1887 * permission to view any of the columns involved, a NULL is returned. Unlike
1888 * BuildIndexValueDescription, if the user has access to view a subset of the
1889 * column involved, that subset will be returned with a key identifying which
1893 ExecBuildSlotValueDescription(Oid reloid,
1894 TupleTableSlot *slot,
1896 Bitmapset *modifiedCols,
1900 StringInfoData collist;
1901 bool write_comma = false;
1902 bool write_comma_collist = false;
1904 AclResult aclresult;
1905 bool table_perm = false;
1906 bool any_perm = false;
1909 * Check if RLS is enabled and should be active for the relation; if so,
1910 * then don't return anything. Otherwise, go through normal permission
1913 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
1916 initStringInfo(&buf);
1918 appendStringInfoChar(&buf, '(');
1921 * Check if the user has permissions to see the row. Table-level SELECT
1922 * allows access to all columns. If the user does not have table-level
1923 * SELECT then we check each column and include those the user has SELECT
1924 * rights on. Additionally, we always include columns the user provided
1927 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
1928 if (aclresult != ACLCHECK_OK)
1930 /* Set up the buffer for the column list */
1931 initStringInfo(&collist);
1932 appendStringInfoChar(&collist, '(');
1935 table_perm = any_perm = true;
1937 /* Make sure the tuple is fully deconstructed */
1938 slot_getallattrs(slot);
1940 for (i = 0; i < tupdesc->natts; i++)
1942 bool column_perm = false;
1946 /* ignore dropped columns */
1947 if (tupdesc->attrs[i]->attisdropped)
1953 * No table-level SELECT, so need to make sure they either have
1954 * SELECT rights on the column or that they have provided the data
1955 * for the column. If not, omit this column from the error
1958 aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
1959 GetUserId(), ACL_SELECT);
1960 if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
1961 modifiedCols) || aclresult == ACLCHECK_OK)
1963 column_perm = any_perm = true;
1965 if (write_comma_collist)
1966 appendStringInfoString(&collist, ", ");
1968 write_comma_collist = true;
1970 appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
1974 if (table_perm || column_perm)
1976 if (slot->tts_isnull[i])
1983 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1984 &foutoid, &typisvarlena);
1985 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1989 appendStringInfoString(&buf, ", ");
1993 /* truncate if needed */
1994 vallen = strlen(val);
1995 if (vallen <= maxfieldlen)
1996 appendStringInfoString(&buf, val);
1999 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2000 appendBinaryStringInfo(&buf, val, vallen);
2001 appendStringInfoString(&buf, "...");
2006 /* If we end up with zero columns being returned, then return NULL. */
2010 appendStringInfoChar(&buf, ')');
2014 appendStringInfoString(&collist, ") = ");
2015 appendStringInfoString(&collist, buf.data);
2017 return collist.data;
2025 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2026 * given ResultRelInfo
2029 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2032 Bitmapset *updatedCols;
2035 * Compute lock mode to use. If columns that are part of the key have not
2036 * been modified, then we can use a weaker lock, allowing for better
2039 updatedCols = GetUpdatedColumns(relinfo, estate);
2040 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2041 INDEX_ATTR_BITMAP_KEY);
2043 if (bms_overlap(keyCols, updatedCols))
2044 return LockTupleExclusive;
2046 return LockTupleNoKeyExclusive;
2050 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2052 * If no such struct, either return NULL or throw error depending on missing_ok
2055 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2059 foreach(lc, estate->es_rowMarks)
2061 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2063 if (erm->rti == rti)
2067 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2072 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2074 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2075 * input plan node (not planstate node!). We need the latter to find out
2076 * the column numbers of the resjunk columns.
2079 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2081 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2084 aerm->rowmark = erm;
2086 /* Look up the resjunk columns associated with this rowmark */
2087 if (erm->markType != ROW_MARK_COPY)
2089 /* need ctid for all methods other than COPY */
2090 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2091 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2093 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2094 elog(ERROR, "could not find junk %s column", resname);
2098 /* need wholerow if COPY */
2099 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2100 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2102 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2103 elog(ERROR, "could not find junk %s column", resname);
2106 /* if child rel, need tableoid */
2107 if (erm->rti != erm->prti)
2109 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2110 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2112 if (!AttributeNumberIsValid(aerm->toidAttNo))
2113 elog(ERROR, "could not find junk %s column", resname);
2121 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2122 * process the updated version under READ COMMITTED rules.
2124 * See backend/executor/README for some info about how this works.
2129 * Check a modified tuple to see if we want to process its updated version
2130 * under READ COMMITTED rules.
2132 * estate - outer executor state data
2133 * epqstate - state for EvalPlanQual rechecking
2134 * relation - table containing tuple
2135 * rti - rangetable index of table containing tuple
2136 * lockmode - requested tuple lock mode
2137 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2138 * priorXmax - t_xmax from the outdated tuple
2140 * *tid is also an output parameter: it's modified to hold the TID of the
2141 * latest version of the tuple (note this may be changed even on failure)
2143 * Returns a slot containing the new candidate update/delete tuple, or
2144 * NULL if we determine we shouldn't process the row.
2146 * Note: properly, lockmode should be declared as enum LockTupleMode,
2147 * but we use "int" to avoid having to include heapam.h in executor.h.
2150 EvalPlanQual(EState *estate, EPQState *epqstate,
2151 Relation relation, Index rti, int lockmode,
2152 ItemPointer tid, TransactionId priorXmax)
2154 TupleTableSlot *slot;
2155 HeapTuple copyTuple;
2160 * Get and lock the updated version of the row; if fail, return NULL.
2162 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2165 if (copyTuple == NULL)
2169 * For UPDATE/DELETE we have to return tid of actual row we're executing
2172 *tid = copyTuple->t_self;
2175 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2177 EvalPlanQualBegin(epqstate, estate);
2180 * Free old test tuple, if any, and store new tuple where relation's scan
2183 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2186 * Fetch any non-locked source rows
2188 EvalPlanQualFetchRowMarks(epqstate);
2191 * Run the EPQ query. We assume it will return at most one tuple.
2193 slot = EvalPlanQualNext(epqstate);
2196 * If we got a tuple, force the slot to materialize the tuple so that it
2197 * is not dependent on any local state in the EPQ query (in particular,
2198 * it's highly likely that the slot contains references to any pass-by-ref
2199 * datums that may be present in copyTuple). As with the next step, this
2200 * is to guard against early re-use of the EPQ query.
2202 if (!TupIsNull(slot))
2203 (void) ExecMaterializeSlot(slot);
2206 * Clear out the test tuple. This is needed in case the EPQ query is
2207 * re-used to test a tuple for a different relation. (Not clear that can
2208 * really happen, but let's be safe.)
2210 EvalPlanQualSetTuple(epqstate, rti, NULL);
2216 * Fetch a copy of the newest version of an outdated tuple
2218 * estate - executor state data
2219 * relation - table containing tuple
2220 * lockmode - requested tuple lock mode
2221 * wait_policy - requested lock wait policy
2222 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2223 * priorXmax - t_xmax from the outdated tuple
2225 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2226 * that there is no newest version (ie, the row was deleted not updated).
2227 * We also return NULL if the tuple is locked and the wait policy is to skip
2230 * If successful, we have locked the newest tuple version, so caller does not
2231 * need to worry about it changing anymore.
2233 * Note: properly, lockmode should be declared as enum LockTupleMode,
2234 * but we use "int" to avoid having to include heapam.h in executor.h.
2237 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2238 LockWaitPolicy wait_policy,
2239 ItemPointer tid, TransactionId priorXmax)
2241 HeapTuple copyTuple = NULL;
2242 HeapTupleData tuple;
2243 SnapshotData SnapshotDirty;
2246 * fetch target tuple
2248 * Loop here to deal with updated or busy tuples
2250 InitDirtySnapshot(SnapshotDirty);
2251 tuple.t_self = *tid;
2256 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2259 HeapUpdateFailureData hufd;
2262 * If xmin isn't what we're expecting, the slot must have been
2263 * recycled and reused for an unrelated tuple. This implies that
2264 * the latest version of the row was deleted, so we need do
2265 * nothing. (Should be safe to examine xmin without getting
2266 * buffer's content lock. We assume reading a TransactionId to be
2267 * atomic, and Xmin never changes in an existing tuple, except to
2268 * invalid or frozen, and neither of those can match priorXmax.)
2270 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2273 ReleaseBuffer(buffer);
2277 /* otherwise xmin should not be dirty... */
2278 if (TransactionIdIsValid(SnapshotDirty.xmin))
2279 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2282 * If tuple is being updated by other transaction then we have to
2283 * wait for its commit/abort, or die trying.
2285 if (TransactionIdIsValid(SnapshotDirty.xmax))
2287 ReleaseBuffer(buffer);
2288 switch (wait_policy)
2291 XactLockTableWait(SnapshotDirty.xmax,
2292 relation, &tuple.t_self,
2296 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2297 return NULL; /* skip instead of waiting */
2300 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2302 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2303 errmsg("could not obtain lock on row in relation \"%s\"",
2304 RelationGetRelationName(relation))));
2307 continue; /* loop back to repeat heap_fetch */
2311 * If tuple was inserted by our own transaction, we have to check
2312 * cmin against es_output_cid: cmin >= current CID means our
2313 * command cannot see the tuple, so we should ignore it. Otherwise
2314 * heap_lock_tuple() will throw an error, and so would any later
2315 * attempt to update or delete the tuple. (We need not check cmax
2316 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2317 * by our transaction dead, regardless of cmax.) We just checked
2318 * that priorXmax == xmin, so we can test that variable instead of
2319 * doing HeapTupleHeaderGetXmin again.
2321 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2322 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2324 ReleaseBuffer(buffer);
2329 * This is a live tuple, so now try to lock it.
2331 test = heap_lock_tuple(relation, &tuple,
2332 estate->es_output_cid,
2333 lockmode, wait_policy,
2334 false, &buffer, &hufd);
2335 /* We now have two pins on the buffer, get rid of one */
2336 ReleaseBuffer(buffer);
2340 case HeapTupleSelfUpdated:
2343 * The target tuple was already updated or deleted by the
2344 * current command, or by a later command in the current
2345 * transaction. We *must* ignore the tuple in the former
2346 * case, so as to avoid the "Halloween problem" of
2347 * repeated update attempts. In the latter case it might
2348 * be sensible to fetch the updated tuple instead, but
2349 * doing so would require changing heap_update and
2350 * heap_delete to not complain about updating "invisible"
2351 * tuples, which seems pretty scary (heap_lock_tuple will
2352 * not complain, but few callers expect
2353 * HeapTupleInvisible, and we're not one of them). So for
2354 * now, treat the tuple as deleted and do not process.
2356 ReleaseBuffer(buffer);
2359 case HeapTupleMayBeUpdated:
2360 /* successfully locked */
2363 case HeapTupleUpdated:
2364 ReleaseBuffer(buffer);
2365 if (IsolationUsesXactSnapshot())
2367 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2368 errmsg("could not serialize access due to concurrent update")));
2370 /* Should not encounter speculative tuple on recheck */
2371 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2372 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2374 /* it was updated, so look at the updated version */
2375 tuple.t_self = hufd.ctid;
2376 /* updated row should have xmin matching this xmax */
2377 priorXmax = hufd.xmax;
2380 /* tuple was deleted, so give up */
2383 case HeapTupleWouldBlock:
2384 ReleaseBuffer(buffer);
2387 case HeapTupleInvisible:
2388 elog(ERROR, "attempted to lock invisible tuple");
2391 ReleaseBuffer(buffer);
2392 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2394 return NULL; /* keep compiler quiet */
2398 * We got tuple - now copy it for use by recheck query.
2400 copyTuple = heap_copytuple(&tuple);
2401 ReleaseBuffer(buffer);
2406 * If the referenced slot was actually empty, the latest version of
2407 * the row must have been deleted, so we need do nothing.
2409 if (tuple.t_data == NULL)
2411 ReleaseBuffer(buffer);
2416 * As above, if xmin isn't what we're expecting, do nothing.
2418 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2421 ReleaseBuffer(buffer);
2426 * If we get here, the tuple was found but failed SnapshotDirty.
2427 * Assuming the xmin is either a committed xact or our own xact (as it
2428 * certainly should be if we're trying to modify the tuple), this must
2429 * mean that the row was updated or deleted by either a committed xact
2430 * or our own xact. If it was deleted, we can ignore it; if it was
2431 * updated then chain up to the next version and repeat the whole
2434 * As above, it should be safe to examine xmax and t_ctid without the
2435 * buffer content lock, because they can't be changing.
2437 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2439 /* deleted, so forget about it */
2440 ReleaseBuffer(buffer);
2444 /* updated, so look at the updated row */
2445 tuple.t_self = tuple.t_data->t_ctid;
2446 /* updated row should have xmin matching this xmax */
2447 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2448 ReleaseBuffer(buffer);
2449 /* loop back to fetch next in chain */
2453 * Return the copied tuple
2459 * EvalPlanQualInit -- initialize during creation of a plan state node
2460 * that might need to invoke EPQ processing.
2462 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2463 * with EvalPlanQualSetPlan.
2466 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2467 Plan *subplan, List *auxrowmarks, int epqParam)
2469 /* Mark the EPQ state inactive */
2470 epqstate->estate = NULL;
2471 epqstate->planstate = NULL;
2472 epqstate->origslot = NULL;
2473 /* ... and remember data that EvalPlanQualBegin will need */
2474 epqstate->plan = subplan;
2475 epqstate->arowMarks = auxrowmarks;
2476 epqstate->epqParam = epqParam;
2480 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2482 * We need this so that ModifyTable can deal with multiple subplans.
2485 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2487 /* If we have a live EPQ query, shut it down */
2488 EvalPlanQualEnd(epqstate);
2489 /* And set/change the plan pointer */
2490 epqstate->plan = subplan;
2491 /* The rowmarks depend on the plan, too */
2492 epqstate->arowMarks = auxrowmarks;
2496 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2498 * NB: passed tuple must be palloc'd; it may get freed later
2501 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2503 EState *estate = epqstate->estate;
2508 * free old test tuple, if any, and store new tuple where relation's scan
2511 if (estate->es_epqTuple[rti - 1] != NULL)
2512 heap_freetuple(estate->es_epqTuple[rti - 1]);
2513 estate->es_epqTuple[rti - 1] = tuple;
2514 estate->es_epqTupleSet[rti - 1] = true;
2518 * Fetch back the current test tuple (if any) for the specified RTI
2521 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2523 EState *estate = epqstate->estate;
2527 return estate->es_epqTuple[rti - 1];
2531 * Fetch the current row values for any non-locked relations that need
2532 * to be scanned by an EvalPlanQual operation. origslot must have been set
2533 * to contain the current result row (top-level row) that we need to recheck.
2536 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2540 Assert(epqstate->origslot != NULL);
2542 foreach(l, epqstate->arowMarks)
2544 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2545 ExecRowMark *erm = aerm->rowmark;
2548 HeapTupleData tuple;
2550 if (RowMarkRequiresRowShareLock(erm->markType))
2551 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2553 /* clear any leftover test tuple for this rel */
2554 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2556 /* if child rel, must check whether it produced this row */
2557 if (erm->rti != erm->prti)
2561 datum = ExecGetJunkAttribute(epqstate->origslot,
2564 /* non-locked rels could be on the inside of outer joins */
2567 tableoid = DatumGetObjectId(datum);
2569 Assert(OidIsValid(erm->relid));
2570 if (tableoid != erm->relid)
2572 /* this child is inactive right now */
2577 if (erm->markType == ROW_MARK_REFERENCE)
2579 HeapTuple copyTuple;
2581 Assert(erm->relation != NULL);
2583 /* fetch the tuple's ctid */
2584 datum = ExecGetJunkAttribute(epqstate->origslot,
2587 /* non-locked rels could be on the inside of outer joins */
2591 /* fetch requests on foreign tables must be passed to their FDW */
2592 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2594 FdwRoutine *fdwroutine;
2595 bool updated = false;
2597 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2598 /* this should have been checked already, but let's be safe */
2599 if (fdwroutine->RefetchForeignRow == NULL)
2601 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2602 errmsg("cannot lock rows in foreign table \"%s\"",
2603 RelationGetRelationName(erm->relation))));
2604 copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2608 if (copyTuple == NULL)
2609 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2612 * Ideally we'd insist on updated == false here, but that
2613 * assumes that FDWs can track that exactly, which they might
2614 * not be able to. So just ignore the flag.
2619 /* ordinary table, fetch the tuple */
2622 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2623 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2625 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2627 /* successful, copy tuple */
2628 copyTuple = heap_copytuple(&tuple);
2629 ReleaseBuffer(buffer);
2633 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2639 Assert(erm->markType == ROW_MARK_COPY);
2641 /* fetch the whole-row Var for the relation */
2642 datum = ExecGetJunkAttribute(epqstate->origslot,
2645 /* non-locked rels could be on the inside of outer joins */
2648 td = DatumGetHeapTupleHeader(datum);
2650 /* build a temporary HeapTuple control structure */
2651 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2653 /* relation might be a foreign table, if so provide tableoid */
2654 tuple.t_tableOid = erm->relid;
2655 /* also copy t_ctid in case there's valid data there */
2656 tuple.t_self = td->t_ctid;
2658 /* copy and store tuple */
2659 EvalPlanQualSetTuple(epqstate, erm->rti,
2660 heap_copytuple(&tuple));
2666 * Fetch the next row (if any) from EvalPlanQual testing
2668 * (In practice, there should never be more than one row...)
2671 EvalPlanQualNext(EPQState *epqstate)
2673 MemoryContext oldcontext;
2674 TupleTableSlot *slot;
2676 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2677 slot = ExecProcNode(epqstate->planstate);
2678 MemoryContextSwitchTo(oldcontext);
2684 * Initialize or reset an EvalPlanQual state tree
2687 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2689 EState *estate = epqstate->estate;
2693 /* First time through, so create a child EState */
2694 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2699 * We already have a suitable child EPQ tree, so just reset it.
2701 int rtsize = list_length(parentestate->es_range_table);
2702 PlanState *planstate = epqstate->planstate;
2704 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2706 /* Recopy current values of parent parameters */
2707 if (parentestate->es_plannedstmt->nParamExec > 0)
2709 int i = parentestate->es_plannedstmt->nParamExec;
2713 /* copy value if any, but not execPlan link */
2714 estate->es_param_exec_vals[i].value =
2715 parentestate->es_param_exec_vals[i].value;
2716 estate->es_param_exec_vals[i].isnull =
2717 parentestate->es_param_exec_vals[i].isnull;
2722 * Mark child plan tree as needing rescan at all scan nodes. The
2723 * first ExecProcNode will take care of actually doing the rescan.
2725 planstate->chgParam = bms_add_member(planstate->chgParam,
2726 epqstate->epqParam);
2731 * Start execution of an EvalPlanQual plan tree.
2733 * This is a cut-down version of ExecutorStart(): we copy some state from
2734 * the top-level estate rather than initializing it fresh.
2737 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2741 MemoryContext oldcontext;
2744 rtsize = list_length(parentestate->es_range_table);
2746 epqstate->estate = estate = CreateExecutorState();
2748 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2751 * Child EPQ EStates share the parent's copy of unchanging state such as
2752 * the snapshot, rangetable, result-rel info, and external Param info.
2753 * They need their own copies of local state, including a tuple table,
2754 * es_param_exec_vals, etc.
2756 * The ResultRelInfo array management is trickier than it looks. We
2757 * create a fresh array for the child but copy all the content from the
2758 * parent. This is because it's okay for the child to share any
2759 * per-relation state the parent has already created --- but if the child
2760 * sets up any ResultRelInfo fields, such as its own junkfilter, that
2761 * state must *not* propagate back to the parent. (For one thing, the
2762 * pointed-to data is in a memory context that won't last long enough.)
2764 estate->es_direction = ForwardScanDirection;
2765 estate->es_snapshot = parentestate->es_snapshot;
2766 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2767 estate->es_range_table = parentestate->es_range_table;
2768 estate->es_plannedstmt = parentestate->es_plannedstmt;
2769 estate->es_junkFilter = parentestate->es_junkFilter;
2770 estate->es_output_cid = parentestate->es_output_cid;
2771 if (parentestate->es_num_result_relations > 0)
2773 int numResultRelations = parentestate->es_num_result_relations;
2774 ResultRelInfo *resultRelInfos;
2776 resultRelInfos = (ResultRelInfo *)
2777 palloc(numResultRelations * sizeof(ResultRelInfo));
2778 memcpy(resultRelInfos, parentestate->es_result_relations,
2779 numResultRelations * sizeof(ResultRelInfo));
2780 estate->es_result_relations = resultRelInfos;
2781 estate->es_num_result_relations = numResultRelations;
2783 /* es_result_relation_info must NOT be copied */
2784 /* es_trig_target_relations must NOT be copied */
2785 estate->es_rowMarks = parentestate->es_rowMarks;
2786 estate->es_top_eflags = parentestate->es_top_eflags;
2787 estate->es_instrument = parentestate->es_instrument;
2788 /* es_auxmodifytables must NOT be copied */
2791 * The external param list is simply shared from parent. The internal
2792 * param workspace has to be local state, but we copy the initial values
2793 * from the parent, so as to have access to any param values that were
2794 * already set from other parts of the parent's plan tree.
2796 estate->es_param_list_info = parentestate->es_param_list_info;
2797 if (parentestate->es_plannedstmt->nParamExec > 0)
2799 int i = parentestate->es_plannedstmt->nParamExec;
2801 estate->es_param_exec_vals = (ParamExecData *)
2802 palloc0(i * sizeof(ParamExecData));
2805 /* copy value if any, but not execPlan link */
2806 estate->es_param_exec_vals[i].value =
2807 parentestate->es_param_exec_vals[i].value;
2808 estate->es_param_exec_vals[i].isnull =
2809 parentestate->es_param_exec_vals[i].isnull;
2814 * Each EState must have its own es_epqScanDone state, but if we have
2815 * nested EPQ checks they should share es_epqTuple arrays. This allows
2816 * sub-rechecks to inherit the values being examined by an outer recheck.
2818 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2819 if (parentestate->es_epqTuple != NULL)
2821 estate->es_epqTuple = parentestate->es_epqTuple;
2822 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2826 estate->es_epqTuple = (HeapTuple *)
2827 palloc0(rtsize * sizeof(HeapTuple));
2828 estate->es_epqTupleSet = (bool *)
2829 palloc0(rtsize * sizeof(bool));
2833 * Each estate also has its own tuple table.
2835 estate->es_tupleTable = NIL;
2838 * Initialize private state information for each SubPlan. We must do this
2839 * before running ExecInitNode on the main query tree, since
2840 * ExecInitSubPlan expects to be able to find these entries. Some of the
2841 * SubPlans might not be used in the part of the plan tree we intend to
2842 * run, but since it's not easy to tell which, we just initialize them
2845 Assert(estate->es_subplanstates == NIL);
2846 foreach(l, parentestate->es_plannedstmt->subplans)
2848 Plan *subplan = (Plan *) lfirst(l);
2849 PlanState *subplanstate;
2851 subplanstate = ExecInitNode(subplan, estate, 0);
2852 estate->es_subplanstates = lappend(estate->es_subplanstates,
2857 * Initialize the private state information for all the nodes in the part
2858 * of the plan tree we need to run. This opens files, allocates storage
2859 * and leaves us ready to start processing tuples.
2861 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2863 MemoryContextSwitchTo(oldcontext);
2867 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2868 * or if we are done with the current EPQ child.
2870 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2871 * of the normal cleanup, but *not* close result relations (which we are
2872 * just sharing from the outer query). We do, however, have to close any
2873 * trigger target relations that got opened, since those are not shared.
2874 * (There probably shouldn't be any of the latter, but just in case...)
2877 EvalPlanQualEnd(EPQState *epqstate)
2879 EState *estate = epqstate->estate;
2880 MemoryContext oldcontext;
2884 return; /* idle, so nothing to do */
2886 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2888 ExecEndNode(epqstate->planstate);
2890 foreach(l, estate->es_subplanstates)
2892 PlanState *subplanstate = (PlanState *) lfirst(l);
2894 ExecEndNode(subplanstate);
2897 /* throw away the per-estate tuple table */
2898 ExecResetTupleTable(estate->es_tupleTable, false);
2900 /* close any trigger target relations attached to this EState */
2901 foreach(l, estate->es_trig_target_relations)
2903 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2905 /* Close indices and then the relation itself */
2906 ExecCloseIndices(resultRelInfo);
2907 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2910 MemoryContextSwitchTo(oldcontext);
2912 FreeExecutorState(estate);
2914 /* Mark EPQState idle */
2915 epqstate->estate = NULL;
2916 epqstate->planstate = NULL;
2917 epqstate->origslot = NULL;