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,
82 ScanDirection direction,
84 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
85 static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
86 Bitmapset *modifiedCols,
87 AclMode requiredPerms);
88 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
89 static char *ExecBuildSlotValueDescription(Oid reloid,
92 Bitmapset *modifiedCols,
94 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
98 * Note that GetUpdatedColumns() also exists in commands/trigger.c. There does
99 * not appear to be any good header to put it into, given the structures that
100 * it uses, so we let them be duplicated. Be sure to update both if one needs
101 * to be changed, however.
103 #define GetInsertedColumns(relinfo, estate) \
104 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->insertedCols)
105 #define GetUpdatedColumns(relinfo, estate) \
106 (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
108 /* end of local decls */
111 /* ----------------------------------------------------------------
114 * This routine must be called at the beginning of any execution of any
117 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
118 * only because some places use QueryDescs for utility commands). The tupDesc
119 * field of the QueryDesc is filled in to describe the tuples that will be
120 * returned, and the internal fields (estate and planstate) are set up.
122 * eflags contains flag bits as described in executor.h.
124 * NB: the CurrentMemoryContext when this is called will become the parent
125 * of the per-query context used for this Executor invocation.
127 * We provide a function hook variable that lets loadable plugins
128 * get control when ExecutorStart is called. Such a plugin would
129 * normally call standard_ExecutorStart().
131 * ----------------------------------------------------------------
134 ExecutorStart(QueryDesc *queryDesc, int eflags)
136 if (ExecutorStart_hook)
137 (*ExecutorStart_hook) (queryDesc, eflags);
139 standard_ExecutorStart(queryDesc, eflags);
143 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
146 MemoryContext oldcontext;
148 /* sanity checks: queryDesc must not be started already */
149 Assert(queryDesc != NULL);
150 Assert(queryDesc->estate == NULL);
153 * If the transaction is read-only, we need to check if any writes are
154 * planned to non-temporary tables. EXPLAIN is considered read-only.
156 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
157 * would require (a) storing the combocid hash in shared memory, rather
158 * than synchronizing it just once at the start of parallelism, and (b) an
159 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
160 * INSERT may have no such troubles, but we forbid it to simplify the
163 * We have lower-level defenses in CommandCounterIncrement and elsewhere
164 * against performing unsafe operations in parallel mode, but this gives a
165 * more user-friendly error message.
167 if ((XactReadOnly || IsInParallelMode()) &&
168 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
169 ExecCheckXactReadOnly(queryDesc->plannedstmt);
172 * Build EState, switch into per-query memory context for startup.
174 estate = CreateExecutorState();
175 queryDesc->estate = estate;
177 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
180 * Fill in external parameters, if any, from queryDesc; and allocate
181 * workspace for internal parameters
183 estate->es_param_list_info = queryDesc->params;
185 if (queryDesc->plannedstmt->nParamExec > 0)
186 estate->es_param_exec_vals = (ParamExecData *)
187 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
190 * If non-read-only query, set the command ID to mark output tuples with
192 switch (queryDesc->operation)
197 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
200 if (queryDesc->plannedstmt->rowMarks != NIL ||
201 queryDesc->plannedstmt->hasModifyingCTE)
202 estate->es_output_cid = GetCurrentCommandId(true);
205 * A SELECT without modifying CTEs can't possibly queue triggers,
206 * so force skip-triggers mode. This is just a marginal efficiency
207 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
208 * all that expensive, but we might as well do it.
210 if (!queryDesc->plannedstmt->hasModifyingCTE)
211 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
217 estate->es_output_cid = GetCurrentCommandId(true);
221 elog(ERROR, "unrecognized operation code: %d",
222 (int) queryDesc->operation);
227 * Copy other important information into the EState
229 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
230 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
231 estate->es_top_eflags = eflags;
232 estate->es_instrument = queryDesc->instrument_options;
235 * Initialize the plan state tree
237 InitPlan(queryDesc, eflags);
240 * Set up an AFTER-trigger statement context, unless told not to, or
241 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
243 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
244 AfterTriggerBeginQuery();
246 /* Enter parallel mode, if required by the query. */
247 if (queryDesc->plannedstmt->parallelModeNeeded &&
248 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
251 MemoryContextSwitchTo(oldcontext);
254 /* ----------------------------------------------------------------
257 * This is the main routine of the executor module. It accepts
258 * the query descriptor from the traffic cop and executes the
261 * ExecutorStart must have been called already.
263 * If direction is NoMovementScanDirection then nothing is done
264 * except to start up/shut down the destination. Otherwise,
265 * we retrieve up to 'count' tuples in the specified direction.
267 * Note: count = 0 is interpreted as no portal limit, i.e., run to
268 * completion. Also note that the count limit is only applied to
269 * retrieved tuples, not for instance to those inserted/updated/deleted
270 * by a ModifyTable plan node.
272 * There is no return value, but output tuples (if any) are sent to
273 * the destination receiver specified in the QueryDesc; and the number
274 * of tuples processed at the top level can be found in
275 * estate->es_processed.
277 * We provide a function hook variable that lets loadable plugins
278 * get control when ExecutorRun is called. Such a plugin would
279 * normally call standard_ExecutorRun().
281 * ----------------------------------------------------------------
284 ExecutorRun(QueryDesc *queryDesc,
285 ScanDirection direction, long count)
287 if (ExecutorRun_hook)
288 (*ExecutorRun_hook) (queryDesc, direction, count);
290 standard_ExecutorRun(queryDesc, direction, count);
294 standard_ExecutorRun(QueryDesc *queryDesc,
295 ScanDirection direction, long count)
301 MemoryContext oldcontext;
304 Assert(queryDesc != NULL);
306 estate = queryDesc->estate;
308 Assert(estate != NULL);
309 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
312 * Switch into per-query memory context
314 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
316 /* Allow instrumentation of Executor overall runtime */
317 if (queryDesc->totaltime)
318 InstrStartNode(queryDesc->totaltime);
321 * extract information from the query descriptor and the query feature.
323 operation = queryDesc->operation;
324 dest = queryDesc->dest;
327 * startup tuple receiver, if we will be emitting tuples
329 estate->es_processed = 0;
330 estate->es_lastoid = InvalidOid;
332 sendTuples = (operation == CMD_SELECT ||
333 queryDesc->plannedstmt->hasReturning);
336 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
341 if (!ScanDirectionIsNoMovement(direction))
343 queryDesc->planstate,
350 /* Allow nodes to release or shut down resources. */
351 (void) ExecShutdownNode(queryDesc->planstate);
354 * shutdown tuple receiver, if we started it
357 (*dest->rShutdown) (dest);
359 if (queryDesc->totaltime)
360 InstrStopNode(queryDesc->totaltime, estate->es_processed);
362 MemoryContextSwitchTo(oldcontext);
365 /* ----------------------------------------------------------------
368 * This routine must be called after the last ExecutorRun call.
369 * It performs cleanup such as firing AFTER triggers. It is
370 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
371 * include these actions in the total runtime.
373 * We provide a function hook variable that lets loadable plugins
374 * get control when ExecutorFinish is called. Such a plugin would
375 * normally call standard_ExecutorFinish().
377 * ----------------------------------------------------------------
380 ExecutorFinish(QueryDesc *queryDesc)
382 if (ExecutorFinish_hook)
383 (*ExecutorFinish_hook) (queryDesc);
385 standard_ExecutorFinish(queryDesc);
389 standard_ExecutorFinish(QueryDesc *queryDesc)
392 MemoryContext oldcontext;
395 Assert(queryDesc != NULL);
397 estate = queryDesc->estate;
399 Assert(estate != NULL);
400 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
402 /* This should be run once and only once per Executor instance */
403 Assert(!estate->es_finished);
405 /* Switch into per-query memory context */
406 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
408 /* Allow instrumentation of Executor overall runtime */
409 if (queryDesc->totaltime)
410 InstrStartNode(queryDesc->totaltime);
412 /* Run ModifyTable nodes to completion */
413 ExecPostprocessPlan(estate);
415 /* Execute queued AFTER triggers, unless told not to */
416 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
417 AfterTriggerEndQuery(estate);
419 if (queryDesc->totaltime)
420 InstrStopNode(queryDesc->totaltime, 0);
422 MemoryContextSwitchTo(oldcontext);
424 estate->es_finished = true;
427 /* ----------------------------------------------------------------
430 * This routine must be called at the end of execution of any
433 * We provide a function hook variable that lets loadable plugins
434 * get control when ExecutorEnd is called. Such a plugin would
435 * normally call standard_ExecutorEnd().
437 * ----------------------------------------------------------------
440 ExecutorEnd(QueryDesc *queryDesc)
442 if (ExecutorEnd_hook)
443 (*ExecutorEnd_hook) (queryDesc);
445 standard_ExecutorEnd(queryDesc);
449 standard_ExecutorEnd(QueryDesc *queryDesc)
452 MemoryContext oldcontext;
455 Assert(queryDesc != NULL);
457 estate = queryDesc->estate;
459 Assert(estate != NULL);
462 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
463 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
464 * might forget to call it.
466 Assert(estate->es_finished ||
467 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
470 * Switch into per-query memory context to run ExecEndPlan
472 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
474 ExecEndPlan(queryDesc->planstate, estate);
476 /* do away with our snapshots */
477 UnregisterSnapshot(estate->es_snapshot);
478 UnregisterSnapshot(estate->es_crosscheck_snapshot);
481 * Must switch out of context before destroying it
483 MemoryContextSwitchTo(oldcontext);
485 /* Exit parallel mode, if it was required by the query. */
486 if (queryDesc->plannedstmt->parallelModeNeeded &&
487 !(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY))
491 * Release EState and per-query memory context. This should release
492 * everything the executor has allocated.
494 FreeExecutorState(estate);
496 /* Reset queryDesc fields that no longer point to anything */
497 queryDesc->tupDesc = NULL;
498 queryDesc->estate = NULL;
499 queryDesc->planstate = NULL;
500 queryDesc->totaltime = NULL;
503 /* ----------------------------------------------------------------
506 * This routine may be called on an open queryDesc to rewind it
508 * ----------------------------------------------------------------
511 ExecutorRewind(QueryDesc *queryDesc)
514 MemoryContext oldcontext;
517 Assert(queryDesc != NULL);
519 estate = queryDesc->estate;
521 Assert(estate != NULL);
523 /* It's probably not sensible to rescan updating queries */
524 Assert(queryDesc->operation == CMD_SELECT);
527 * Switch into per-query memory context
529 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
534 ExecReScan(queryDesc->planstate);
536 MemoryContextSwitchTo(oldcontext);
542 * Check access permissions for all relations listed in a range table.
544 * Returns true if permissions are adequate. Otherwise, throws an appropriate
545 * error if ereport_on_violation is true, or simply returns false otherwise.
547 * Note that this does NOT address row level security policies (aka: RLS). If
548 * rows will be returned to the user as a result of this permission check
549 * passing, then RLS also needs to be consulted (and check_enable_rls()).
551 * See rewrite/rowsecurity.c.
554 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
559 foreach(l, rangeTable)
561 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
563 result = ExecCheckRTEPerms(rte);
566 Assert(rte->rtekind == RTE_RELATION);
567 if (ereport_on_violation)
568 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
569 get_rel_name(rte->relid));
574 if (ExecutorCheckPerms_hook)
575 result = (*ExecutorCheckPerms_hook) (rangeTable,
576 ereport_on_violation);
582 * Check access permissions for a single RTE.
585 ExecCheckRTEPerms(RangeTblEntry *rte)
587 AclMode requiredPerms;
589 AclMode remainingPerms;
594 * Only plain-relation RTEs need to be checked here. Function RTEs are
595 * checked by init_fcache when the function is prepared for execution.
596 * Join, subquery, and special RTEs need no checks.
598 if (rte->rtekind != RTE_RELATION)
602 * No work if requiredPerms is empty.
604 requiredPerms = rte->requiredPerms;
605 if (requiredPerms == 0)
611 * userid to check as: current user unless we have a setuid indication.
613 * Note: GetUserId() is presently fast enough that there's no harm in
614 * calling it separately for each RTE. If that stops being true, we could
615 * call it once in ExecCheckRTPerms and pass the userid down from there.
616 * But for now, no need for the extra clutter.
618 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
621 * We must have *all* the requiredPerms bits, but some of the bits can be
622 * satisfied from column-level rather than relation-level permissions.
623 * First, remove any bits that are satisfied by relation permissions.
625 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
626 remainingPerms = requiredPerms & ~relPerms;
627 if (remainingPerms != 0)
632 * If we lack any permissions that exist only as relation permissions,
633 * we can fail straight away.
635 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
639 * Check to see if we have the needed privileges at column level.
641 * Note: failures just report a table-level error; it would be nicer
642 * to report a column-level error if we have some but not all of the
645 if (remainingPerms & ACL_SELECT)
648 * When the query doesn't explicitly reference any columns (for
649 * example, SELECT COUNT(*) FROM table), allow the query if we
650 * have SELECT on any column of the rel, as per SQL spec.
652 if (bms_is_empty(rte->selectedCols))
654 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
655 ACLMASK_ANY) != ACLCHECK_OK)
659 while ((col = bms_next_member(rte->selectedCols, col)) >= 0)
661 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
662 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
664 if (attno == InvalidAttrNumber)
666 /* Whole-row reference, must have priv on all cols */
667 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
668 ACLMASK_ALL) != ACLCHECK_OK)
673 if (pg_attribute_aclcheck(relOid, attno, userid,
674 ACL_SELECT) != ACLCHECK_OK)
681 * Basically the same for the mod columns, for both INSERT and UPDATE
682 * privilege as specified by remainingPerms.
684 if (remainingPerms & ACL_INSERT && !ExecCheckRTEPermsModified(relOid,
690 if (remainingPerms & ACL_UPDATE && !ExecCheckRTEPermsModified(relOid,
700 * ExecCheckRTEPermsModified
701 * Check INSERT or UPDATE access permissions for a single RTE (these
702 * are processed uniformly).
705 ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
706 AclMode requiredPerms)
711 * When the query doesn't explicitly update any columns, allow the query
712 * if we have permission on any column of the rel. This is to handle
713 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
715 if (bms_is_empty(modifiedCols))
717 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
718 ACLMASK_ANY) != ACLCHECK_OK)
722 while ((col = bms_next_member(modifiedCols, col)) >= 0)
724 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
725 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
727 if (attno == InvalidAttrNumber)
729 /* whole-row reference can't happen here */
730 elog(ERROR, "whole-row update is not implemented");
734 if (pg_attribute_aclcheck(relOid, attno, userid,
735 requiredPerms) != ACLCHECK_OK)
743 * Check that the query does not imply any writes to non-temp tables;
744 * unless we're in parallel mode, in which case don't even allow writes
747 * Note: in a Hot Standby slave this would need to reject writes to temp
748 * tables just as we do in parallel mode; but an HS slave can't have created
749 * any temp tables in the first place, so no need to check that.
752 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
757 * Fail if write permissions are requested in parallel mode for table
758 * (temp or non-temp), otherwise fail for any non-temp table.
760 foreach(l, plannedstmt->rtable)
762 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
764 if (rte->rtekind != RTE_RELATION)
767 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
770 if (isTempNamespace(get_rel_namespace(rte->relid)))
773 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
776 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
777 PreventCommandIfParallelMode(CreateCommandTag((Node *) plannedstmt));
781 /* ----------------------------------------------------------------
784 * Initializes the query plan: open files, allocate storage
785 * and start up the rule manager
786 * ----------------------------------------------------------------
789 InitPlan(QueryDesc *queryDesc, int eflags)
791 CmdType operation = queryDesc->operation;
792 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
793 Plan *plan = plannedstmt->planTree;
794 List *rangeTable = plannedstmt->rtable;
795 EState *estate = queryDesc->estate;
796 PlanState *planstate;
802 * Do permissions checks
804 ExecCheckRTPerms(rangeTable, true);
807 * initialize the node's execution state
809 estate->es_range_table = rangeTable;
810 estate->es_plannedstmt = plannedstmt;
813 * initialize result relation stuff, and open/lock the result rels.
815 * We must do this before initializing the plan tree, else we might try to
816 * do a lock upgrade if a result rel is also a source rel.
818 if (plannedstmt->resultRelations)
820 List *resultRelations = plannedstmt->resultRelations;
821 int numResultRelations = list_length(resultRelations);
822 ResultRelInfo *resultRelInfos;
823 ResultRelInfo *resultRelInfo;
825 resultRelInfos = (ResultRelInfo *)
826 palloc(numResultRelations * sizeof(ResultRelInfo));
827 resultRelInfo = resultRelInfos;
828 foreach(l, resultRelations)
830 Index resultRelationIndex = lfirst_int(l);
831 Oid resultRelationOid;
832 Relation resultRelation;
834 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
835 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
836 InitResultRelInfo(resultRelInfo,
839 estate->es_instrument);
842 estate->es_result_relations = resultRelInfos;
843 estate->es_num_result_relations = numResultRelations;
844 /* es_result_relation_info is NULL except when within ModifyTable */
845 estate->es_result_relation_info = NULL;
850 * if no result relation, then set state appropriately
852 estate->es_result_relations = NULL;
853 estate->es_num_result_relations = 0;
854 estate->es_result_relation_info = NULL;
858 * Similarly, we have to lock relations selected FOR [KEY] UPDATE/SHARE
859 * before we initialize the plan tree, else we'd be risking lock upgrades.
860 * While we are at it, build the ExecRowMark list.
862 estate->es_rowMarks = NIL;
863 foreach(l, plannedstmt->rowMarks)
865 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
870 /* ignore "parent" rowmarks; they are irrelevant at runtime */
874 /* get relation's OID (will produce InvalidOid if subquery) */
875 relid = getrelid(rc->rti, rangeTable);
878 * If you change the conditions under which rel locks are acquired
879 * here, be sure to adjust ExecOpenScanRelation to match.
881 switch (rc->markType)
883 case ROW_MARK_EXCLUSIVE:
884 case ROW_MARK_NOKEYEXCLUSIVE:
886 case ROW_MARK_KEYSHARE:
887 relation = heap_open(relid, RowShareLock);
889 case ROW_MARK_REFERENCE:
890 relation = heap_open(relid, AccessShareLock);
893 /* no physical table access is required */
897 elog(ERROR, "unrecognized markType: %d", rc->markType);
898 relation = NULL; /* keep compiler quiet */
902 /* Check that relation is a legal target for marking */
904 CheckValidRowMarkRel(relation, rc->markType);
906 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
907 erm->relation = relation;
910 erm->prti = rc->prti;
911 erm->rowmarkId = rc->rowmarkId;
912 erm->markType = rc->markType;
913 erm->strength = rc->strength;
914 erm->waitPolicy = rc->waitPolicy;
915 erm->ermActive = false;
916 ItemPointerSetInvalid(&(erm->curCtid));
917 erm->ermExtra = NULL;
918 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
922 * Initialize the executor's tuple table to empty.
924 estate->es_tupleTable = NIL;
925 estate->es_trig_tuple_slot = NULL;
926 estate->es_trig_oldtup_slot = NULL;
927 estate->es_trig_newtup_slot = NULL;
929 /* mark EvalPlanQual not active */
930 estate->es_epqTuple = NULL;
931 estate->es_epqTupleSet = NULL;
932 estate->es_epqScanDone = NULL;
935 * Initialize private state information for each SubPlan. We must do this
936 * before running ExecInitNode on the main query tree, since
937 * ExecInitSubPlan expects to be able to find these entries.
939 Assert(estate->es_subplanstates == NIL);
940 i = 1; /* subplan indices count from 1 */
941 foreach(l, plannedstmt->subplans)
943 Plan *subplan = (Plan *) lfirst(l);
944 PlanState *subplanstate;
948 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
949 * it is a parameterless subplan (not initplan), we suggest that it be
950 * prepared to handle REWIND efficiently; otherwise there is no need.
953 & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);
954 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
955 sp_eflags |= EXEC_FLAG_REWIND;
957 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
959 estate->es_subplanstates = lappend(estate->es_subplanstates,
966 * Initialize the private state information for all the nodes in the query
967 * tree. This opens files, allocates storage and leaves us ready to start
970 planstate = ExecInitNode(plan, estate, eflags);
973 * Get the tuple descriptor describing the type of tuples to return.
975 tupType = ExecGetResultType(planstate);
978 * Initialize the junk filter if needed. SELECT queries need a filter if
979 * there are any junk attrs in the top-level tlist.
981 if (operation == CMD_SELECT)
983 bool junk_filter_needed = false;
986 foreach(tlist, plan->targetlist)
988 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
992 junk_filter_needed = true;
997 if (junk_filter_needed)
1001 j = ExecInitJunkFilter(planstate->plan->targetlist,
1003 ExecInitExtraTupleSlot(estate));
1004 estate->es_junkFilter = j;
1006 /* Want to return the cleaned tuple type */
1007 tupType = j->jf_cleanTupType;
1011 queryDesc->tupDesc = tupType;
1012 queryDesc->planstate = planstate;
1016 * Check that a proposed result relation is a legal target for the operation
1018 * Generally the parser and/or planner should have noticed any such mistake
1019 * already, but let's make sure.
1021 * Note: when changing this function, you probably also need to look at
1022 * CheckValidRowMarkRel.
1025 CheckValidResultRel(Relation resultRel, CmdType operation)
1027 TriggerDesc *trigDesc = resultRel->trigdesc;
1028 FdwRoutine *fdwroutine;
1030 switch (resultRel->rd_rel->relkind)
1032 case RELKIND_RELATION:
1035 case RELKIND_SEQUENCE:
1037 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1038 errmsg("cannot change sequence \"%s\"",
1039 RelationGetRelationName(resultRel))));
1041 case RELKIND_TOASTVALUE:
1043 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1044 errmsg("cannot change TOAST relation \"%s\"",
1045 RelationGetRelationName(resultRel))));
1050 * Okay only if there's a suitable INSTEAD OF trigger. Messages
1051 * here should match rewriteHandler.c's rewriteTargetView, except
1052 * that we omit errdetail because we haven't got the information
1053 * handy (and given that we really shouldn't get here anyway, it's
1054 * not worth great exertion to get).
1059 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1061 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1062 errmsg("cannot insert into view \"%s\"",
1063 RelationGetRelationName(resultRel)),
1064 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
1067 if (!trigDesc || !trigDesc->trig_update_instead_row)
1069 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1070 errmsg("cannot update view \"%s\"",
1071 RelationGetRelationName(resultRel)),
1072 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
1075 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1077 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1078 errmsg("cannot delete from view \"%s\"",
1079 RelationGetRelationName(resultRel)),
1080 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
1083 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1087 case RELKIND_MATVIEW:
1088 if (!MatViewIncrementalMaintenanceIsEnabled())
1090 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1091 errmsg("cannot change materialized view \"%s\"",
1092 RelationGetRelationName(resultRel))));
1094 case RELKIND_FOREIGN_TABLE:
1095 /* Okay only if the FDW supports it */
1096 fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1100 if (fdwroutine->ExecForeignInsert == NULL)
1102 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1103 errmsg("cannot insert into foreign table \"%s\"",
1104 RelationGetRelationName(resultRel))));
1105 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1106 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1108 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1109 errmsg("foreign table \"%s\" does not allow inserts",
1110 RelationGetRelationName(resultRel))));
1113 if (fdwroutine->ExecForeignUpdate == NULL)
1115 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1116 errmsg("cannot update foreign table \"%s\"",
1117 RelationGetRelationName(resultRel))));
1118 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1119 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1121 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1122 errmsg("foreign table \"%s\" does not allow updates",
1123 RelationGetRelationName(resultRel))));
1126 if (fdwroutine->ExecForeignDelete == NULL)
1128 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1129 errmsg("cannot delete from foreign table \"%s\"",
1130 RelationGetRelationName(resultRel))));
1131 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1132 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1134 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1135 errmsg("foreign table \"%s\" does not allow deletes",
1136 RelationGetRelationName(resultRel))));
1139 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1145 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1146 errmsg("cannot change relation \"%s\"",
1147 RelationGetRelationName(resultRel))));
1153 * Check that a proposed rowmark target relation is a legal target
1155 * In most cases parser and/or planner should have noticed this already, but
1156 * they don't cover all cases.
1159 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1161 FdwRoutine *fdwroutine;
1163 switch (rel->rd_rel->relkind)
1165 case RELKIND_RELATION:
1168 case RELKIND_SEQUENCE:
1169 /* Must disallow this because we don't vacuum sequences */
1171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1172 errmsg("cannot lock rows in sequence \"%s\"",
1173 RelationGetRelationName(rel))));
1175 case RELKIND_TOASTVALUE:
1176 /* We could allow this, but there seems no good reason to */
1178 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1179 errmsg("cannot lock rows in TOAST relation \"%s\"",
1180 RelationGetRelationName(rel))));
1183 /* Should not get here; planner should have expanded the view */
1185 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1186 errmsg("cannot lock rows in view \"%s\"",
1187 RelationGetRelationName(rel))));
1189 case RELKIND_MATVIEW:
1190 /* Allow referencing a matview, but not actual locking clauses */
1191 if (markType != ROW_MARK_REFERENCE)
1193 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1194 errmsg("cannot lock rows in materialized view \"%s\"",
1195 RelationGetRelationName(rel))));
1197 case RELKIND_FOREIGN_TABLE:
1198 /* Okay only if the FDW supports it */
1199 fdwroutine = GetFdwRoutineForRelation(rel, false);
1200 if (fdwroutine->RefetchForeignRow == NULL)
1202 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1203 errmsg("cannot lock rows in foreign table \"%s\"",
1204 RelationGetRelationName(rel))));
1208 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1209 errmsg("cannot lock rows in relation \"%s\"",
1210 RelationGetRelationName(rel))));
1216 * Initialize ResultRelInfo data for one result relation
1218 * Caution: before Postgres 9.1, this function included the relkind checking
1219 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1220 * appropriate. Be sure callers cover those needs.
1223 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1224 Relation resultRelationDesc,
1225 Index resultRelationIndex,
1226 int instrument_options)
1228 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1229 resultRelInfo->type = T_ResultRelInfo;
1230 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1231 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1232 resultRelInfo->ri_NumIndices = 0;
1233 resultRelInfo->ri_IndexRelationDescs = NULL;
1234 resultRelInfo->ri_IndexRelationInfo = NULL;
1235 /* make a copy so as not to depend on relcache info not changing... */
1236 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1237 if (resultRelInfo->ri_TrigDesc)
1239 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1241 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1242 palloc0(n * sizeof(FmgrInfo));
1243 resultRelInfo->ri_TrigWhenExprs = (List **)
1244 palloc0(n * sizeof(List *));
1245 if (instrument_options)
1246 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1250 resultRelInfo->ri_TrigFunctions = NULL;
1251 resultRelInfo->ri_TrigWhenExprs = NULL;
1252 resultRelInfo->ri_TrigInstrument = NULL;
1254 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1255 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1257 resultRelInfo->ri_FdwRoutine = NULL;
1258 resultRelInfo->ri_FdwState = NULL;
1259 resultRelInfo->ri_ConstraintExprs = NULL;
1260 resultRelInfo->ri_junkFilter = NULL;
1261 resultRelInfo->ri_projectReturning = NULL;
1265 * ExecGetTriggerResultRel
1267 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1268 * triggers are fired on one of the result relations of the query, and so
1269 * we can just return a member of the es_result_relations array. (Note: in
1270 * self-join situations there might be multiple members with the same OID;
1271 * if so it doesn't matter which one we pick.) However, it is sometimes
1272 * necessary to fire triggers on other relations; this happens mainly when an
1273 * RI update trigger queues additional triggers on other relations, which will
1274 * be processed in the context of the outer query. For efficiency's sake,
1275 * we want to have a ResultRelInfo for those triggers too; that can avoid
1276 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1277 * ANALYZE to report the runtimes of such triggers.) So we make additional
1278 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1281 ExecGetTriggerResultRel(EState *estate, Oid relid)
1283 ResultRelInfo *rInfo;
1287 MemoryContext oldcontext;
1289 /* First, search through the query result relations */
1290 rInfo = estate->es_result_relations;
1291 nr = estate->es_num_result_relations;
1294 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1299 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1300 foreach(l, estate->es_trig_target_relations)
1302 rInfo = (ResultRelInfo *) lfirst(l);
1303 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1306 /* Nope, so we need a new one */
1309 * Open the target relation's relcache entry. We assume that an
1310 * appropriate lock is still held by the backend from whenever the trigger
1311 * event got queued, so we need take no new lock here. Also, we need not
1312 * recheck the relkind, so no need for CheckValidResultRel.
1314 rel = heap_open(relid, NoLock);
1317 * Make the new entry in the right context.
1319 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1320 rInfo = makeNode(ResultRelInfo);
1321 InitResultRelInfo(rInfo,
1323 0, /* dummy rangetable index */
1324 estate->es_instrument);
1325 estate->es_trig_target_relations =
1326 lappend(estate->es_trig_target_relations, rInfo);
1327 MemoryContextSwitchTo(oldcontext);
1330 * Currently, we don't need any index information in ResultRelInfos used
1331 * only for triggers, so no need to call ExecOpenIndices.
1338 * ExecContextForcesOids
1340 * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1341 * we need to ensure that result tuples have space for an OID iff they are
1342 * going to be stored into a relation that has OIDs. In other contexts
1343 * we are free to choose whether to leave space for OIDs in result tuples
1344 * (we generally don't want to, but we do if a physical-tlist optimization
1345 * is possible). This routine checks the plan context and returns TRUE if the
1346 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1347 * *hasoids is set to the required value.
1349 * One reason this is ugly is that all plan nodes in the plan tree will emit
1350 * tuples with space for an OID, though we really only need the topmost node
1351 * to do so. However, node types like Sort don't project new tuples but just
1352 * return their inputs, and in those cases the requirement propagates down
1353 * to the input node. Eventually we might make this code smart enough to
1354 * recognize how far down the requirement really goes, but for now we just
1355 * make all plan nodes do the same thing if the top level forces the choice.
1357 * We assume that if we are generating tuples for INSERT or UPDATE,
1358 * estate->es_result_relation_info is already set up to describe the target
1359 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1360 * the target relations may have OIDs and some not. We have to make the
1361 * decisions on a per-relation basis as we initialize each of the subplans of
1362 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1363 * while initializing each subplan.
1365 * CREATE TABLE AS is even uglier, because we don't have the target relation's
1366 * descriptor available when this code runs; we have to look aside at the
1367 * flags passed to ExecutorStart().
1370 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1372 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1376 Relation rel = ri->ri_RelationDesc;
1380 *hasoids = rel->rd_rel->relhasoids;
1385 if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1390 if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1399 /* ----------------------------------------------------------------
1400 * ExecPostprocessPlan
1402 * Give plan nodes a final chance to execute before shutdown
1403 * ----------------------------------------------------------------
1406 ExecPostprocessPlan(EState *estate)
1411 * Make sure nodes run forward.
1413 estate->es_direction = ForwardScanDirection;
1416 * Run any secondary ModifyTable nodes to completion, in case the main
1417 * query did not fetch all rows from them. (We do this to ensure that
1418 * such nodes have predictable results.)
1420 foreach(lc, estate->es_auxmodifytables)
1422 PlanState *ps = (PlanState *) lfirst(lc);
1426 TupleTableSlot *slot;
1428 /* Reset the per-output-tuple exprcontext each time */
1429 ResetPerTupleExprContext(estate);
1431 slot = ExecProcNode(ps);
1433 if (TupIsNull(slot))
1439 /* ----------------------------------------------------------------
1442 * Cleans up the query plan -- closes files and frees up storage
1444 * NOTE: we are no longer very worried about freeing storage per se
1445 * in this code; FreeExecutorState should be guaranteed to release all
1446 * memory that needs to be released. What we are worried about doing
1447 * is closing relations and dropping buffer pins. Thus, for example,
1448 * tuple tables must be cleared or dropped to ensure pins are released.
1449 * ----------------------------------------------------------------
1452 ExecEndPlan(PlanState *planstate, EState *estate)
1454 ResultRelInfo *resultRelInfo;
1459 * shut down the node-type-specific query processing
1461 ExecEndNode(planstate);
1466 foreach(l, estate->es_subplanstates)
1468 PlanState *subplanstate = (PlanState *) lfirst(l);
1470 ExecEndNode(subplanstate);
1474 * destroy the executor's tuple table. Actually we only care about
1475 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1476 * the TupleTableSlots, since the containing memory context is about to go
1479 ExecResetTupleTable(estate->es_tupleTable, false);
1482 * close the result relation(s) if any, but hold locks until xact commit.
1484 resultRelInfo = estate->es_result_relations;
1485 for (i = estate->es_num_result_relations; i > 0; i--)
1487 /* Close indices and then the relation itself */
1488 ExecCloseIndices(resultRelInfo);
1489 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1494 * likewise close any trigger target relations
1496 foreach(l, estate->es_trig_target_relations)
1498 resultRelInfo = (ResultRelInfo *) lfirst(l);
1499 /* Close indices and then the relation itself */
1500 ExecCloseIndices(resultRelInfo);
1501 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1505 * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1508 foreach(l, estate->es_rowMarks)
1510 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1513 heap_close(erm->relation, NoLock);
1517 /* ----------------------------------------------------------------
1520 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1521 * moving in the specified direction.
1523 * Runs to completion if numberTuples is 0
1525 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1527 * ----------------------------------------------------------------
1530 ExecutePlan(EState *estate,
1531 PlanState *planstate,
1535 ScanDirection direction,
1538 TupleTableSlot *slot;
1539 long current_tuple_count;
1542 * initialize local variables
1544 current_tuple_count = 0;
1547 * Set the direction.
1549 estate->es_direction = direction;
1552 * Loop until we've processed the proper number of tuples from the plan.
1556 /* Reset the per-output-tuple exprcontext */
1557 ResetPerTupleExprContext(estate);
1560 * Execute the plan and obtain a tuple
1562 slot = ExecProcNode(planstate);
1565 * if the tuple is null, then we assume there is nothing more to
1566 * process so we just end the loop...
1568 if (TupIsNull(slot))
1572 * If we have a junk filter, then project a new tuple with the junk
1575 * Store this new "clean" tuple in the junkfilter's resultSlot.
1576 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1577 * because that tuple slot has the wrong descriptor.)
1579 if (estate->es_junkFilter != NULL)
1580 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1583 * If we are supposed to send the tuple somewhere, do so. (In
1584 * practice, this is probably always the case at this point.)
1587 (*dest->receiveSlot) (slot, dest);
1590 * Count tuples processed, if this is a SELECT. (For other operation
1591 * types, the ModifyTable plan node must count the appropriate
1594 if (operation == CMD_SELECT)
1595 (estate->es_processed)++;
1598 * check our tuple count.. if we've processed the proper number then
1599 * quit, else loop again and process more tuples. Zero numberTuples
1602 current_tuple_count++;
1603 if (numberTuples && numberTuples == current_tuple_count)
1610 * ExecRelCheck --- check that tuple meets constraints for result relation
1612 * Returns NULL if OK, else name of failed check constraint
1615 ExecRelCheck(ResultRelInfo *resultRelInfo,
1616 TupleTableSlot *slot, EState *estate)
1618 Relation rel = resultRelInfo->ri_RelationDesc;
1619 int ncheck = rel->rd_att->constr->num_check;
1620 ConstrCheck *check = rel->rd_att->constr->check;
1621 ExprContext *econtext;
1622 MemoryContext oldContext;
1627 * If first time through for this result relation, build expression
1628 * nodetrees for rel's constraint expressions. Keep them in the per-query
1629 * memory context so they'll survive throughout the query.
1631 if (resultRelInfo->ri_ConstraintExprs == NULL)
1633 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1634 resultRelInfo->ri_ConstraintExprs =
1635 (List **) palloc(ncheck * sizeof(List *));
1636 for (i = 0; i < ncheck; i++)
1638 /* ExecQual wants implicit-AND form */
1639 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1640 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1641 ExecPrepareExpr((Expr *) qual, estate);
1643 MemoryContextSwitchTo(oldContext);
1647 * We will use the EState's per-tuple context for evaluating constraint
1648 * expressions (creating it if it's not already there).
1650 econtext = GetPerTupleExprContext(estate);
1652 /* Arrange for econtext's scan tuple to be the tuple under test */
1653 econtext->ecxt_scantuple = slot;
1655 /* And evaluate the constraints */
1656 for (i = 0; i < ncheck; i++)
1658 qual = resultRelInfo->ri_ConstraintExprs[i];
1661 * NOTE: SQL specifies that a NULL result from a constraint expression
1662 * is not to be treated as a failure. Therefore, tell ExecQual to
1663 * return TRUE for NULL.
1665 if (!ExecQual(qual, econtext, true))
1666 return check[i].ccname;
1669 /* NULL result means no error */
1674 ExecConstraints(ResultRelInfo *resultRelInfo,
1675 TupleTableSlot *slot, EState *estate)
1677 Relation rel = resultRelInfo->ri_RelationDesc;
1678 TupleDesc tupdesc = RelationGetDescr(rel);
1679 TupleConstr *constr = tupdesc->constr;
1680 Bitmapset *modifiedCols;
1681 Bitmapset *insertedCols;
1682 Bitmapset *updatedCols;
1686 if (constr->has_not_null)
1688 int natts = tupdesc->natts;
1691 for (attrChk = 1; attrChk <= natts; attrChk++)
1693 if (tupdesc->attrs[attrChk - 1]->attnotnull &&
1694 slot_attisnull(slot, attrChk))
1698 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1699 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1700 modifiedCols = bms_union(insertedCols, updatedCols);
1701 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1708 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1709 errmsg("null value in column \"%s\" violates not-null constraint",
1710 NameStr(tupdesc->attrs[attrChk - 1]->attname)),
1711 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1712 errtablecol(rel, attrChk)));
1717 if (constr->num_check > 0)
1721 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1725 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1726 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1727 modifiedCols = bms_union(insertedCols, updatedCols);
1728 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1734 (errcode(ERRCODE_CHECK_VIOLATION),
1735 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1736 RelationGetRelationName(rel), failed),
1737 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1738 errtableconstraint(rel, failed)));
1744 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1745 * of the specified kind.
1747 * Note that this needs to be called multiple times to ensure that all kinds of
1748 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
1749 * CHECK OPTION set and from row level security policies). See ExecInsert()
1753 ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
1754 TupleTableSlot *slot, EState *estate)
1756 Relation rel = resultRelInfo->ri_RelationDesc;
1757 TupleDesc tupdesc = RelationGetDescr(rel);
1758 ExprContext *econtext;
1763 * We will use the EState's per-tuple context for evaluating constraint
1764 * expressions (creating it if it's not already there).
1766 econtext = GetPerTupleExprContext(estate);
1768 /* Arrange for econtext's scan tuple to be the tuple under test */
1769 econtext->ecxt_scantuple = slot;
1771 /* Check each of the constraints */
1772 forboth(l1, resultRelInfo->ri_WithCheckOptions,
1773 l2, resultRelInfo->ri_WithCheckOptionExprs)
1775 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1776 ExprState *wcoExpr = (ExprState *) lfirst(l2);
1779 * Skip any WCOs which are not the kind we are looking for at this
1782 if (wco->kind != kind)
1786 * WITH CHECK OPTION checks are intended to ensure that the new tuple
1787 * is visible (in the case of a view) or that it passes the
1788 * 'with-check' policy (in the case of row security). If the qual
1789 * evaluates to NULL or FALSE, then the new tuple won't be included in
1790 * the view or doesn't pass the 'with-check' policy for the table. We
1791 * need ExecQual to return FALSE for NULL to handle the view case (the
1792 * opposite of what we do above for CHECK constraints).
1794 if (!ExecQual((List *) wcoExpr, econtext, false))
1797 Bitmapset *modifiedCols;
1798 Bitmapset *insertedCols;
1799 Bitmapset *updatedCols;
1804 * For WITH CHECK OPTIONs coming from views, we might be
1805 * able to provide the details on the row, depending on
1806 * the permissions on the relation (that is, if the user
1807 * could view it directly anyway). For RLS violations, we
1808 * don't include the data since we don't know if the user
1809 * should be able to view the tuple as as that depends on
1812 case WCO_VIEW_CHECK:
1813 insertedCols = GetInsertedColumns(resultRelInfo, estate);
1814 updatedCols = GetUpdatedColumns(resultRelInfo, estate);
1815 modifiedCols = bms_union(insertedCols, updatedCols);
1816 val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
1823 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1824 errmsg("new row violates WITH CHECK OPTION for \"%s\"",
1826 val_desc ? errdetail("Failing row contains %s.",
1829 case WCO_RLS_INSERT_CHECK:
1830 case WCO_RLS_UPDATE_CHECK:
1831 if (wco->polname != NULL)
1833 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1834 errmsg("new row violates row level security policy \"%s\" for \"%s\"",
1835 wco->polname, wco->relname)));
1838 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1839 errmsg("new row violates row level security policy for \"%s\"",
1842 case WCO_RLS_CONFLICT_CHECK:
1843 if (wco->polname != NULL)
1845 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1846 errmsg("new row violates row level security policy \"%s\" (USING expression) for \"%s\"",
1847 wco->polname, wco->relname)));
1850 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1851 errmsg("new row violates row level security policy (USING expression) for \"%s\"",
1855 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
1863 * ExecBuildSlotValueDescription -- construct a string representing a tuple
1865 * This is intentionally very similar to BuildIndexValueDescription, but
1866 * unlike that function, we truncate long field values (to at most maxfieldlen
1867 * bytes). That seems necessary here since heap field values could be very
1868 * long, whereas index entries typically aren't so wide.
1870 * Also, unlike the case with index entries, we need to be prepared to ignore
1871 * dropped columns. We used to use the slot's tuple descriptor to decode the
1872 * data, but the slot's descriptor doesn't identify dropped columns, so we
1873 * now need to be passed the relation's descriptor.
1875 * Note that, like BuildIndexValueDescription, if the user does not have
1876 * permission to view any of the columns involved, a NULL is returned. Unlike
1877 * BuildIndexValueDescription, if the user has access to view a subset of the
1878 * column involved, that subset will be returned with a key identifying which
1882 ExecBuildSlotValueDescription(Oid reloid,
1883 TupleTableSlot *slot,
1885 Bitmapset *modifiedCols,
1889 StringInfoData collist;
1890 bool write_comma = false;
1891 bool write_comma_collist = false;
1893 AclResult aclresult;
1894 bool table_perm = false;
1895 bool any_perm = false;
1898 * Check if RLS is enabled and should be active for the relation; if so,
1899 * then don't return anything. Otherwise, go through normal permission
1902 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
1905 initStringInfo(&buf);
1907 appendStringInfoChar(&buf, '(');
1910 * Check if the user has permissions to see the row. Table-level SELECT
1911 * allows access to all columns. If the user does not have table-level
1912 * SELECT then we check each column and include those the user has SELECT
1913 * rights on. Additionally, we always include columns the user provided
1916 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
1917 if (aclresult != ACLCHECK_OK)
1919 /* Set up the buffer for the column list */
1920 initStringInfo(&collist);
1921 appendStringInfoChar(&collist, '(');
1924 table_perm = any_perm = true;
1926 /* Make sure the tuple is fully deconstructed */
1927 slot_getallattrs(slot);
1929 for (i = 0; i < tupdesc->natts; i++)
1931 bool column_perm = false;
1935 /* ignore dropped columns */
1936 if (tupdesc->attrs[i]->attisdropped)
1942 * No table-level SELECT, so need to make sure they either have
1943 * SELECT rights on the column or that they have provided the data
1944 * for the column. If not, omit this column from the error
1947 aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
1948 GetUserId(), ACL_SELECT);
1949 if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
1950 modifiedCols) || aclresult == ACLCHECK_OK)
1952 column_perm = any_perm = true;
1954 if (write_comma_collist)
1955 appendStringInfoString(&collist, ", ");
1957 write_comma_collist = true;
1959 appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
1963 if (table_perm || column_perm)
1965 if (slot->tts_isnull[i])
1972 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1973 &foutoid, &typisvarlena);
1974 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1978 appendStringInfoString(&buf, ", ");
1982 /* truncate if needed */
1983 vallen = strlen(val);
1984 if (vallen <= maxfieldlen)
1985 appendStringInfoString(&buf, val);
1988 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
1989 appendBinaryStringInfo(&buf, val, vallen);
1990 appendStringInfoString(&buf, "...");
1995 /* If we end up with zero columns being returned, then return NULL. */
1999 appendStringInfoChar(&buf, ')');
2003 appendStringInfoString(&collist, ") = ");
2004 appendStringInfoString(&collist, buf.data);
2006 return collist.data;
2014 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2015 * given ResultRelInfo
2018 ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2021 Bitmapset *updatedCols;
2024 * Compute lock mode to use. If columns that are part of the key have not
2025 * been modified, then we can use a weaker lock, allowing for better
2028 updatedCols = GetUpdatedColumns(relinfo, estate);
2029 keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2030 INDEX_ATTR_BITMAP_KEY);
2032 if (bms_overlap(keyCols, updatedCols))
2033 return LockTupleExclusive;
2035 return LockTupleNoKeyExclusive;
2039 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2041 * If no such struct, either return NULL or throw error depending on missing_ok
2044 ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2048 foreach(lc, estate->es_rowMarks)
2050 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
2052 if (erm->rti == rti)
2056 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2061 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2063 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2064 * input plan node (not planstate node!). We need the latter to find out
2065 * the column numbers of the resjunk columns.
2068 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2070 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
2073 aerm->rowmark = erm;
2075 /* Look up the resjunk columns associated with this rowmark */
2076 if (erm->markType != ROW_MARK_COPY)
2078 /* need ctid for all methods other than COPY */
2079 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2080 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2082 if (!AttributeNumberIsValid(aerm->ctidAttNo))
2083 elog(ERROR, "could not find junk %s column", resname);
2087 /* need wholerow if COPY */
2088 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2089 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2091 if (!AttributeNumberIsValid(aerm->wholeAttNo))
2092 elog(ERROR, "could not find junk %s column", resname);
2095 /* if child rel, need tableoid */
2096 if (erm->rti != erm->prti)
2098 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2099 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2101 if (!AttributeNumberIsValid(aerm->toidAttNo))
2102 elog(ERROR, "could not find junk %s column", resname);
2110 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2111 * process the updated version under READ COMMITTED rules.
2113 * See backend/executor/README for some info about how this works.
2118 * Check a modified tuple to see if we want to process its updated version
2119 * under READ COMMITTED rules.
2121 * estate - outer executor state data
2122 * epqstate - state for EvalPlanQual rechecking
2123 * relation - table containing tuple
2124 * rti - rangetable index of table containing tuple
2125 * lockmode - requested tuple lock mode
2126 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2127 * priorXmax - t_xmax from the outdated tuple
2129 * *tid is also an output parameter: it's modified to hold the TID of the
2130 * latest version of the tuple (note this may be changed even on failure)
2132 * Returns a slot containing the new candidate update/delete tuple, or
2133 * NULL if we determine we shouldn't process the row.
2135 * Note: properly, lockmode should be declared as enum LockTupleMode,
2136 * but we use "int" to avoid having to include heapam.h in executor.h.
2139 EvalPlanQual(EState *estate, EPQState *epqstate,
2140 Relation relation, Index rti, int lockmode,
2141 ItemPointer tid, TransactionId priorXmax)
2143 TupleTableSlot *slot;
2144 HeapTuple copyTuple;
2149 * Get and lock the updated version of the row; if fail, return NULL.
2151 copyTuple = EvalPlanQualFetch(estate, relation, lockmode, LockWaitBlock,
2154 if (copyTuple == NULL)
2158 * For UPDATE/DELETE we have to return tid of actual row we're executing
2161 *tid = copyTuple->t_self;
2164 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2166 EvalPlanQualBegin(epqstate, estate);
2169 * Free old test tuple, if any, and store new tuple where relation's scan
2172 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
2175 * Fetch any non-locked source rows
2177 EvalPlanQualFetchRowMarks(epqstate);
2180 * Run the EPQ query. We assume it will return at most one tuple.
2182 slot = EvalPlanQualNext(epqstate);
2185 * If we got a tuple, force the slot to materialize the tuple so that it
2186 * is not dependent on any local state in the EPQ query (in particular,
2187 * it's highly likely that the slot contains references to any pass-by-ref
2188 * datums that may be present in copyTuple). As with the next step, this
2189 * is to guard against early re-use of the EPQ query.
2191 if (!TupIsNull(slot))
2192 (void) ExecMaterializeSlot(slot);
2195 * Clear out the test tuple. This is needed in case the EPQ query is
2196 * re-used to test a tuple for a different relation. (Not clear that can
2197 * really happen, but let's be safe.)
2199 EvalPlanQualSetTuple(epqstate, rti, NULL);
2205 * Fetch a copy of the newest version of an outdated tuple
2207 * estate - executor state data
2208 * relation - table containing tuple
2209 * lockmode - requested tuple lock mode
2210 * wait_policy - requested lock wait policy
2211 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2212 * priorXmax - t_xmax from the outdated tuple
2214 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
2215 * that there is no newest version (ie, the row was deleted not updated).
2216 * We also return NULL if the tuple is locked and the wait policy is to skip
2219 * If successful, we have locked the newest tuple version, so caller does not
2220 * need to worry about it changing anymore.
2222 * Note: properly, lockmode should be declared as enum LockTupleMode,
2223 * but we use "int" to avoid having to include heapam.h in executor.h.
2226 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
2227 LockWaitPolicy wait_policy,
2228 ItemPointer tid, TransactionId priorXmax)
2230 HeapTuple copyTuple = NULL;
2231 HeapTupleData tuple;
2232 SnapshotData SnapshotDirty;
2235 * fetch target tuple
2237 * Loop here to deal with updated or busy tuples
2239 InitDirtySnapshot(SnapshotDirty);
2240 tuple.t_self = *tid;
2245 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2248 HeapUpdateFailureData hufd;
2251 * If xmin isn't what we're expecting, the slot must have been
2252 * recycled and reused for an unrelated tuple. This implies that
2253 * the latest version of the row was deleted, so we need do
2254 * nothing. (Should be safe to examine xmin without getting
2255 * buffer's content lock. We assume reading a TransactionId to be
2256 * atomic, and Xmin never changes in an existing tuple, except to
2257 * invalid or frozen, and neither of those can match priorXmax.)
2259 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2262 ReleaseBuffer(buffer);
2266 /* otherwise xmin should not be dirty... */
2267 if (TransactionIdIsValid(SnapshotDirty.xmin))
2268 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2271 * If tuple is being updated by other transaction then we have to
2272 * wait for its commit/abort, or die trying.
2274 if (TransactionIdIsValid(SnapshotDirty.xmax))
2276 ReleaseBuffer(buffer);
2277 switch (wait_policy)
2280 XactLockTableWait(SnapshotDirty.xmax,
2281 relation, &tuple.t_self,
2285 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2286 return NULL; /* skip instead of waiting */
2289 if (!ConditionalXactLockTableWait(SnapshotDirty.xmax))
2291 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2292 errmsg("could not obtain lock on row in relation \"%s\"",
2293 RelationGetRelationName(relation))));
2296 continue; /* loop back to repeat heap_fetch */
2300 * If tuple was inserted by our own transaction, we have to check
2301 * cmin against es_output_cid: cmin >= current CID means our
2302 * command cannot see the tuple, so we should ignore it. Otherwise
2303 * heap_lock_tuple() will throw an error, and so would any later
2304 * attempt to update or delete the tuple. (We need not check cmax
2305 * because HeapTupleSatisfiesDirty will consider a tuple deleted
2306 * by our transaction dead, regardless of cmax.) We just checked
2307 * that priorXmax == xmin, so we can test that variable instead of
2308 * doing HeapTupleHeaderGetXmin again.
2310 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2311 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2313 ReleaseBuffer(buffer);
2318 * This is a live tuple, so now try to lock it.
2320 test = heap_lock_tuple(relation, &tuple,
2321 estate->es_output_cid,
2322 lockmode, wait_policy,
2323 false, &buffer, &hufd);
2324 /* We now have two pins on the buffer, get rid of one */
2325 ReleaseBuffer(buffer);
2329 case HeapTupleSelfUpdated:
2332 * The target tuple was already updated or deleted by the
2333 * current command, or by a later command in the current
2334 * transaction. We *must* ignore the tuple in the former
2335 * case, so as to avoid the "Halloween problem" of
2336 * repeated update attempts. In the latter case it might
2337 * be sensible to fetch the updated tuple instead, but
2338 * doing so would require changing heap_update and
2339 * heap_delete to not complain about updating "invisible"
2340 * tuples, which seems pretty scary (heap_lock_tuple will
2341 * not complain, but few callers expect
2342 * HeapTupleInvisible, and we're not one of them). So for
2343 * now, treat the tuple as deleted and do not process.
2345 ReleaseBuffer(buffer);
2348 case HeapTupleMayBeUpdated:
2349 /* successfully locked */
2352 case HeapTupleUpdated:
2353 ReleaseBuffer(buffer);
2354 if (IsolationUsesXactSnapshot())
2356 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2357 errmsg("could not serialize access due to concurrent update")));
2359 /* Should not encounter speculative tuple on recheck */
2360 Assert(!HeapTupleHeaderIsSpeculative(tuple.t_data));
2361 if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2363 /* it was updated, so look at the updated version */
2364 tuple.t_self = hufd.ctid;
2365 /* updated row should have xmin matching this xmax */
2366 priorXmax = hufd.xmax;
2369 /* tuple was deleted, so give up */
2372 case HeapTupleWouldBlock:
2373 ReleaseBuffer(buffer);
2376 case HeapTupleInvisible:
2377 elog(ERROR, "attempted to lock invisible tuple");
2380 ReleaseBuffer(buffer);
2381 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2383 return NULL; /* keep compiler quiet */
2387 * We got tuple - now copy it for use by recheck query.
2389 copyTuple = heap_copytuple(&tuple);
2390 ReleaseBuffer(buffer);
2395 * If the referenced slot was actually empty, the latest version of
2396 * the row must have been deleted, so we need do nothing.
2398 if (tuple.t_data == NULL)
2400 ReleaseBuffer(buffer);
2405 * As above, if xmin isn't what we're expecting, do nothing.
2407 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2410 ReleaseBuffer(buffer);
2415 * If we get here, the tuple was found but failed SnapshotDirty.
2416 * Assuming the xmin is either a committed xact or our own xact (as it
2417 * certainly should be if we're trying to modify the tuple), this must
2418 * mean that the row was updated or deleted by either a committed xact
2419 * or our own xact. If it was deleted, we can ignore it; if it was
2420 * updated then chain up to the next version and repeat the whole
2423 * As above, it should be safe to examine xmax and t_ctid without the
2424 * buffer content lock, because they can't be changing.
2426 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2428 /* deleted, so forget about it */
2429 ReleaseBuffer(buffer);
2433 /* updated, so look at the updated row */
2434 tuple.t_self = tuple.t_data->t_ctid;
2435 /* updated row should have xmin matching this xmax */
2436 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2437 ReleaseBuffer(buffer);
2438 /* loop back to fetch next in chain */
2442 * Return the copied tuple
2448 * EvalPlanQualInit -- initialize during creation of a plan state node
2449 * that might need to invoke EPQ processing.
2451 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2452 * with EvalPlanQualSetPlan.
2455 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2456 Plan *subplan, List *auxrowmarks, int epqParam)
2458 /* Mark the EPQ state inactive */
2459 epqstate->estate = NULL;
2460 epqstate->planstate = NULL;
2461 epqstate->origslot = NULL;
2462 /* ... and remember data that EvalPlanQualBegin will need */
2463 epqstate->plan = subplan;
2464 epqstate->arowMarks = auxrowmarks;
2465 epqstate->epqParam = epqParam;
2469 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2471 * We need this so that ModifyTable can deal with multiple subplans.
2474 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2476 /* If we have a live EPQ query, shut it down */
2477 EvalPlanQualEnd(epqstate);
2478 /* And set/change the plan pointer */
2479 epqstate->plan = subplan;
2480 /* The rowmarks depend on the plan, too */
2481 epqstate->arowMarks = auxrowmarks;
2485 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2487 * NB: passed tuple must be palloc'd; it may get freed later
2490 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2492 EState *estate = epqstate->estate;
2497 * free old test tuple, if any, and store new tuple where relation's scan
2500 if (estate->es_epqTuple[rti - 1] != NULL)
2501 heap_freetuple(estate->es_epqTuple[rti - 1]);
2502 estate->es_epqTuple[rti - 1] = tuple;
2503 estate->es_epqTupleSet[rti - 1] = true;
2507 * Fetch back the current test tuple (if any) for the specified RTI
2510 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2512 EState *estate = epqstate->estate;
2516 return estate->es_epqTuple[rti - 1];
2520 * Fetch the current row values for any non-locked relations that need
2521 * to be scanned by an EvalPlanQual operation. origslot must have been set
2522 * to contain the current result row (top-level row) that we need to recheck.
2525 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2529 Assert(epqstate->origslot != NULL);
2531 foreach(l, epqstate->arowMarks)
2533 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2534 ExecRowMark *erm = aerm->rowmark;
2537 HeapTupleData tuple;
2539 if (RowMarkRequiresRowShareLock(erm->markType))
2540 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2542 /* clear any leftover test tuple for this rel */
2543 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2545 /* if child rel, must check whether it produced this row */
2546 if (erm->rti != erm->prti)
2550 datum = ExecGetJunkAttribute(epqstate->origslot,
2553 /* non-locked rels could be on the inside of outer joins */
2556 tableoid = DatumGetObjectId(datum);
2558 Assert(OidIsValid(erm->relid));
2559 if (tableoid != erm->relid)
2561 /* this child is inactive right now */
2566 if (erm->markType == ROW_MARK_REFERENCE)
2568 HeapTuple copyTuple;
2570 Assert(erm->relation != NULL);
2572 /* fetch the tuple's ctid */
2573 datum = ExecGetJunkAttribute(epqstate->origslot,
2576 /* non-locked rels could be on the inside of outer joins */
2580 /* fetch requests on foreign tables must be passed to their FDW */
2581 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2583 FdwRoutine *fdwroutine;
2584 bool updated = false;
2586 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2587 /* this should have been checked already, but let's be safe */
2588 if (fdwroutine->RefetchForeignRow == NULL)
2590 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2591 errmsg("cannot lock rows in foreign table \"%s\"",
2592 RelationGetRelationName(erm->relation))));
2593 copyTuple = fdwroutine->RefetchForeignRow(epqstate->estate,
2597 if (copyTuple == NULL)
2598 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2601 * Ideally we'd insist on updated == false here, but that
2602 * assumes that FDWs can track that exactly, which they might
2603 * not be able to. So just ignore the flag.
2608 /* ordinary table, fetch the tuple */
2611 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2612 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2614 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2616 /* successful, copy tuple */
2617 copyTuple = heap_copytuple(&tuple);
2618 ReleaseBuffer(buffer);
2622 EvalPlanQualSetTuple(epqstate, erm->rti, copyTuple);
2628 Assert(erm->markType == ROW_MARK_COPY);
2630 /* fetch the whole-row Var for the relation */
2631 datum = ExecGetJunkAttribute(epqstate->origslot,
2634 /* non-locked rels could be on the inside of outer joins */
2637 td = DatumGetHeapTupleHeader(datum);
2639 /* build a temporary HeapTuple control structure */
2640 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2642 /* relation might be a foreign table, if so provide tableoid */
2643 tuple.t_tableOid = erm->relid;
2644 /* also copy t_ctid in case there's valid data there */
2645 tuple.t_self = td->t_ctid;
2647 /* copy and store tuple */
2648 EvalPlanQualSetTuple(epqstate, erm->rti,
2649 heap_copytuple(&tuple));
2655 * Fetch the next row (if any) from EvalPlanQual testing
2657 * (In practice, there should never be more than one row...)
2660 EvalPlanQualNext(EPQState *epqstate)
2662 MemoryContext oldcontext;
2663 TupleTableSlot *slot;
2665 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2666 slot = ExecProcNode(epqstate->planstate);
2667 MemoryContextSwitchTo(oldcontext);
2673 * Initialize or reset an EvalPlanQual state tree
2676 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2678 EState *estate = epqstate->estate;
2682 /* First time through, so create a child EState */
2683 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2688 * We already have a suitable child EPQ tree, so just reset it.
2690 int rtsize = list_length(parentestate->es_range_table);
2691 PlanState *planstate = epqstate->planstate;
2693 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2695 /* Recopy current values of parent parameters */
2696 if (parentestate->es_plannedstmt->nParamExec > 0)
2698 int i = parentestate->es_plannedstmt->nParamExec;
2702 /* copy value if any, but not execPlan link */
2703 estate->es_param_exec_vals[i].value =
2704 parentestate->es_param_exec_vals[i].value;
2705 estate->es_param_exec_vals[i].isnull =
2706 parentestate->es_param_exec_vals[i].isnull;
2711 * Mark child plan tree as needing rescan at all scan nodes. The
2712 * first ExecProcNode will take care of actually doing the rescan.
2714 planstate->chgParam = bms_add_member(planstate->chgParam,
2715 epqstate->epqParam);
2720 * Start execution of an EvalPlanQual plan tree.
2722 * This is a cut-down version of ExecutorStart(): we copy some state from
2723 * the top-level estate rather than initializing it fresh.
2726 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2730 MemoryContext oldcontext;
2733 rtsize = list_length(parentestate->es_range_table);
2735 epqstate->estate = estate = CreateExecutorState();
2737 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2740 * Child EPQ EStates share the parent's copy of unchanging state such as
2741 * the snapshot, rangetable, result-rel info, and external Param info.
2742 * They need their own copies of local state, including a tuple table,
2743 * es_param_exec_vals, etc.
2745 * The ResultRelInfo array management is trickier than it looks. We
2746 * create a fresh array for the child but copy all the content from the
2747 * parent. This is because it's okay for the child to share any
2748 * per-relation state the parent has already created --- but if the child
2749 * sets up any ResultRelInfo fields, such as its own junkfilter, that
2750 * state must *not* propagate back to the parent. (For one thing, the
2751 * pointed-to data is in a memory context that won't last long enough.)
2753 estate->es_direction = ForwardScanDirection;
2754 estate->es_snapshot = parentestate->es_snapshot;
2755 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2756 estate->es_range_table = parentestate->es_range_table;
2757 estate->es_plannedstmt = parentestate->es_plannedstmt;
2758 estate->es_junkFilter = parentestate->es_junkFilter;
2759 estate->es_output_cid = parentestate->es_output_cid;
2760 if (parentestate->es_num_result_relations > 0)
2762 int numResultRelations = parentestate->es_num_result_relations;
2763 ResultRelInfo *resultRelInfos;
2765 resultRelInfos = (ResultRelInfo *)
2766 palloc(numResultRelations * sizeof(ResultRelInfo));
2767 memcpy(resultRelInfos, parentestate->es_result_relations,
2768 numResultRelations * sizeof(ResultRelInfo));
2769 estate->es_result_relations = resultRelInfos;
2770 estate->es_num_result_relations = numResultRelations;
2772 /* es_result_relation_info must NOT be copied */
2773 /* es_trig_target_relations must NOT be copied */
2774 estate->es_rowMarks = parentestate->es_rowMarks;
2775 estate->es_top_eflags = parentestate->es_top_eflags;
2776 estate->es_instrument = parentestate->es_instrument;
2777 /* es_auxmodifytables must NOT be copied */
2780 * The external param list is simply shared from parent. The internal
2781 * param workspace has to be local state, but we copy the initial values
2782 * from the parent, so as to have access to any param values that were
2783 * already set from other parts of the parent's plan tree.
2785 estate->es_param_list_info = parentestate->es_param_list_info;
2786 if (parentestate->es_plannedstmt->nParamExec > 0)
2788 int i = parentestate->es_plannedstmt->nParamExec;
2790 estate->es_param_exec_vals = (ParamExecData *)
2791 palloc0(i * sizeof(ParamExecData));
2794 /* copy value if any, but not execPlan link */
2795 estate->es_param_exec_vals[i].value =
2796 parentestate->es_param_exec_vals[i].value;
2797 estate->es_param_exec_vals[i].isnull =
2798 parentestate->es_param_exec_vals[i].isnull;
2803 * Each EState must have its own es_epqScanDone state, but if we have
2804 * nested EPQ checks they should share es_epqTuple arrays. This allows
2805 * sub-rechecks to inherit the values being examined by an outer recheck.
2807 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2808 if (parentestate->es_epqTuple != NULL)
2810 estate->es_epqTuple = parentestate->es_epqTuple;
2811 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2815 estate->es_epqTuple = (HeapTuple *)
2816 palloc0(rtsize * sizeof(HeapTuple));
2817 estate->es_epqTupleSet = (bool *)
2818 palloc0(rtsize * sizeof(bool));
2822 * Each estate also has its own tuple table.
2824 estate->es_tupleTable = NIL;
2827 * Initialize private state information for each SubPlan. We must do this
2828 * before running ExecInitNode on the main query tree, since
2829 * ExecInitSubPlan expects to be able to find these entries. Some of the
2830 * SubPlans might not be used in the part of the plan tree we intend to
2831 * run, but since it's not easy to tell which, we just initialize them
2834 Assert(estate->es_subplanstates == NIL);
2835 foreach(l, parentestate->es_plannedstmt->subplans)
2837 Plan *subplan = (Plan *) lfirst(l);
2838 PlanState *subplanstate;
2840 subplanstate = ExecInitNode(subplan, estate, 0);
2841 estate->es_subplanstates = lappend(estate->es_subplanstates,
2846 * Initialize the private state information for all the nodes in the part
2847 * of the plan tree we need to run. This opens files, allocates storage
2848 * and leaves us ready to start processing tuples.
2850 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2852 MemoryContextSwitchTo(oldcontext);
2856 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2857 * or if we are done with the current EPQ child.
2859 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2860 * of the normal cleanup, but *not* close result relations (which we are
2861 * just sharing from the outer query). We do, however, have to close any
2862 * trigger target relations that got opened, since those are not shared.
2863 * (There probably shouldn't be any of the latter, but just in case...)
2866 EvalPlanQualEnd(EPQState *epqstate)
2868 EState *estate = epqstate->estate;
2869 MemoryContext oldcontext;
2873 return; /* idle, so nothing to do */
2875 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2877 ExecEndNode(epqstate->planstate);
2879 foreach(l, estate->es_subplanstates)
2881 PlanState *subplanstate = (PlanState *) lfirst(l);
2883 ExecEndNode(subplanstate);
2886 /* throw away the per-estate tuple table */
2887 ExecResetTupleTable(estate->es_tupleTable, false);
2889 /* close any trigger target relations attached to this EState */
2890 foreach(l, estate->es_trig_target_relations)
2892 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2894 /* Close indices and then the relation itself */
2895 ExecCloseIndices(resultRelInfo);
2896 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2899 MemoryContextSwitchTo(oldcontext);
2901 FreeExecutorState(estate);
2903 /* Mark EPQState idle */
2904 epqstate->estate = NULL;
2905 epqstate->planstate = NULL;
2906 epqstate->origslot = NULL;